Python 3home |
Introduction to Python
davidbpython.com
All programs must make decisions during execution.
Consider these decisions by programs you know:
Each program will decide conditional statements allow any program to make the decisions it needs to do its work.
The if statement executes code in its block only if the test is True.
aa = input('please enter a positive integer: ')
int_aa = int(aa)
if int_aa < 0: # test: is this a True statement?
print('error: input invalid') # block (2 lines) -- lines are
exit() # executed only if test is True
d_int_aa = int_aa * 2
print('your value doubled is ' + str(d_int_aa))
The two components of an if statement are the test and the block. The test determines whether the block will be executed.
An else statement will execute its block if the if test before it was not True.
xx = input('enter a value less than 100: ')
yy = int(xx)
if yy < 100:
print(xx + ' is a valid number')
print('congratulations.')
else:
print(xx + ' is too high')
print('please re-run and try again.')
Since else means "otherwise", we can say that only one block of an if/else statement will execute.
elif is also used with if (and optionally else): you can chain additional conditions for other behavior.
zz = input('type an integer and I will tell you its sign: ')
zyz = int(zz)
if zyz > 0:
print('that number is positive')
elif zyz < 0:
print('that number is negative')
else:
print('0 is neutral')
A code block is marked by indented lines. The end of the block is marked by a line that returns to the prior indent.
xx = input('enter a value less than 100: ') # not in any block
yy = int(xx) # not in any block
if yy < 100: # the start of the 'if' block
print(xx + ' is a valid number')
print('congratulations.') # last line of the 'if' block
else: # the start of the 'else' block
print(xx + ' is too high')
print('please re-run and try again.') # last line of the 'else' block
Note also that a block is preceded by an unindented line that ends in a colon.
Blocks can be nested within one another. A nested block (a "block within a block") is indented further to the right.
var_a = int(input('enter a number: '))
var_b = int(input('enter another number: '))
if var_b >= var_a: # 'outer' block
print("the test was true")
print("var b is at least as large")
if var_a == var_b: # 'inner' block
print('the two values are equivalent')
print("in outer block, not in the inner block") # back in 'outer' block
print('this gets printed in any case (i.e., not part of either block)')
Decision trees using 'if' and 'else' is a part of most programs.
>, <, <=, >= tests with numbers work as you might expect.
var = 5
var2 = 3.3
if var >= var2:
print('var is greater or equal')
if var == var2:
print('they are equivalent')
With strings, this operator tests to see if two strings are identical.
var = 'hello'
var2 = 'hello'
if var == var2:
print('these are equivalent strings')
in with strings allows you can to see if a 'substring' appears within a string.
article = 'The market rallied, buoyed by a rise in Samsung Electronics.'
if 'Samsung' in article:
print('Samsung was found')
Python uses the operator and to combine tests: both must be True.
The and compound statement if both tests are True, the entire statement is True.
xx = input('what is your ID? ')
yy = input('what is your pin? ')
if xx == 'dbb212' and yy == '3859':
print('you are a validated user')
else:
print('you are not validated')
Note the lack of parentheses around the tests -- if the syntax is unambiguous, Python will understand. We can use parentheses to clarify compound statements like these, but they often aren't necessary. Beginners may think they need to put parentheses around some values. You should avoid parentheses wherever you can.
Python uses the operator or to combine tests: either can be True for the entire expression to be True.
aa = input('please enter "q" or "quit" to quit: ')
if aa == 'q' or aa == 'quit':
exit()
print('continuing...')
Again, note the lack of parentheses around the tests -- if the syntax is unambiguous, Python will understand. We can use parentheses to clarify compound statements like these, but they often aren't necessary. Beginners may think they need to put parentheses around some values. You should avoid parentheses wherever you can.
Both sides of an 'or' or 'and' must be complete tests.
if aa == 'q' or aa == 'quit': # not "if aa == 'q' or 'quit'""
exit()
Note the 'or' test above -- we would not say if aa == 'q' or 'quit'; this would always succeed (for reasons discussed later).
We can also test a variable against multiple values by using in with a list (more on lists next week):
if aa in ['q', 'quit']:
exit()
You can negate a test with the not keyword.
var_a = 5
var_b = 10
if not var_a > var_b:
print("var_a is not larger than var_b (well - it isn't).")
Of course this particular test can also be expressed by replacing the comparison operator > with <=, but when we learn about new True/False condition types we'll see how this operator can come in handy.
True and False are boolean values (type bool), and are produced by expressions that can be seen as True or False.
aa = 3
bb = 5
if aa > bb:
print("that is true")
Tests are actually expressions that resolve to True or False, which are values of boolean type:
var = 5
var2 = 10
xx = (5 > 3)
print(xx) # True
print(type(xx)) # <class 'bool'>
Note that we would almost never assign comparisons like these to variables, but we are doing so here to illustrate that they resolve to boolean values. ex 3.1 - 3.9