Python Cheat Notebook
This notebook contains Python code with reduced comments
# I'm a comment! When there is text after a hashtag, that text does not affect the code.
print("Hi")
5 + 5 #addition
5 * 5 #multiplication
5 / 5 #division
5 ** 2 #exponentiation
4 % 2 #modulus
5 % 2 #modulus
(5 + 5) * (5 -1) #operations order
4/5 #numbers with decimal places are called "float"
'I am a string' #you can create a string with single quotes
"I am also a string" #you can create a string with double quotes
"I am a string with 'single quotes'" #to use single quotes within the string, the string is created in double quotes.
'I am a string with "double quotes"'#to use double quotes inside the string, the string is created in single quotes.
print("I am a string".title()) # .title() makes the first letter of each word capitalized
print("I am A string".lower()) # .lower() makes all letters lowercase
print("i Am a string".upper()) # .upper() makes all letters capitalized
True #true
False #false
1 > 2 # false
1 < 2 # true
10 >= 10 # greater than or equal (true for the condition)
10 <= 40 # less than or equal (true for the condition)
1 == 1 #true
'words' == 'word' #false
'word' == 'word' #true
(50 > 100) and (100 < 300) # and (both conditions must be satisfied)
(10 > 20) or (20 < 30) # or (only one of the conditions needs to be met)
(10 == 10.5) or (2 == 3) or (4 == 4)
if 10 < 20:
print('Corret!') # condition satisfied, the result will be printed
if 1 < 2:
print("One is less than two!") # condition satisfied, the result will be printed
if 1 < 2:
print('Correct') # condition satisfied, the result will be printed
else:
print('Incorrect')
if 1 > 2:
print('Correct')
else:
print('Incorrect') # condition not satisfied, the "else" result will be printed
if 1 == 2:
print('first condition')
elif 3 == 3:
print('second condition')
else:
print('None of the conditions') # the second condition is true
variable = 20 # defines that 20 will be stored in the 'variable' word
variable # "calling" the variable
two = 2
word = 'words' #defining more than one variable
age = 25
name = 'John'
print(age,name)
print('My name is: {}, my age is: {}'.format(name,age))
# With {} and .format () you replace text with variables:
print(f'My name is: {name}, my age is: {age}')
# you can also format a string with and f before it and the variables inside {}
It is also possible to create variables from the values of other variables:
x = 2
y = 3
z = x + y #z is the sum of x and y, which can be any values (2 and 3 in this case).
z
[5,10,15] # lists are written with []
['words',5,(5*5),name] # it is possible to store different types of data
You can add an item to the list:
my_list = ['a','b','c'] #a variable (my_list) that contains a list
my_list.append('d') #append adds an item to the list
my_list # the list after appending
my_list[0] #0 calls the list's first item
my_list[1] #1 calls the list's second item
my_list[1:] # What comes before the colon is the starting point of the selection.
# In this case, the second item is selected until the last
my_list[:2] # What comes after the colon is the arrival point of the selection.
# In this case, it is selected from the first item to the third [2]
my_list[0] = 'NEW' # replaces the element
my_list # list after replacing
del my_list[2] # deletes the list's third item
my_list # list after the remotion
len(my_list) # checks the number of items in the list.
nested = [1,2,3,[4,5,['hello',"guys"]]] # It is possible to store lists within lists (nested list)
# The [] within the list create other list
nested[3] # the fourth item on the nest list is also a list
nested[3][2] # finds the element within the list stored in the "nested" list
nested[3][2][0] # finds the first element within the list that was stored within the "nested" list
d = {'key1':'item1','key2':'item2'} # dictionaries are created with {} and have keys and values
d # calling the dictionary
d['key1'] # here we call the value stored in key1
d['key3']="item3" # it is also possible to add keys and values to the dictionary, as in the example.
d # the dictionary after adding the key3
Tuples
t = (1,2,3) # tuples are created with () and are immutable
t[0]
t[0] = 'NEW' # it is not possible to change it, so an error will occur!
my_list = [1,2,3,4,5,"hello",'world'] # creating a new list with integers and strings
for item in my_list: # in this for loop, each item in the list is printed.
print(item)
for item in my_list: # in this for loop, for each recognized list item you are asked to print the word "Looping"
print('Looping')
for i in my_list: #in this for loop, each element of the list is multiplied by 2.
print(2*i) #It is important to realize the difference between the behavior of the operator with numbers and strings.
i = 1
while i < 5: #as long as the requested condition is true (i less than 5), the loop will be executed.
print('i is: {}'.format(i))
i = i+1
i = 3
while i < 7: # as long as the condition is true (i less than 7),
print('i is: {}'.format(i)) # the loop will be executed. i is updated at the end of the loop
i = i+1
range(0,5) #defines an intervalo
for i in range(0,5): # defines that the loop will be executed while i is within the range
print("The number is: {} ".format(i))
list(range(2,7)) # turns the range into a list of values
x = [1,2,3,4] # creates a new list
out = [] # here a loop is created to raise the elements of list x to the power of 2.
for item in x:
out.append(item**2)
print(out)
[item**2 for item in x] # here we have a pythonic way to accomplish the same task, with just one line of code
def my_func(phrase): #def is the word used to create the function. After that,
print(phrase) #the function name comes and the parameters come inside the parenthesis.
#In this case, we create a function that will print the sentence we want.
my_func("Hello World") #The phrase is "Hello World"
my_func("I'm in the Data Science Bootcamp") #With another phrase
def multiply_by_2(x): #In this case, we create a function that multiplies by 2.
return x*2
result = multiply_by_2(5) # Applying the function to a number
result
word_2 = multiply_by_2('Hi ') # It can be applied with strings too, but the behavior is different.
word_2
def complex_function(x,y,z): #x,y,z are parameters
s = x+y+z # the function creates the s variable
m = x*y*z # the function creates the m variable
print("The sum of x, y and z is: ", s) # the function prints the results
print("The multiplication of x, y and z is: ", m)
complex_function(5,2,3)
class Person: #creates the class
def __init__(self,name,age,profession): #initiates the class
self.name=name #defines atributes
self.age=age
self.profession=profession
def historic(self): #creates a method, a function designated specifically to the class created
print("The object {} us {} years old and is a {}!".format(self.name,self.age,self.profession))
soccer_player = Person("John",150,"soccer_player") #creates an instance of the Person class
journalist = Person("Mary",235,"journalist")
soccer_player.age #shows one of the atributes
soccer_player.historic() #applies the created method to one of the instances
journalist.historic() #applies the created method to one of the instances
