Section 5: Python Statements

  Python Bootcamp 0 to Hero

Section 5 Menu

< Section 4
Section 6 >

    1. if, elif and else Statements in Python
    2. for Loops in Python
    3. while Loops in Python
    4. Useful Operators in Python
    5. List Comprehensions in Python
    6. Python Statements Test Overview
    7. Python Statements Test Solutions

Control Flow allows us to execute specific blocks of code under specific conditions

if, elif and else Statements in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9407960#content

These statements require a ‘:’ and white space (tabs)

if some_condition_is_true:
    # execute some code that is indented
    # this line would execute as well
elif previous_was_false_but_this_is_true:
    #execute different code
elif both_above_are_false_but_this_is_true:
    # execute this block
    # of code
else:
    # execute this code if all conditions above are false

Example

hungry = True
if hungry:
   print("Feed me!")
else:
   print("I'll eat later.")

Feed me!

hungry = False
if hungry:
   print("Feed me!")
else:
   print("I'll eat later.")

I’ll eat later.

Note: Non 0 results are True, 0 results are False

hungry = 5
if hungry:
   print("Feed me!")
else:
   print("I'll eat later.")

Feed me!

hungry = 0
if hungry:
   print("Feed me!")
else:
   print("I'll eat later.")

I’ll eat later.

for Loops in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9407962#content

  • Many objects in Python are ‘iterable’, meaning we can iterate (step through) over every element in the object.
    • Such as every
      • element in a list
      • character in a string
      • key in a dictionary
  • We can use ‘for’ loops to execute a block of code for every iteration.
mylist = [1, 2, 3]
for value in mylist:
    print(value)

1
2
3

myname = "Sofia"
for value in myname:
    print(value)

S
o
f
i
a

Note: You can use an underscore character for variable names you do not use

mylist = [1, 2, 3]
for _ in mylist:
    print('Hello')

Hello
Hello
Hello

tuple unpacking

Below we ‘unpack’ the tuple by assigning each index in the tuple to a variable.

mylist = [(1,2), (3,4), (5,6)]
print(len(mylist))
for value in mylist:
    print(value)
for a, b in mylist:
    print(f"{a} and {b}")
3
(1, 2)
(3, 4)
(5, 6)
1 and 2
3 and 4
5 and 6

Note: The number of variables must match the tuple count or an error will occur!

mylist = [(1,2,3), (3,4), (5,6)]
print(len(mylist))
for value in mylist:
    print(value)
for a, b in mylist:
    print(f"{a} and {b}")
3
(1, 2, 3)
(3, 4)
(5, 6)
ValueError: too many values to unpack (expected 2)

for loops with dictionaries

 

Note: Keep in mind these are not ordered! There is no guarantee you’ll get your items back in the order you entered them!

This only return the keys!!

mydict = {'k1': '1', 'k2': 2, 'k3':3}
for value in mydict:
    print(value)

k1
k2
k3

To get the key:value pairs:

mydict = {'k1': '1', 'k2': 2, 'k3':3}
for value in mydict.items():
    print(value)

(‘k1’, 1)
(‘k2’, 2)
(‘k3’, 3)

To get JUST the values:

mydict = {'k1': '1', 'k2': 2, 'k3':3}
for key, value in mydict.items():
    print(value)

1
2
3
…or use an underscore for the key variable…

mydict = {'k1': '1', 'k2': 2, 'k3':3}
for _, value in mydict.items():
    print(value)

1
2
3
…or use .values()

mydict = {'k1': '1', 'k2': 2, 'k3':3}
for value in mydict.values():
    print(value)

1
2
3

while Loops in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9407964#content

  • while loops will continue to execute a block of code ‘while’ a condition remains True
    • while my_pool != full, keep_filling_pool = true
while some_condition:
    # do something
    # and continue to do it until the condition is false!
else:
    # do something else one time

Example

x = 0
while x < 5:
    print(x)
    x += 1
else:
    print(f"'{x}' is not less than 5!")

0
1
2
3
4
‘5’ is not less than 5!

break, continue and pass

  • break: Breaks out of the current closest enclosing loop.
  • continue: Goes to the top of the current closest enclosing loop.
  • pass: does nothing at all.  o.O   O.o
    • it is a filler for blocks of code that have no code!

pass

x = [1,2,3]
for value in x:
    # nothing here
print('done')

IndentationError: expected an indented block

x = [1,2,3]
for value in x:
    pass
print('done')

done

continue

name = 'Sophia'
for letter in name:
    if letter == 'p':
        print('f')
        continue
    elif letter == 'h':
        #don't print anything
        continue
    print(letter)

S
o
f
i
a

break

name = 'Sofia Roberts'
for letter in name:
    if letter == ' ':
        break
    print(letter)

S
o
f
i
a

Useful Operators in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9407966#content

range

range(start,stop,step)

for num in range(5):
    print(num)

0
1
2
3
4

for num in range(2,5):
    print(num)

2
3
4

for num in range(0,5,2):
    print(num)

0
2
4

Create a list with range

x = list(range(5))
print(x)

[0, 1, 2, 3, 4]

enumerate

i = 0
for letter in 'abcde':
    print(f"Index {i} = {letter}")
    i += 1

Index 0 = a
Index 1 = b
Index 2 = c
Index 3 = d
Index 4 = e

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

(0, ‘a’)
(1, ‘b’)
(2, ‘c’)
(3, ‘d’)
(4, ‘e’)

for i, letter in enumerate('abcde'):
    print(f"Index {i} = {letter}")

Index 0 = a
Index 1 = b
Index 2 = c
Index 3 = d
Index 4 = e

zip

Returns sets of tuples paired from multiple lists
* Note: it stops pairing to the list with the smallest count.

mylist1 = [1, 2, 3, 4]
mylist2 = ['a', 'b', 'c', 'd']
mylist3 = ['Thomas', 'Sofia', 'Roberts']
for item in zip(mylist1, mylist2, mylist3):
    print(item)

(1, ‘a’, ‘Thomas’)
(2, ‘b’, ‘Sofia’)
(3, ‘c’, ‘Roberts’)

list(zip(mylist1, mylist2, mylist3))

[(1, ‘a’, ‘Thomas’), (2, ‘b’, ‘Sofia’), (3, ‘c’, ‘Roberts’)]

in

mylist = ['Thomas', 'Sofia', 'Roberts']
'Jim' in mylist

False

'Sofia' in mylist

True

'f' in "Sofia"

True

'k1' in {'k1': 123}

True

123 in {'k1': 123}

False

123 in {'k1': 123}.values()

True

min and max

mylist = [1, 2, 3, 4]
min(mylist)

1

max(mylist)

4

Random Library

shuffle

This is an in place function and does not return anything.

from random import shuffle
mylist = [1,2,3,4,5,6,7,8,9,10]
shuffle(mylist)
mylist

[6, 3, 9, 2, 1, 8, 5, 10, 4, 7]

shuffle(mylist)
mylist

[4, 6, 2, 7, 5, 10, 8, 3, 9, 1]

randint

randint(min, max)

from random import randint
x = randint(0,10)
x

4

Other Functions

input

* Note: Input results are always strings!

name = input('What is your name? ')

What is your name? Sofia

name

‘Sofia’

Convert input results to an int or float

number = input('What is your favorite number? ')

What is your favorite number? 24.7

type(number)

str

float(number)

24.7

int(number)

24.7
ValueError: invalid literal for int() with base 10: ‘24.7’

int(float(number))

24

Casting input values

number = int(input('What is your favorite number? '))

What is your favorite number? 24.7
ValueError: invalid literal for int() with base 10: ‘24.7’

number = int(float((input('What is your favorite number? ')))

What is your favorite number? 24.7

number

24

List Comprehensions in Python

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9407968#content

  • List comprehensions are a unique way of quickly creating a list with Python.
  • If you find yourself usinf a for loop along with .append() to create a list, List Comprehensions are a good alternative.
mystring = 'Sofia'
mylist = []
for letter in mystring:
    mylist.append(letter)
mylist

[‘S’, ‘o’, ‘f’, ‘i’, ‘a’]

Shortcut version

mylist = [letter for letter in mystring]
mylist

[‘S’, ‘o’, ‘f’, ‘i’, ‘a’]

mylist = [num for num in range(0,5)]
mylist

[0, 1, 2, 3, 4]

mylist = [num**2 for num in range(0,5)]
mylist

[0, 1, 4, 9, 16]

fahrenheit = [ (9/5*temp+32) for temp in [0, 10, 20, 34.5])
mylist

[32.0, 50.0, 68.0, 94.1]
this is the same as:

fahrenheit = []
for temp in [0, 10, 20, 34.5]:
    fahrenheit.append(9/5*temp+32)
fahrenheit

[32.0, 50.0, 68.0, 94.1]

Using if, else statements

if

mylist = [num for num in range(0,11) if num%2==0]
mylist

[0, 2, 4, 6, 8, 10]
if else
Notice the order is reversed!

mylist = [num if num%2==0 else 'ODD' for num in range(0,11)]
mylist

[0, ‘ODD’, 2, ‘ODD’, 4, ‘ODD’, 6, ‘ODD’, 8, ‘ODD’, 10]

Nested for loops

mylist = [x * y for x in [2, 4, 6] for y in [1, 10, 100]]
mylist

[2, 20, 200, 4, 40, 400, 6, 60, 600]

Python Statements Test Overview

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9407970#content

Python Statements Test Solutions

https://www.udemy.com/complete-python-bootcamp/learn/lecture/9407974#content

 

LEAVE A COMMENT