WHILE LOOP
a = 100 while (a <= 100 and a > 0): print(a) a = a - 1
(TRYIT: Modify your code such that the condition will never return true, then make a syntax error in the print statement - did you get an error? what is the conclusion?)
You can add else statement to while loop, the else statement will be executed once when the while condition is not met.
You can add else statement to while loop, the else statement will be executed once when the while condition is not met.
a = 10 while (a <= 10 and a > 0): print(a) a = a - 1 else: print("Done with the loop")
a = 10 while (a > 10 and a > 0): print(a) a = a - 1 else: print("Done with the loop")
FOR LOOP
For loop in Python is an iterator based loop that iterates through sequences of numbers, characters in a string, etc.
for letter in "Python": print(letter) for number in range(1,10): print(number)
built-in range() function (https://github.com/gnurmatova/Python/blob/master/lecture1/Range.py)
the start parameter is included in the iteration, the end parameter is not.
the start parameter is included in the iteration, the end parameter is not.
print("for number in range(1,5):") for number in range(1,5): print(number) print("for number in range(5):") for number in range(5): print(number) print("for number in range(1,13,4):") for number in range(1,13,4): print(number)
Output:
$ python range.py for number in range(1,5): 1 2 3 4 for number in range(5): 0 1 2 3 4 for number in range(1,13,4): 1 5 9
>>> for number in range(10, 0, -1): ... print(number) ... 10 9 8 7 6 5 4 3 2 1
In Class Exercise:
Write a program that prints first 100 odd numbers, starting at 0
break - breaks the loop and stops any execution
continue - skips any remaining commands in the specific iteration
continue - skips any remaining commands in the specific iteration
print("BREAK") for number in range(1,10): if number == 7: break print(number) print("CONTINUE") for number in range(1,10): if number == 7: continue print(number)
Output:
$ python break.py BREAK 1 2 3 4 5 6 CONTINUE 1 2 3 4 5 6 8 9
READING USER INPUT
Use input() function to read the user input into a variable. The value read will be returned as a string
name=input("What is your Name? ") print("Hello " + name + " It's so nice to meet you!")
Output:
$ python user_input.py What is your Name? Gula Hello Gula It's so nice to meet you!
In class exercise:
Write a program that prompts for 2 numbers and prints their sum, sample output
$ python user_input_sum.py a:2 b:3 The sum of A and B is 5
LISTS and SLICING
Lists in Python are very similar to arrays in Java and C - it is an ordered collection of objects
>>> x = [1,2,3] >>> x[0] 1
Variable can be passed as a list value:
>>> w=9 >>> x=[1,2,3,w] >>> x [1, 2, 3, 9]
Length of list:
>>> x=[1,2,3,4] >>> len(x) 4
Unlike arrays in Java and C, lists can contain elements of different type:
>>> x = [1, "two", 3.3, [1,2,3,4]] >>> x[1] 'two' >>> x[2] 3.3 >>> x[3] [1, 2, 3, 4]
Like with string, the indices can be negative:
>>> x [-1] [1, 2, 3, 4]
You can also extract a range of indices using Slice notation:
>>> x[1:-1] ['two', 3.3]
Reverse order does not work:
>>> x = [1, "two", 3.3, [1,2,3,4]] >>> x[-1:1] []
Leaving out the end index means last index
>>> x[0:] [1, 'two', 3.3, [1, 2, 3, 4]]
in operator validates if an element belongs to a list:
>>> x=[1,2,3] >>> 3 in x True >>> 6 not in x True
concatenating Lists:
>>> [1,2,3]+[4,5,6] [1, 2, 3, 4, 5, 6]
keep in mind that lists do not have to have unique elements:
>>> [1,2,3,4]+[4,5,6,7] [1, 2, 3, 4, 4, 5, 6, 7]
You do not need to allocate the List size ahead of time, however, if you do, it may add efficiency as later on Python will not need to reallocate the memory for your List as it grows:
Note: None is equivalent to null in other programming languages
>>> x=[None]*4 >>> x [None, None, None, None] >>> x[1]=9 >>> x [None, 9, None, None]
min() and max() functions:
>>> x=[5,2,9,5,3,10,1] >>> min(x) 1 >>> max(x) 10
>>> x =['apple', 'melon', 'banana', 'Apricot'] >>> min(x) 'Apricot' >>> max(x) 'melon'
index() method of List returns a position of the passed element:
>>> x=[1, 3.33, "apple", 'c'] >>> x.index(3.33) 1 >>> x.index("apple") 2
In Class Exercise:
What happens if we pass an element that is not in the list to the index function?
If the element is repeated in the list then only the index of the first occurrence is returned
>>> x=[1,3,4,3,5] >>> x.index(3) 1
You can pass the index to start searching at as a second parameter:
>>> x=[1,3,4,3,5] >>> x.index(3,2) 3
In Class Exercise
String Rotation Problem:
leetcode.com/problems/rotate-string/
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to the rightmost position.
For example, if A = 'abcde', then it will be 'bcdea' after one shift on A.
Return True if and only if A can become B after some number of shifts on A.
Example 1: Input: A = 'abcde', B = 'cdeab'
Output: true
Example 2: Input: A = 'abcde', B = 'abced'
Output: false
Note:
- A and B will have length at most 100.
SOLUTION:
- Note that index function throws an exception if substring is not found
- if the lengths of the two strings don't match, then return False off the bat
- A+A creates all possible combinations of the rotation of the A string and if B is present as a substring in that rotation, return True
class Solution: def rotateString(self, A: str, B: str) -> bool: if len(A) != len(B): return False res = 1 try: (A+A).index(B) except: res = 0 return bool(res)
count() method returns the count of times the passed element is found in the List:
>>> x=[6,6,5,4,3,2,2,2] >>> x.count(2) 3 >>> x.count(6) 2
Unlike with Strings, you can use the index notation to modify the lists
>>> x=[1,2,3,4] >>> x[1]=100 >>> x [1, 100, 3, 4]
You can use the slice notation to modify section of a List:
Append to the beginning of a list
>>> x=[1,2,3] >>> x[:0]=[100,200] >>> x [100, 200, 1, 2, 3]
Remove elements from the list:
>>> x=[1,2,3] >>> x[0:2]=[] >>> x [3]
append() method - appends a single element at the end of the list:
>>> x=[1,2,3] >>> x.append(4) >>> x [1, 2, 3, 4] >>> x.append([5,6,7]) >>> x [1, 2, 3, 4, [5, 6, 7]]
extend() allows to extend one list with another
>>> x=[1,2,3] >>> x.extend([5,6,7]) >>> x [1, 2, 3, 5, 6, 7]
insert() inserts an element at a given position, first parameter is the index where the element should be inserted, second is the element
>>> x=[1,2,3] >>> x.insert(0,4) >>> x [4, 1, 2, 3]
like append(), insert does not merge lists, but inserts one into another:
>>> x=[1,2,3] >>> x.insert(0,[5,6,7]) >>> x [[5, 6, 7], 1, 2, 3]
use del() to delete elements from a list
>>> x=[1,2,3] >>> del x[0] >>> x [2, 3] >>> x=[0,1,2,3,4,5,6,7,8,9] >>> del x[0] >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> del x[:2] >>> x [3, 4, 5, 6, 7, 8, 9] >>> del x[3:5] >>> x [3, 4, 5, 8, 9] >>> del x >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined
remove() method of the List class looks for the first occurrence of the passed element and removes it:
>>> x=[3,4,3,4,3,4] >>> x.remove(3) >>> x [4, 3, 4, 3, 4]
reverse() method reverses a list:
>>> x=[1,2,3,4] >>> x.reverse() >>> x [4, 3, 2, 1]
Strides:
Strides let you take every n-th element when slicing a sequence
>>> a = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] >>> odds = a[::2] >>> odds ['red', 'yellow', 'blue'] >>> evens = a[1::2] >>> evens ['orange', 'green', 'purple'] >>> x=[1,2,3,4,5,6,7,8,9] >>> x[1:6:2] [2, 4, 6]
LIST COMPREHENTIONS
In the example below, squares in the list comprehension that contains squares of all values in list a.
Think of it as "DO WHAT with WHAT VALUES"
so we have: for every value in list a, put the value in variable x and then place the x**2
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> squares = [x**2 for x in a] >>> print(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
another example:
>>> names = ['Cecilia', 'Lise', 'Marie'] >>> letters = [len(n) for n in names] >>> letters [7, 4, 5]
you can have nested for loops or add if statements:
>>> a=[x for x in range(3,16)] >>> a [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] >>> a=[x for x in range(3,16) if x%2 == 0] >>> a [4, 6, 8, 10, 12, 14] >>> a=[y for x in range(1,4) for y in range(x)] >>> a [0, 0, 1, 0, 1, 2]
The video below explains the last example above
In Class Exercise:
a. build a list containing different data types; build a parallel list that would contain type of each element in list a, ex:
a = [1, 3.3, "www", True]
>>> types
[<class 'int'>, <class 'float'>, <class 'str'>, <class 'bool'>]
b. What if another element in list a is a list as well? Will that still work? Why?
a. build a list containing different data types; build a parallel list that would contain type of each element in list a, ex:
a = [1, 3.3, "www", True]
>>> types
[<class 'int'>, <class 'float'>, <class 'str'>, <class 'bool'>]
b. What if another element in list a is a list as well? Will that still work? Why?
LEETCODE JEWELS AND STONES
https://leetcode.com/problems/jewels-and-stones/
sum = 0 for l in J: sum=sum+S.count(l) return sum
LEETCODE RUNNING SUM
https://leetcode.com/problems/running-sum-of-1d-array/
Let's try to write the program, one step at a time, first, let's initialize the result:
nums = [1,2,3,4] result = [0]*len(nums) print(result)
$ python leetcode_running_sum.py [0, 0, 0, 0]
That looks good, now, let's get our i and j indices:
nums = [1,2,3,4] result = [0]*len(nums) for i in range(len(nums)): print(i)
nums = [1,2,3,4] result = [0]*len(nums) for i in range(len(nums)): for j in range(i+1): print(j)
nums = [1,2,3,4] result = [0]*len(nums) for i in range(len(nums)): for j in range(i+1): result[i] = result[i] + nums[j] print(result)
HOMEWORK
Add both programs to github homework2 folder and submit the link to github
Program1:
Write a program that guesses an integer number the user thought of.
The number user can think of should be an integer number 1-100.
After the number is successfully guessed, offer the user to play again
Sample output of the program is below.
Do not use random number generation
Total number of lines in the program should be no more than 30
If you struggle with finding a good approach to this, search web for "binary search"
Sample Output1:
Hi, what is your Name? Zain
Hello Zain! Let's play a game!
Think of random number from 1 to 100, and I'll try to guess it!
Is it 50? (yes/no)no
Is the number larger than 50? (yes/no)yes
Is it 75? (yes/no)no
Is the number larger than 75? (yes/no)yes
Is it 88? (yes/no)no
Is the number larger than 88? (yes/no)yes
Is it 94? (yes/no)no
Is the number larger than 94? (yes/no)yes
Is it 97? (yes/no)no
Is the number larger than 97? (yes/no)yes
Is it 99? (yes/no)no
Is the number larger than 99? (yes/no)yes
Is it 100? (yes/no)yes
Yeey! I got it in 7 tries!
Do you want to play more? yes
Is it 50? (yes/no)no
Is the number larger than 50? (yes/no)yes
Is it 75? (yes/no)no
Is the number larger than 75? (yes/no)yes
Is it 88? (yes/no)no
Is the number larger than 88? (yes/no)no
Is it 81? (yes/no)no
Is the number larger than 81? (yes/no)yes
Is it 84? (yes/no)no
Is the number larger than 84? (yes/no)yes
Is it 86? (yes/no)no
Is the number larger than 86? (yes/no)yes
Is it 87? (yes/no)yes
Yeey! I got it in 7 tries!
Do you want to play more?
Do you want to play more? no
Bye-bye
Program 2:
Solve the following Leetcode problem https://leetcode.com/problems/shuffle-string/
use following string functions that we have not yet learned in the class:
list() breaks string into list of characters and
join() concatenates the list of characters back into a string
use following string functions that we have not yet learned in the class:
list() breaks string into list of characters and
join() concatenates the list of characters back into a string
>>> l=list("Hello") >>> l ['H', 'e', 'l', 'l', 'o'] >>> "".join(l) 'Hello' >>> " ".join(l) 'H e l l o' >>> "_".join(l) 'H_e_l_l_o'
PRACTICE QUESTIONS - you do not need to submit these
1. Use slicing notation on list x = [0,1,2,3,4,5,6,7,8,9] to
2. For x=[1,2,3]
3. Guess, and then use Python to validate your guesses
For a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
- print first 4 elements
- print last 4 elements
2. For x=[1,2,3]
- what is the output of x[2:20] ?
- what is the output of x[20] ?
3. Guess, and then use Python to validate your guesses
For a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
- what will a[2::2] produce?
- what will a[2::-2] produce?