Presentation is loading. Please wait.

Presentation is loading. Please wait.

 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"

Similar presentations


Presentation on theme: " Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string""— Presentation transcript:

1

2  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

3  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

4  The built-in range() function produces intervals that can be designated with parameters Example) for x in range(5): print(x, end = " ") # Prints: 0 1 2 3 4

5 Examples) for x in range(5, 10): print(x, end = " ") #Prints: 5 6 7 8 9 for x in range(1, 10, 3): # 3 indicates the step print(x, end = " ") #Prints: 1 4 7

6  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

7  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

8  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

9  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

10 Example) def sum(a, b): return a + b print(sum(5, 6)) #Prints: 11

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

12  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

13  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


Download ppt " Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string""

Similar presentations


Ads by Google