Python Building Blocks AY23 24
Python Building Blocks AY23 24
5 in [1, 2, 3, 4, 6]
# ============================================================= "Hello."[:4] # b 5 not in [1, 2, 3, 4, 6]
# Data types "Hello."[:] ~
hit # Lay
S
# ============================================================= len([8.4, 2, 7])
326
326.2
# int or integer: integer values
# float or floating point number: decimal values
# Membership operators
"lick" in "click"
string who in/not in shington. min([8.4, 2, 7]) E
max([8.4, 2, 7]) = 8 .
4
.
"Hello." # string holds a text "I" in "team" sum([8.4, 2, 7])
order). [C , 4).
False # bool or boolean value: holds one of the values True or False
O "I" not in "team" sorted([8.4, 2, 7]) (put them in = 7 ,
8 .
False 'C'.
=
1 max('a', 'c', 'b')
# ============================================================= # ============================================================= min(True, False) =
S
# ============================================================= # ============================================================= letters = ['a', 'b', 'c', 'd']
# Arithmetic operators: + - * / // ** % letters.append('e')
4 + 1 # Checking the type letters.remove('a')
+ print (letters)
300 - 120 type(326) int =
I'a' , 'b' ,
'd,'d''y' ,
21] letters.extend(['y', 'z'])
3 * 7 type(326.2) float
I
letters.pop() remove last item !
19 / 4 =4 75
19 // 4 : chin o
,
doo
lay phan
4
.
type("Hello.")
type(False) I
Shing
a = I [1, 2] + [3, 4]
[1, 2] * 3
Elab pa rs'
= =
-
5 ** 2 Tra= # Type conversions lines = "\n".join(["line 1", "line 2", "line 3", "line 4"]) + print (lines) = line I
9 + 0 , 12) /2
17
(20 - 3**2 + 0.12) / 2 (20 5 , 56 int(True) [1, 2, 3, 4][::-1] Reverse the order ! wine 2
=
. =
-
=
s
float("7.2") 2 I .
=
[4 , 5 2 , 1]
,
> comuyset[o]
(
rectangle_width = 3.2 # variable name: descriptive of the values it holds boot (" 1) False . be there is Mo order
Es
=
a = 12 a %= 2 = a 1 =
# %2
equivalent to a = a // round(3.141592, 2) 5 14 .
country_set.remove('Belgium')
a **= 2 # equivalent to a = a ** 2 pow(2,10) C 1024. =
=
country_set.pop()
set('ABCD')
# Comparison operators: < > <= >= == != # =============================================================
a == b (xda b ? ) so sant
= :
Ex for · =: a = 12 # Methods a, b = {1, 2, 3}, {2, 3, 4}
a != b
b = 6
# ============================================================= c = a.intersection(b) 92 , 33 =
checkHyamea ho
a <= b ↓ "happy new year".islower() f c = a | b # union
a >= b
ES (v
a < b and a < c "Happy New Year".count("p") empty_dict = {}
a < b or a == c "Happy New Year".find("y") tri( empty_dict = dict()
not a "Happy New Year".startswith("Happy") True elements_dict = {"hydrogen": 1, "helium": 2, "carbon": 6}
2021·
"Happy New Year".replace("New Year", "2021") : 'Happy elements_dict["helium"] C -
Smith &
"
- "My name is {} {} and I'm {} years old.".format("Elizabeth", "Smith", 19)
append) .
"Hello there" diet-keys (t'hy drogen ...., .... ])
....
first_word + " " + second_word lon co !! "We put the {} in {}.".format("cool", "afterschool") elements_dict.values() diet-values ( [1 3 6)] 2
first_word * 5 > phai
= ,
space
items ((l'hydrogen'
, ,
])
- -
"{:.2f}".format(3.141592) = 13 14 .
=============================================================
= : : :
"weight": 4.002602,
"symbol": "He"}}
# Using escape characters: \" \' \\ \t \n # Data structures locations = [(50.85045, 4.34878),
"Tom's skateboard isn't blue." # ============================================================= (48.864716, 2.349014),
'Tom\'s skateboard isn\'t blue.' (51.509865, -0.118092)]
'We are the so-called "Vikings" from the north.' # List locations_dict = {'Brussels': (50.85045, 4.34878),
"We are the so-called \"Vikings\" from the north." empty_list = [] 'Paris': (48.864716, 2.349014),
"first line\nsecond line" empty_list = list() 'London': (51.509865, -0.118092)}
'''first line list_of_random_things = [1, 3.4, 'a string', True]
second line''' list_of_random_things[0] # zero-based indexing # =============================================================
list_of_random_things[1] = -3.4 # Conditional Statements
= [1 ,
-3 4
.
,
la
string ,
incl
print(value) OUTPUT:
# If Statement population_density: population / land_area. The population density of a
phone_balance = 11.81 for key, value in elements_dict.items(): particular area.
bank_balance = 50.24 print("element: {}, atomic number: {}".format(key, value)) """
return population / land_area
if phone_balance < 10: # Do you find writing for loops with list indexes difficult?
phone_balance += 10 # Why go through all the trouble? Here is the lazy man's way. help(population_density)
bank_balance -= 10 letters = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(letters): # Make an argument optional
# If elif else print(index, value) def greet(name, message="Good morning!"):
number = 145 letters[index] = value.upper() """Extend a greeting to a person with the provided message.
if number % 2 == 0:
print("Number " + str(number) + " is even.") # ============================================================= If the message is not provided, it defaults to "Good morning!"
else: # While loops """
print("Number " + str(number) + " is odd.") # ============================================================= print("Hello", name + '. ' + message)
counter = 0
season = 'fall' while counter < 8: greet("Elizabeth")
if season == 'spring': counter += 1 greet("Elizabeth", "How do you do?")
print('plant the garden!') print(counter)
elif season == 'summer': # Using None as a default argument
print('water the garden!') # ============================================================= def greet(name, message=None):
elif season == 'fall': # Functions """Extend a greeting to a person with the provided message.
print('harvest the garden!') # =============================================================
elif season == 'winter': Providing a message is optional.
print('stay indoors!') # Functions performing a task or procedure """
else: def print_greeting(): greeting = "Hello {}.".format(name)
print('unrecognized season') print('Hello!') if message is not None:
greeting += " " + message
# ============================================================= def print_personalized_greeting(name): print(greeting)
# For loops message = 'Hello {}!'.format(name)
# ============================================================= print(message) help(greet)
help(round)
cities = ['new york city', 'brussels', 'paris', 'los angeles'] print_greeting() help(str.strip)
for city in cities: print_personalized_greeting('Elizabeth')
print(city.title()) # =============================================================
print("Done!") # Functions with an output value # Reading and writing files
def add_ten(number): # this returns something # =============================================================
# Create a new list return number + 10
capitalized_cities = [] # reading a text file
for city in cities: def show_plus_ten(number): with open('my_file.txt', 'r') as file:
capitalized_cities.append(city.title()) print(number + 10) # this prints something, but does not return anything file_data = file.read()
lines = file_data.split('\n')
# Built-in range function def cylinder_volume(radius, height):
list(range(8)) pi = 3.141592 lines = []
list(range(2,8)) return height * pi * radius**2 with open('my_file.txt', 'r') as file:
list(range(1,10,2)) for line in file:
cylinder_volume(3, 8) print(line.strip())
# Modify a list cylinder_volume(height=9.75, radius=4.2) lines.append(line.strip())
for index in range(len(cities)):
cities[index] = cities[index].title() # Writing documentation # writing a text file
print(cities) def population_density(population, land_area): with open('my_file.txt', 'w') as file:
"""Calculate the population density of an area.""" file.write('Some text')
# Perform the same action multiple times return population / land_area
for i in range(3): with open('my_file.txt', 'w') as file:
print("Hello there.") def population_density(population, land_area): file.writelines(['Line 1\n', 'Line 2\n', 'Line 3\n'])
"""Calculate the population density of an area.
# Iterating through dictionaries with open('my_file.txt', 'w') as f:
elements_dict = {"hydrogen": 1, "helium": 2, "carbon": 6} INPUT: print('Line 1', 'Line 2', 'Line 3', file=f, sep='\n') # help(print)
population: int. The population of that area
for key in elements_dict: land_area: int or float. This function is unit-agnostic, if you pass in # appending an existing text file
print(key) values in terms of square km or square miles the function will return a with open('my_file.txt', 'a') as file:
density in those units. file.write('appended text\n')
for value in elements_dict.values():