Comments and print()

# I'm a comment! When there is text after a hashtag, that text does not affect the code.
print("Hi")
Hi

Numeric Operations

5 + 5 #addition
10
5 * 5 #multiplication
25
5 / 5 #division
1.0
5 ** 2 #exponentiation
25
4 % 2 #modulus
0
5 % 2 #modulus
1
(5 + 5) * (5 -1) #operations order
40
4/5 #numbers with decimal places are called "float"
0.8

Strings (texts)

'I am a string' #you can create a string with single quotes
'I am a string'
"I am also a string" #you can create a string with double quotes
'I am also a string'
"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 'single quotes'"
'I am a string with "double quotes"'#to use double quotes inside the string, the string is created in single quotes.
'I am a string with "double quotes"'
print("I am a string".title()) # .title() makes the first letter of each word capitalized
I Am A String
print("I am A string".lower()) # .lower() makes all letters lowercase
i am a string
print("i Am a string".upper()) # .upper() makes all letters capitalized
I AM A STRING

Booleans and Comparison Operators

True #true
True
False #false
False
1 > 2 # false
False
1 < 2 # true
True
10 >= 10 # greater than or equal (true for the condition)
True
10 <= 40 # less than or equal (true for the condition)
True
1 == 1 #true
True
'words' == 'word' #false
False
'word' == 'word' #true
True

Connectives

(50 > 100) and (100 < 300) # and (both conditions must be satisfied)
False
(10 > 20) or (20 < 30) # or (only one of the conditions needs to be met)
True
(10 == 10.5) or (2 == 3) or (4 == 4)
True

if, elif, else

if 10 < 20: 
    print('Corret!') # condition satisfied, the result will be printed
Corret!
if 1 < 2:
    print("One is less than two!") # condition satisfied, the result will be printed
One is less than two!
if 1 < 2: 
    print('Correct') # condition satisfied, the result will be printed
else:
    print('Incorrect')
Correct
if 1 > 2: 
    print('Correct') 
else:
    print('Incorrect') # condition not satisfied, the "else" result will be printed
Incorrect
if 1 == 2:
    print('first condition')
elif 3 == 3:
    print('second condition')
else:
    print('None of the conditions') # the second condition is true
second condition

Variables

You can think of variables as words that store a value. That simple:

variable = 20 # defines that 20 will be stored in the 'variable' word
variable # "calling" the variable
20
two = 2
word = 'words'  #defining more than one variable
age = 25
name = 'John'
print(age,name) 
25 John

Format

print('My name is: {}, my age is: {}'.format(name,age)) 
# With {} and .format () you replace text with variables:
My name is: John, my age is: 25
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 {} 
My name is: John, my age is: 25

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

Lists

[5,10,15] # lists are written with []
[5, 10, 15]
['words',5,(5*5),name] # it is possible to store different types of data 
['words', 5, 25, 'John']

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
['a', 'b', 'c', 'd']
my_list[0] #0 calls the list's first item
'a'
my_list[1] #1 calls the list's second item
'b'
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
['b', 'c', 'd']
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]
['a', 'b']
my_list[0] = 'NEW' # replaces the element
my_list # list after replacing
['NEW', 'b', 'c', 'd']
del my_list[2] # deletes the list's third item
my_list # list after the remotion
['NEW', 'b', 'd']
len(my_list) # checks the number of items in the list.
3
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
[4, 5, ['hello', 'guys']]
nested[3][2] # finds the element within the list stored in the "nested" list
['hello', 'guys']
nested[3][2][0] # finds the first element within the list that was stored within the "nested" list
'hello'

Dictionaries

d = {'key1':'item1','key2':'item2'} # dictionaries are created with {} and have keys and values
d # calling the dictionary
{'key1': 'item1', 'key2': 'item2'}
d['key1'] # here we call the value stored in key1
'item1'
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
{'key1': 'item1', 'key2': 'item2', 'key3': 'item3'}

Tuples

t = (1,2,3) # tuples are created with () and are immutable
t[0]
1
t[0] = 'NEW' # it is not possible to change it, so an error will occur!
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-70-9bfd67d608a2> in <module>
----> 1 t[0] = 'NEW' # it is not possible to change it, so an error will occur!

TypeError: 'tuple' object does not support item assignment

Loops - for:

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)          
1
2
3
4
5
hello
world
for item in my_list: # in this for loop, for each recognized list item you are asked to print the word "Looping"
    print('Looping')       
Looping
Looping
Looping
Looping
Looping
Looping
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.
2
4
6
8
10
hellohello
worldworld

Loops - while

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 is: 1
i is: 2
i is: 3
i is: 4
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                      
i is: 3
i is: 4
i is: 5
i is: 6

range()

range(0,5) #defines an intervalo
range(0, 5)
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))
The number is: 0 
The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 
list(range(2,7)) # turns the range into a list of values
[2, 3, 4, 5, 6]

List comprehension

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)
[1, 4, 9, 16]
[item**2 for item in x] # here we have a pythonic way to accomplish the same task, with just one line of code
                        
[1, 4, 9, 16]

Functions

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"
Hello World
my_func("I'm in the Data Science Bootcamp") #With another phrase
I'm in the Data Science Bootcamp
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
10
word_2 = multiply_by_2('Hi ') # It can be applied with strings too, but the behavior is different.
word_2
'Hi Hi '
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)
The sum of x, y and z is:  10
The multiplication of x, y and z is:  30

Classes and functions

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
150
soccer_player.historic() #applies the created method to one of the instances
The object John us 150 years old and is a soccer_player!
journalist.historic() #applies the created method to one of the instances
The object Mary us 235 years old and is a journalist!