forked from huangsam/ultimate-python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconditional.py
More file actions
Latest commit
66 lines (56 loc) · 2.07 KB
/
Copy pathconditional.py
File metadata and controls
66 lines (56 loc) · 2.07 KB
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
"""
This module shows how to use if blocks, if-else blocks and if-elif-else
blocks to decide which lines of code to run (and skip).
"""
defmain() ->None:
x=1
x_add_two=x+2
# This condition is obviously true
ran_1=False
ifx_add_two==3: # skip: else
ran_1=True# run
assertran_1isTrue
# A negated condition can also be true
ran_2=False
ifnotx_add_two==1: # skip: else
ran_2=True# run
assertran_2isTrue
# There are `else` statements as well, which run if the initial condition
# fails. Notice that one line gets skipped and this conditional does not
# help us make a conclusion on the variable's true value
ifx_add_two==1:
ran_3=False# skip: if
else:
ran_3=True# run
assertran_3isTrue
# The `else` statement also runs once all other `if` and `elif` conditions
# fail. Notice that multiple lines get skipped, and that all the
# conditions could have been compressed to `x_add_two != 3` for
# simplicity. In this case, less logic results in more clarity
ifx_add_two==1:
ran_4=False# skip: if
elifx_add_two==2:
ran_4=False# skip: if
elifx_add_two<3orx_add_two>3:
ran_4=False# skip: if
else:
ran_4=True# run
assertran_4isTrue
# Conditionals can also be written in one line using `if` and `else`
# with the following form: A if condition else B. This can be used
# for assignments as shown below
ran_5=False
ran_5=Trueifx_add_two==3elseFalse
assertran_5isTrue
# Python is one of the few programming languages that allows chained
# comparisons. This is useful for checking if a variable is within
# a range of values. You can see that in this example, the expression
# `0 < x_add_two < 2` is equivalent to `x_add_two > 0 and x_add_two < 2`
ran_6=False
if0<x_add_two<2:
ran_6=False# skip: if
else:
ran_6=True# run
assertran_6isTrue
if__name__=="__main__":
main()