Beginner Python Concepts
a-Rye
39.3K views
Control Flow
Control Flow refers to the use of comparison logic to determine what to do next. By that, I mean using if, elif, else statements to filter what code to run based on certain conditions.
The test cases provided test some of the common "corner cases" you may want to test.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def control_flow(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
print(control_flow(1000000))
print(control_flow(95))
print(control_flow(90))
print(control_flow(89))
print(control_flow(85))
print(control_flow(75))
print(control_flow(65))
print(control_flow(59))
print(control_flow(0))
print(control_flow(-1000))
If and elif statements will execute if the expression equates to True or 1. If the expression evaluates down to any other value, the attached code won't execute.
Here are some examples of such:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
the_meaning_of_life = 42
valid = False
if the_meaning_of_life == 42:
print("Ran")
if 1:
print("1 worked as well!")
if valid:
print("It's valid")
else:
print("It's not valid")
You can also chain conditions in your if, elif, else statement blocks. This can be done with and, or, not, and xor.
Try changing the conditions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
my_int = 5
if my_int < 10 and my_int > 0:
print("It's between 0 and 10")
my_char = 'c'
to_search = "Does this string have your letter?"
if my_char not in to_search:
print("Nope, my char is not in there!")
if my_char not in to_search or 1:
print("Either part can be true")
if my_char not in to_search or 1 or my_int < -1000:
print("You can have as many conditionals as you want!")
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.