0% found this document useful (0 votes)
22 views

Python Building Blocks AY23 24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Python Building Blocks AY23 24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

List is Mutable

### =========================================================== "Hello."[0] # zero-based indexing


-
list_of_random_things[-2] = 'a different string'
### Python Building Blocks "Hello."[-1] # index from the end of the string list_of_random_things[1:3] # lower index: inclusive, upper index: exclusive
### =========================================================== "Hello."[1:3] # lower index: inclusive, upper index: exclusive = [3 4 ,
'a
string']
Laij diel
"Hello."[3:] #
.

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) =

# Operators # Built-in functions max (True ,


False) = True

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'
= =
-

19 % 4 = 5 (phan du) '.'.join(['ab', 'pq', '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]
,

# Assignment operators: = += -= *= /= //= **= %= bool("Hello.") True = # Tuple wine 4


a = 42 # assigning a variable str(False) =False" location = (50.85045, 4.34878)

> comuyset[o]
(

rectangle_width = 3.2 # variable name: descriptive of the values it holds boot (" 1) False . be there is Mo order
Es
=

a, b, c = 42, 7 , 16.2 # assigning multiple variables # Other built-in functions # set


a += 2 # equivalent to a = a + 2 print("Hello.") = Hello empty_set = set()
a -= 2 # equivalent to a = a - 2 print(8, -27.43) 8 27 43 country_set = {'Germany', 'Belgium', 'Brazil', 'Sweden'}
[country_set = set(['Germany', 'Belgium', 'Brazil', 'Sweden', 'Germany'])
-
= .

a *= 2 # equivalent to a = a * 2 input("What is your name? ")


a /= 2 # equivalent to a = a / 2 len("Hello.") 6 O
country_set.add('Ireland')
-
D !
co append only
=
> Set
a //= 2 # equivalent to a = a // 2 abs(-15.1) 1 15 11 15 'Belgium' in country_set I ,
==
-
-
=

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 =

a < b c = a & b # insersection


a > b > a = 2b # O
String methods c = a.union(b) = E
,
-
-

checkHyamea ho
a <= b ↓ "happy new year".islower() f c = a | b # union
a >= b

# Logical operators: and or not


value
of b is
assigned to b. "HAPPY NEW YEAR".isupper()
"happy new year".title()
"Happy New Year".lower()
ed
c = a.difference(b)
c = a - b # difference [13 => why not 7 4 ?
c = a.symmetric_difference(b)
)
=
,
=
[Cb difference(a) =4
92 , 43 3
Face
=
True and False I "Happy New Year".upper() c = a ^ b # symmetric difference
'Happy
Happy
True or False "happy new year".capitalize()
year
, new
=
=

not True False


=
" Happy New Year \t \n".strip() new year ! # Dictionary

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 -

# String operators: + * "911".isnumeric() True = elements_dict["lithium"] = 3 = add element to diet


is Elizabeth
first_word = "Hello"
second_word = "there" "My name

Smith &
"
- "My name is {} {} and I'm {} years old.".format("Elizabeth", "Smith", 19)

"We put the {} in {}.".format("mock", "democracy")


"lithium" in elements_dict
= TRUE .

(dictionary has No add .


MOR ·

append) .
"Hello there" diet-keys (t'hy drogen ...., .... ])
....

first_word + second_word = "We put the {} in {}.".format("YOU", "YOUnique") elements_dict.keys() = I

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'
, ,

])
- -

"{} {} {} {}.".format("We", "are", "learning", "Python") elements_dict.items() diet 1) , ('Wulium' 2)


....
Hello Hello
= _
, , ,
....

"{:.2f}".format(3.141592) = 13 14 .

# ============================================================= '{:02d}'.format(8) 8 = # Compound data structures


# Strings ' '.join(['Elizabeth', 'Smith']) 'Elizabeth Smith' = elements_dict = {"hydrogen": {"number": 1,
'B' 'C' , 'D']
-
# ============================================================= "A B C D".split() I L Al "weight": 1.00794,
# The empty string "A:B:C:D".split(':')
I
I'A' , 'B' 'C' 'D'] =
,
dief in die "symbol": "H"},
5. "A
, ,
"" "line1\nline2\nline3".split() "helium": {"number": 2,
''
#
: BSplit)
: c [A B C D']
: D" :

=============================================================
= : : :
"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

& list-of-rondom-things True


# Indexing and slicing list_of_random_things[-1] # index from the end of the list = # =============================================================

= [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():

You might also like