Difference between revisions of "Control Flow, if statements etc.."

From rbachwiki
Jump to navigation Jump to search
Line 7: Line 7:
  else:
  else:
     print('wrong name')
     print('wrong name')
=Python Loops=
=Python For Loops=
  list2 = [(2,4),(6,8),(10,12)]
  list2 = [(2,4),(6,8),(10,12)]
  for tup in list2:
  for tup in list2:
Line 47: Line 47:
Remember that dictionaries are unordered, and that keys and values come back in arbitrary order. You can obtain a sorted list using sorted():
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())
  sorted(d.values())
=Python While Loops=

Revision as of 20:41, 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