Post

Python Crash Course 5 - If

I’m YouKoutaku. These codes are from the book python_Crash_Course, 2nd edition. I learned python and took these notes for this book.

5.If

5.1 sample

1
2
3
4
5
6
7
8
cars = ['audi','bmw','subaru','toyota']

for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

1
2
3
4
Audi
BMW
Subaru
Toyota

5.2 condition

5.2.1 eq

1
2
car = 'bmw'
car == 'bmw'
1
True
1
2
car = 'audi'
car == 'bmw'
1
False

5.2.2 eq for case

1
2
car = 'Bmw'
car == 'bmw'
1
False
1
2
3
car = 'Bmw'
print(car.lower() == 'bmw')
print(car)
1
2
True
Bmw

5.2.3 non_ep

1
2
3
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchovies!")
1
Hold the anchovies!

5.2.4 compare value

1
2
3
answer = 17
if answer != 42 :
    print("That is not the correct answer.")
1
That is not the correct answer.
1
2
3
4
a = 0
b = 10
print(a > b)
print(b >=a )
1
2
False
True

5.2.5 multi-condition

1
2
3
4
5
# and
a = 0
b = 10
a > 1 and b >5

1
False
1
2
3
4
# or
a = 0
b = 10
a > 1 or b >5
1
True

5.2.6 check value include in list

1
2
3
ani = ['cat','dog','pig']
print('cat' in ani)
print('tagger' in ani)
1
2
True
False

check value not include in list

1
2
3
ani = ['cat','dog','pig']
print('cat' not in ani)
print('tagger' not in ani)
1
2
False
True

5.2.8 boolean

1
2
3
4
5
a = True
#not true
b = False
#not false
print (a , b)
1
True False
1
2
3
4
5
6
7
# E-5-1
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')

print("\n Is car == 'audi'? I predict False")
print(car == 'audi')
1
2
3
4
5
Is car == 'subaru'? I predict True.
True

 Is car == 'audi'? I predict False
False

5.3 if

5.3.1 sample

if conditional_test:
  do something

1
2
3
a = 10
if a>0:
    print('Yes, a>0.')
1
Yes, a>0.

5.3.2 if-else

1
2
3
4
5
a = 10
if a>0:
    print('Yes')
else:
    print('NO')
1
Yes

5.3.3 if-elif-else

1
2
3
4
5
6
7
age = 12
if age < 4:
    print("$0")
elif age <18:
    print("$25")
else:
    print("$45")
1
$25
1
2
3
4
5
6
7
8
9
age = 12
if age < 4:
    p = 0
elif age <18:
    p = 25
else:
    p = 45
    
print(f"Your cost is {p}")
1
Your cost is 25

5.4 if using in list

1
2
3
4
5
6
7
8
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
    if requested_topping == 'green peppers': 
        print("Sorry, we are out of green peppers right now.") 
    else: 
        print(f"Adding {requested_topping}.") 

print("\nFinished making your pizza!")
1
2
3
4
5
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!

5.5 if format\

age < 4: is batter than if age < 4:

This post is licensed under CC BY 4.0 by the author.