Difference between revisions of "Control Flow, if statements etc.."
Line 48: | Line 48: | ||
sorted(d.values()) | sorted(d.values()) | ||
=Python While Loops= | =Python While Loops= | ||
x = 0 | |||
while x < 5: | |||
print(f'The value of x is {x}) | |||
x += 1 | |||
else: | |||
print("x is not less than 5") | |||
'''break, continue, pass''' | |||
We can use break, continue, and pass statements in our loops to add additional functionality for various cases. The three statements are defined by: | |||
break: Breaks out of the current closest enclosing loop.<br> | |||
continue: Goes to the top of the closest enclosing loop.<br> | |||
pass: Does nothing at all.<br> | |||
Thinking about break and continue statements, the general format of the while loop looks like this:<br> | |||
while test: | |||
code statement | |||
if test: | |||
break | |||
if test: | |||
continue | |||
else: | |||
break and continue statements can appear anywhere inside the loop’s body, but we will usually put them further nested in conjunction with an if statement to perform an action based on some condition. |
Revision as of 20:46, 6 January 2019
Python If Statemts
name = "b" if name == 'robert': print(name) elif name == 'john': print(name) else: print('wrong name')
Python For Loops
list2 = [(2,4),(6,8),(10,12)] for tup in list2: print(tup)
output
(2, 4) (6, 8) (10, 12)
Now with unpacking
for (t1,t2) in list2: print(t1)
Output
2 6 10
Another Example
d = {'k1':1,'k2':2,'k3':3} for item in d: print(item)
Create a dictionary view object
d.items()
output
dict_items([('k1', 1), ('k2', 2), ('k3', 3)])
Dictionary unpacking
for k,v in d.items(): print(k) print(v)
output
k1 1 k2 2 k3 3
If you want to obtain a true list of keys, values, or key/value tuples, you can cast the view as a list:
list(d.keys())
output
['k1', 'k2', 'k3']
Remember that dictionaries are unordered, and that keys and values come back in arbitrary order. You can obtain a sorted list using sorted():
sorted(d.values())
Python While Loops
x = 0 while x < 5: print(f'The value of x is {x}) x += 1 else: print("x is not less than 5")
break, continue, pass We can use break, continue, and pass statements in our loops to add additional functionality for various cases. The three statements are defined by:
break: Breaks out of the current closest enclosing loop.
continue: Goes to the top of the closest enclosing loop.
pass: Does nothing at all.
Thinking about break and continue statements, the general format of the while loop looks like this:
while test: code statement if test: break if test: continue else:
break and continue statements can appear anywhere inside the loop’s body, but we will usually put them further nested in conjunction with an if statement to perform an action based on some condition.