-
Notifications
You must be signed in to change notification settings - Fork 1
/
conditionals.py
104 lines (76 loc) · 2.29 KB
/
conditionals.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'''If Statements and Conditional Tests'''
# At the heart of every if statement is an expression that can be evaluated as
# True or False and this is called a conditional test (also called a boolean
# expression). If the conditional test evaluates as True, python will execute
# the code following the if statement, otherwise it will be ignored.
cars = ['ford', 'bmw', 'honda', 'subaru']
# checking for equality:
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# checking for inequality:
for car in cars:
if car != 'bmw':
print(car.title())
else:
print(car.upper())
# Both produce the same result:
# Ford
# BMW
# Honda
# Subaru
# if, elif, else chains
# -----------------------------------------------------------------------------
age = 42
if age < 5:
admission = 0
elif age < 19:
admission = 5
elif age >= 65:
admission = 3
else:
admission = 10
print(admission) # 10
# Note you are not required to have a final else statement. It may be more
# readable to use another elif. Keep in mind if you do it this way, there is no
# catchall at the end, so the value must meet one of the elif conditions or it
# may raise an exception.
if age < 5:
admission = 0
elif age < 19:
admission = 5
elif age >= 65:
admission = 3
elif age < 65:
admission = 10
# Check for values with in, not in
# -----------------------------------------------------------------------------
users = ['rick', 'morty', 'raja', 'bob']
user = 'morty'
if user in users:
print('Hello', user.title())
else:
print('Create account')
# same as:
if user not in users:
print('Create account')
else:
print('Hello', user.title())
# Check for multiple conditions
# -----------------------------------------------------------------------------
import time
now = time.localtime() # <class 'time.struct_time'>
day = time.strftime('%A', now) # <class 'str'>
hour = int(time.strftime('%H', now)) # <class 'int'>
if (4 > hour or hour > 20) and (day != 'Friday') and (day != 'Saturday'):
print('Time for bed!')
else:
print('Carry on.')
# if, else assignments
# -----------------------------------------------------------------------------
flag = True
x = 100 if flag else 0
print(f'{flag=}, {x=}')
# flag=True, x=100