Download presentation
Presentation is loading. Please wait.
1
Python unit_4 review Tue/Wed, Dec 1-2
2
Four Python data types int: age = 20 float: pi = 3.14159 String:
name = ‘Alice’ zipcode=‘95120’ Boolean: isCold = True
3
Arithmetic operator + Addition - Subtraction * Multiplication
/ Division % Modulus if x % 2 == odd number if x % 2 == even number ** Exponent 5**3 = 125
4
Assignment operator a = (a + b) a += b a = (a – b) a -= b
5
Data types and operators
Numeric types can use all arithmetic operators If mixing string and numeric, be careful !!! print(3+5.5) # ok. Output: 8.5 print(3+’5.5’) # error: unsupported type print(‘3’+’5.5’) # ok. String operation # output: 35.5 print( ‘Hi’*5) #ok. Output: HiHiHiHiHi print(‘Hi’+5) # error.
6
Built-in functions for type conversion
int(x): convert x to a integer example: int(‘5’) float(x): convert x to a decimal example: float(‘2.8’) str(x): convert x to a string example: str(5)
7
Type conversion example
print(3+’5’) #error print(3+int(‘5’)) #ok print(‘Hi’ + 5) #error print(‘Hi’ + str(5)) #ok. Output: Hi5
8
Built-in function for keyboard input
Example_1 print(“Please enter your username: “) x=input() Example_2 x = input(“Please enter your username: “)
9
Keyboard input (cont’)
input() always returns a string. If you want the result to be a number, use int(input()) or float(input()) x=input(“How many books you will buy: “) num_books = int(x) #use int() to convert # string to int price = num_books*22.99
10
Python while loop while loop_condition : statement_1 statement_2
Note: Check loop_condition, execute statements. Repeat above, until loop_condition becomes False.
11
while LOOP sample count = 1 while count < 11 : count = count + 1
12
Infinite while loop c = 0 while c< 10 : print (“Hello !!!”)
13
If you don’t want an infinite loop
c = 0 while c< 10 : print (“Hello !!!”) c = c + 1 Use “break” to break out of a loop. while True : if c > 9 : break
14
range() range(start, stop, step)
A quick way to create a list of integers The first integer = start Last integer = stop – 1 Example: range(4) [0,1,2,3] range(1, 5) [1,2,3,4] range(2,7,2) [2,4,6]
15
For loop and range() Print “Hello” 4 times
for x in range(4) : # x will be integer 0,1,2,3 one by one print(“Hello”) Print the sum of integers from 2 to 8 sum = 0 for x in range(2,9) : # x will be integer 2,3,4,5,6,7,8 sum = sum + x print(sum)
16
list data structure Len() : how many elements in the list?
Use index to access data (positive or negative index) myList = [34, 26, ‘abc’, 56, ‘xy’] | | | | | index: or : in operator if ‘abc’ in myList Len() : how many elements in the list? + : merge two lists myList * 3 : repeat myList 3 times
17
list traverse in order print(myList) for x in myList : print(x)
18
list slice syntax: myList[start : stop : step] ending index = stop - 1
if start is missing, start from beginning if stop is missing, to the end if step is missing, step = 1 myList[::] get all list elements in order myList[::-1] get all list elements in reverse order
19
Useful List methods myList.append(‘something’) # add a new item to the end myList.sort() # reorder and change the original list myList.sort(reverse=True) # sort in reverse order myString = ‘- ’.join(myList) # join all items with # ‘-’ as separator
20
Display partial list langs = ["C", "C++", “XML", "Python"]
print(langs[2:]) output: “XML” “Python” for x in langs[2:] : print(x + “ is cool”) Output: XML is cool Python is cool
21
Modify list member: must use index
Question: how to modify the last two elements to “Java”? langs = ["C", "C++", "Perl", "Python"] langs[2] = "Perl“ langs[3] = "Python“ range(2,4) gives an integer list [2,3] To update the last two elements to “Java” for x in range(2,4) : langs[x] = “Java” output: ['C', 'C++', 'Java', 'Java']
22
String myStr = ‘the ring’ index: 0 1 2 3 4 5 6 7
myStr[start : stop : step] “in” operator ‘r’ in myStr “+”: link two strings “*”: repeat string print(myStr*3)
23
String looping myStr = ‘the ring’ count = 0 for char in myStr :
if char==‘e’ : count = count + 1
24
But string is immutable!!!
name = ‘007 Spectre’ You can’t change any letter in a string. name[2] = ‘8’ # ERROR!!!!!!
25
String replace() Python provides a built-in function
myStr.replace(old, new, count) old -- The old substring to be replaced. new --The new substring, which would replace old substring. count – an optional argument. Note: for all string methods result, assign it to something. s1 = myStr.replace(old, new, count) Or myStr = myStr.replace(old, new, count)
26
Dictionary eng2spa = {} # Create an empty dictionary
eng2spa[key] = value create a new entry or Replace the value if the key already exists. key in eng2spa # output: True or False Key not in eng2spa # output: True or False Len(eng2spa) key_list = list(eng2spa.keys()) # get list of keys val_list = list(eng2spa.values()) # get list of values
27
Function----def foo() :
def play_music() : print(“Start playing Hello…”) def find_route_to_home() : print(“open google map. Point to home.”) play_music() find_route_to_home()
28
def foo(arg) : def play_music(music_name) :
print(“Start playing: “, music_name) play_music(‘Hello’) play_music(‘Skyfall’) play_music(‘Happy’)
29
def foo(arg1, arg2) : def get_avg(x, y) : avg = (x+y)/2
print(“average is: “, avg) get_avg(5, 8) get_avg(22, 34) Note: function result can’t be assigned to a variable !!! x = get_avg(5, 8) # (error !!!)
30
Solution: def foo(arg1, arg2): return
def get_avg(x, y) : avg = (x+y)/2 return avg x = get_avg(5, 8) y = get_avg(3.4, 2.7)
31
Reminder Show dictionary_proj today: Dec1:2nd/Dec2:3rd
Next Project will be Banking. Coming soon. Test: Fri or Monday. Open notes, but handwritten notes only.
32
Stanford Splash !! at36 April 2016. Class try-on for high schooler
33
Extra question just for fun
Write a function that reverses the order of the words in a string. For instance, the string “To be or not to be, that is a question. “ is changed to “question. A is that be, to not or be To”. Assume that all words are space delimited and treat punctuation the same as letters. You are given two fuses and a lighter. When lit, each fuse takes exactly one hour to burn from one end to the other. The fuses do not burn at a constant rate, though, and they are not identical. In other words, you may take no assumptions about the relationship between the length and the time it will take to burn. Two equal length of fuse might take different time to burn. Using only the fuses and the lighter, measure a period of exactly 45 minutes.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.