1/61
week 2,3 & 4
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Conditional Expressions Overview
allows programs to make decision based on whether they true or not
relational operators.
used to compare two values
they return boolean value
examples of rational operators
>
<
>=
<=
== checks if values are equal
= used for assignment
!=
boolean operators
and true, if both operands are true
or true if at least one is true
not , true if operands is false, false if operands is true
Operator Precedence
Now that we have seen how operators can be mixed, we need precedence rules for all operators
▪ () (highest precedence – performed first)
▪ **
▪ * / // %
▪ + -
▪ < <= >= > == !=
▪ not
▪ and
▪ or (lowest precedence – performed last)
De Morgan’s Laws
2 rules for boolean
1st rule Not(A and B) —> Not A or Not B
2nd rule Not (A or B) —> Not A and Not B
BOOLEAN
binary value that can either be true or false
Conditional (relational) expression
expression that converts values using relational or conditional operators
Iteration
executing the same basic task multiple times
allows repetition many times without having to type the same statement many times
Counter-Controlled Loops
repeats a block of code for specific number of times
In Python, this is typically implemented with the for
loop and the range()
function.
note
range(n) —> start from 0 and stop before n
range(start, stop, step) —> start from start, stop before stop and add a step
Print numbers 1 to 5 using a counter-controlled loop
for counter in range(1, 6):
print(counter)
#1 2 3 4 5
Condition-Controlled Loops
used when we don’t in advance how many times a loop should repeat
Count-Controlled Loop (for
loop)
you know in advance how many times you want the loop to repeat
for variable in range(start, stop, step)
Condition-Controlled Loop (while
loop)
Use it when:
You don’t know how many times the loop should repeat ahead of time.
The loop should continue based on a condition being true
i = 0
while i < 5:
print("Count is:", i)
i += 1
What Is a Post-Check Loop?/do-while loop
runs at least once
Infinite Loops
loop that never end unless stopped manually or broken from inside
The break
Statement
stops when a certain condition is met
exit the loop
while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
print("You entered:", num)
The continue
Statement
skips the rest of the loop for the current iteration and goes to the next one
for i in range(1, 6):
if i == 3:
continue # Skip 3
print(i)
result
1
2
4
5
The else
Statement (with loops)
the else statement after break wont print
The pass
Statement
does nothing
pass
placeholder that does nothing
array
data structure that stores values accessible under index
it can hold different types of data
called a list
index
position
Arrays can be fixed length or variable length
fixed array cannot be changed
variable array can be altered
x.append
adds an item to the end of a list
x.remove
removes an item from the list
print(x[index])
accessing position of a number in a list
print(x[-1])
accessing the last item in a list
x[index] = new item
changing old item into a new item
Iterating over items in list
when you don’t need to know the indexes
for a in X:
print(a)
when you need to know indexes
for n in range (len (X)):
print(n, X[n])
Common Pitfall/Error
accessing an item that is not in the list
IndexError:
list index is out of range
Merging lists (concatenation)
adding list
list1[1, 2 ] + list2[3, 4 ]
= [1, 2, 3, 4]
Checking for item (membership)
checking an item a from list
X = [1, 2, 3]
print(2 in X)
print(5 in X)
true
false
Multiplying content of lists (repetition)
repeating content in a list
list1[1, 2]
list1×2
=[1, 2, 1, 2]
Access List Item (Indexing)
list = [1, 2, 3, 4, 5]
print(list[2])
3
Get Length of List (Length)
use len
list = [1, 2, 3, 4, 5]
print(len(list))
5
DELETE
del(list)
different from remove
= [10, 20, 30, 40]
del X[1] # Deletes the item at index 1
print(X)
[10, 30, 40]
but then remove removes an item
X = [10, 20, 30, 40]
X.remove(20) # Removes the value 20
print(X)
[10, 30, 40]
Get Slice of List (Slicing)
x[start, stop, step]
Iterate Over List (Iteration)
X = [1, 3, 5]
for num in X:
print(num * 2)
2
6
10
Add element to end
x.append
Sort list
x.sort
from smallest to the biggest
Reverse items
X.reverse()
X = [6, 5, 4, 3, 2, 1]
Find position of item
x.index[2]
Insert item at index
x.insert(index, new value)
x.insert(2, 99)
Count occurrences of item
count how many times does an item appear on a list
x.count(2)
it will count how many times does 2 appears
Remove first occurrence of an item
remove the fisrt occurrence of a number
x.remove(99)
Remove and return item at index
x.pop(99)
it will return the position on 99 in the list
Split string into list
x.split(‘,’)
x=“1”, “2”, “3”
[“1”, “2”, “3”]
Split by space (default)
sentence = "Hello world this is ChatGPT"
words = sentence.split()
print(words)
['Hello', 'world', 'this', 'is', 'ChatGPT']
# Join list into string
does similar work to sep
x=[1, 2, 3]
‘*’.join(x)
1*2*3
sep = ‘*’
sep.join(x)
1*2×3
2-Dimensional Arrays
a list of list
x =[ [1, 2], [3, 4]]
x[0] = [1, 2]
x[1] = [3, 4]
x[0][0] = 1 (return an item in row 0 column 0)
x[0][1] = 2
x[1][1] = 1
note
x[0][0]
the first index selects a row
the second index selects a column
multi-dimensional lists
students = [['saleem', ['csc1015f', ['12 april', ['5','6','7']]]]]
solve
x[0][0]
x[0][1][0]
x[0][1][1][0]
x[0][1][1][1]
x[0][1][1][1][2]
Dictionaries
{ }
its immutable
D = {'a': 'apples', 'b': 'bananas', 'p': 'pears'}
'a'
, 'b'
, and 'p'
are the keys, and 'apples'
, 'bananas'
, and 'pears'
are their corresponding values.
D = {'a': 'apples', 'b': 'bananas', 'p': 'pears'}
print(D[‘a]) #apples
D[“b”] = cherry #D = {'a': 'apples', 'b': 'cherry', 'p': 'pears'}
D.keys()
– returns all keys
D.values()
– returns all values
D.items()
– returns key-value pairs
for key, value in fruits.items():
print(key, ":", value)
a : apples
b : bananas
p : pears
Remove a key and return its value
removed = fruits.pop('p')
print(removed) # Output: pears
print(fruits) # Output: {'a': 'apples', 'b': 'bananas'}
Remove all items
fruits.clear()
print(fruits) # Output: {}
generic (or nested) data structures
you can combine lists dicts and tuples ect.
Dictionary of Lists
D = {
'kayleigh': [12, 23, 31],
'callum': [45, 54, 55]
}
print(D['kayleigh']) # Output: [12, 23, 31]
print(D['callum'][1]) # Output: 54
D['kayleigh'].append(42)
print(D['kayleigh']) # Output: [12, 23, 31, 42]
'kayleigh and callum are key
and the lists are values
List of Dictionaries
E = [
{'name': 'palesa', 'year': 1},
{'name': 'luqmaan', 'year': 1}
]
print(E[0]['name']) # Output: palesa
print(E[1]['year']) # Output: 1
E.append({'name': 'samira', 'year': 2})
[
{'name': 'palesa', 'year': 1},
{'name': 'luqmaan', 'year': 1},
{'name': 'samira', 'year': 2}
]