Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string" for char in x : print(char, end = “ “) #char is not a reserved word #Prints: s t r i n g
Use slice notation to create a copy to loop through rather than looping through the original list Example) x = [1, 3, 5]; for num in x[:]: x.append(num) print(x) #Prints: [1, 3, 5, 1, 3, 5] rather than creating an # infinite loop
The built-in range() function produces intervals that can be designated with parameters Example) for x in range(5): print(x, end = " ") # Prints:
Examples) for x in range(5, 10): print(x, end = " ") #Prints: for x in range(1, 10, 3): # 3 indicates the step print(x, end = " ") #Prints: 1 4 7
The break statement can be used to exit the loop in which the break statement has been placed The continue statement moves to the next iteration of the loop without executing lines below it
Loop statements may now use an else clause The else is executed when a loop exhausts all items in a list or hits the terminating condition, but not when a break statement is used Example) x = 0 while x < 10: x+=1 else: print("In the Else") #Prints: In the Else
The pass statement does nothing This statement is used when code is required, but nothing useful needs to be written while True: pass #Infinite loop that does nothing
The keyword def is used to define functions def must be immediately followed by the function’s name and a list of parameters Parameters that are passed in functions are always references to an existing object, not the object itself No return types are required
Example) def sum(a, b): return a + b print(sum(5, 6)) #Prints: 11
The same function can have multiple names def sum(a, b): return a + b print(sum(5, 6)) #Prints 11 s = sum print(s(3, 5)) # Prints 8
A function without a return statement, returns “None” A function that does not reach its return statement will return “None” Example) def mystery(): pass print(mystery()) #returns: None
Use “in” to determine if an element is part of a list x = 5 y = [2, 5, 6, 7] if x in y: print("5 exists") # Prints: 5 exists