Multiple Operation & Conditions Lesson 22 to 26 Python Core
Note:
For example, the string "Hello" can be thought of as a list, where each character is an item in the list. The first item is "H", the second item is "e", and so on.
Items.count
For example, you can count how many 42s are there in the list using: items.count(42) where items is the name of our list.
words = ["Hello", "world", "!"] print(words[0]) print(words[1]) print(words[2])
Hello world !
Note: Keyboard
In console, you can stop the program's execution by using the Ctrl-C shortcut or by closing the program.
Note for empty_list
In some code samples you might see a comma after the last item in the list. It's not mandatory, but perfectly valid.
List
Lesson 23.1
List Operations
Lesson 24
List Function
Lesson 25.1
Which line of code will cause an error? num = [5, 4, 3, [2], 1] print(num[0]) print(num[3][0]) print(num[5]) Line 4 Line 2 Line 3
Line 4
What is the result of this code? x = 4 y = 2 if not 1 + 1 == y or x == 4 and 7 == 8: print("Yes") elif x > y: print("No") Yes No
No
What is the result of this code? if 1 + 1 * 3 == 6: print("Yes") else: print("No") Yes No
No
grade = 88 if(grade >= 70 and grade <= 100): print("Passed!")
Passed!
NOTE>
Python's order of operations is the same as that of normal mathematics: parentheses first, then exponentiation, then multiplication/division, and then addition/subtraction.
list.remove(item):
Removes an object from a list
list.count(item):
Returns a count of how many times an item occurs in a list
min(list):
Returns the list item with minimum value
max(list):
Returns the list item with the maximum value
list.reverse():
Reverses items in a list.
String behaves
Some types, such as strings, can be indexed like lists. Indexing strings behaves as though you are indexing a list containing each character in the string.
Note >
Space (" ") is also a symbol and has an index. Trying to access a non-existing index will produce an error.
The code below uses an if/else statement inside a while loop to separate the even and odd numbers in the range of 1 to 10: x = 1 while x < 10: if x%2 == 0: print(str(x) + " is even") else: print(str(x) + " is odd") x += 1
1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd
What is the result of this code? nums = [1, 2, 3, 4, 5] nums[3] = nums[1] print(nums[3])
2
letters = ['p', 'q', 'r', 's', 'p', 'u'] print(letters.index('r')) print(letters.index('p')) print(letters.index('z'))
2 0 Traceback (most recent call last): File "file0.py", line 4, in <module> print(letters.index('z')) ValueError: 'z' is not in list
How many numbers does this code print? i = 5 while True: print(i) i = i - 1 if i <= 2: break
3
What is the result of this code? letters = ["a", "b", "c"] letters.append("d") print(len(letters))
4 After the 2nd statement, "d" is added to the list. So, letters contains 4 items.
How many numbers does this code print? i = 3 while i>=0: print(i) i = i - 1
4 Answer 4 and out put should be 3 2 1 0 Like this 4times
What is the result of this code? nums = [5, 4, 3, 2, 1] print(nums[1])
4 In a list it goes from 0, 1, 2, 3, 4, 5 so 4 is 1 in number order of list computer generate.
nums = [1, 3, 5, 2, 4] print(len(nums))
5
m = [ [1,2,3], [4,5,6] ] print(m[1][2])
6
What is the result of this code? nums = [10, 9, 8, 7, 6, 5] nums[0] = nums[1] - 5 if 4 in nums: print(nums[3]) else: print(nums[4])
7 9-5 == 4 condition is true so it will print 3rd number of array [10,9,8,7,6,5] [0,1,2,3,4,5] answer is 7
What is the result of this code? nums = [9, 8, 7, 6, 5] nums.append(4) nums.insert(2, 11) print(len(nums))
7 Inserting 2 and 11 into list will be 2, 5, 6, 7, 8, 9, 11 total is 7
List Square Brackets & commas
A list is created using square brackets with commas separating items. words = ["Hello", "world", "!"]
matrix
A matrix-like structure can be used in cases where you need to store data in row-column format. For example, when creating a ticketing program, the seat numbers can be stored in a matrix, with their corresponding rows and numbers.
Operator precedence
A very important concept in programming. It is an extension of the mathematical idea of order of operations (multiplication being performed before addition, etc.)
While Loops
A while loop is used to repeat a block of code multiple times.
An example use case of break:
An infinite while loop can be used to continuously take user input. For example, you are making a calculator and need to take numbers from the user to add and stop, when the user enters "stop".
Elements note: Shifted Right
Elements, that are after the inserted item, are shifted to the right.
Append method
The append method adds an item to the end of an existing list.
Note on code
The code above outputs the 3rd item of the 2nd row.
Notes>
The code in the body of a while loop is executed repeatedly. This is called iteration.
Note :
The dot before append is there because it is a method of the list class. Methods will be explained in a later lesson.
Note: in operator
The in operator is also used to determine whether or not a string is a substring of another string.
Index method
The index method finds the first occurrence of a list item and returns its index.
Insert Method
The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end.
words = ["Python", "fun"] index = 1 words.insert(index, "is") print(words)
['Python', 'is', 'fun']
nums = [1, 2, 3] print(nums + [4, 5, 6]) print(nums * 3)
[1, 2, 3, 4, 5, 6] [1, 2, 3, 1, 2, 3, 1, 2, 3]
nums = [1, 2, 3] nums.append(4) print(nums)
[1, 2, 3, 4]
nums = [7, 7, 7, 7, 7] nums[2] = 5 print(nums)
[7, 7, 5, 7, 7] It replace the middle number 0, 1, 2, 3, 4, 5
empty_list = [] print(empty_list)
[]
Lists
are used to store items.
continue
continue jumps back to the top of the loop, rather than stopping it
Which statement ends the current iteration and continues with the next one?
continues
Note >>>
he first list item's index is 0, rather than 1, as might be expected.
Fill in the blanks to create a list, reassign its 2nd element and print the whole list. nums = [33, 42, 56__ nums[____] = 22 print(______)
nums = [33, 42, 56] nums[ 1 ] = 22 print(nums)
str(x)
str(x) is used to convert the number x to a string, so that it can be used for concatenation.
str = "Hello world!" print(str[6])
w
What is the result of this code? words = ["hello"] words.append("world") print(words[1]) An error occurs hello world
world
Fill in the blanks to create a loop that increments the value of x by 2 and prints the even values. x = 0 ________x <=20___ ____________(x) x += 2
x = 0 while x <=20: print (x) x += 2
i = 0 while 1==1: print(i) i = i + 1 if i >= 5: print("Breaking") break print("Finished")
0 1 2 3 4 Breaking Finished
number = 3 things = ["string", 0, [1, 2, number], 4.56] print(things[1]) print(things[2]) print(things[2][2])
0 [1, 2, 3] 3
How many items are in this list? [2,] Choice 3 1 2
1
i = 1 while i <=5: print(i) i = i + 1 print("Finished!")
1 2 3 4 5 Finished!
i = 0 while i<5: i += 1 if i==3: print("Skipping 3") continue print(i)
1 2 Skipping 3 4 5
Break
To end a while loop prematurely, the break statement can be used.
print(False == False or True) print(False == (False or True)) print((False == False) or True)
True False True
nums = [1, 2, 3] print(not 4 in nums) print(4 not in nums) print(not 3 in nums) print(3 not in nums)
True True False False
words = ["spam", "egg", "spam", "sausage"] print("spam" in words) print("egg" in words) print("tomato" in words)
True True False
Len Function
Unlike the index of the items, len does not start with 0. So, the list above contains 5 items, meaning len will return 5.
Note: Break error
Using the break statement outside of a loop causes an error.
Continue error : Note
Using the continue statement outside of a loop causes an error.
Chaining Multiple Condition
You can chain multiple conditional statements in an if statement using the Boolean operators.
Note>>
You can use multiple and, or, not operators to chain multiple conditions together.
Len function Note:
len is written before the list it is being called on, without a dot.
Fill in the blanks to print "Yes" if the list contains 'z': letters = ['a', 'b', 'z'] ______ "z"_____ letters: print("Yes")
letters = ['a', 'b', 'z'] if "z" in letters: print("Yes")
Drag and drop from the options below to add 'z' to the end of the list and print the list's length. list.______('z') print(_______ _______)
list . append ('z') print( len (list) )
Fill in the blanks to create a list and print its 3rd element. list =__42, 55, 67] print(list[____])
list =[ 42, 55, 67 ] print( list [ 2 ])