Control Flow, if statements etc..

From rbachwiki
Jump to navigation Jump to search

Python If Statemts

name = "b"
if name == 'robert':
   print(name)
elif name == 'john':
   print(name)
else:
   print('wrong name')

Python For Loops

print('My name is ')
for i in range(5, 25):
   print('Robert five time ' + str(i))
total = 0
for num in range(101):
   total = total + num
print('the total from 1 to 100 is: ' + str(total))
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.

Python Operators

Range

for num in range(10)
  print(num)

Output

0,1,2,3,4,5,6,7,8,9
for num in range(3,10) # start at 3
  print(num)
for num in range(3,10,2) # start at 3 step 2
  print(num)
index_count=0
for letter in 'abcde':
  print('At index{} the letter is {}' .format(index_count,letter))
  index_count +=1

Enumerate Function

word= 'abcde'
for item in enumerate(word):
  print(item)

output

(0,'a')
(1,'b')
(2,'c')
...
for index, letter in enumerate(word):
  print(index)
  print(letter)
  print('\n')

output

 0
 a
 1
 b
...

Zip Function

mylist = [1,2,3]
mylist2 = ['a','b','c']
for item in zip(mylist1, mylist2):
 print(item)

output

(1, 'a')
(2, 'b')
(3, 'c')

In Operator

'x' in ['x','y']

Return

True

Random Library Have to be imported

from random import shuffle # shuffle function
mylist = [1,2,3]
shuffle(mylist)
from random import randint # import random function
randint(0,100)

output

79

Accept User input

result = input("Enter a number')

Try Except Python

rawstr = input('Enter a number: ')
try:
  ival = int(rawstr)
except:
  ival = -1
if ival > 0 :
  print('Nice work')
else:
  print('Not a number')

output

Nice work

Back To Top - Category