Python 3

home

Introduction to Python

davidbpython.com




Conditionals and Blocks; Object Methods

conditionals: if/elif/else and while

All programs must make decisions during execution.


Consider these decisions by programs you know:


Conditional statements allow any program to make the decisions it needs to do its work.





'if' statement

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                   # double the value
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.





'else' statement

An else statement will execute its block if the if test before it was not True.


xx = input('enter an even or odd number:  ')
yy = int(xx)

if yy % 2 == 0:                    # can 2 divide into yy evenly?
    print(xx + ' is even')
    print('congratulations.')

else:
    print(xx + ' is odd')
    print('you are odd too.')

Therefore we can say that only one block of an if/else statement will execute.





'elif' statement

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')





the python code block

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 an even or odd number:  ')  # not in any block
yy = int(xx)                                      # ditto


if yy % 2 == 0:                         # the start of the 'if' block
    print('your number is even')
    print('even is cool')               # last line of the 'if' block


else:                                   # the start of the 'else' block
    print('your number is odd')
    print('you are cool')               # last line of the 'else' block


print('thanks for playing "even/odd number"')      # not in any block

Note also that a block is preceded by an unindented line that ends in a colon.





nested blocks increase indent

Blocks can be nested within one another. A nested block (a "block within a block") simply moves the code block further to the right.


var_a = int(input('enter a number: '))
var_b = int(input('enter another number:  '))

if var_b >= var_a:                         # compare int values for truth
    print("the test was true")
    print("var b is at least as large")

    if var_a == var_b:                     # if the two values are equivalent
        print('the two values are equivalent')

    print("now we're in the outer block but not in the inner block")

print('this gets printed in any case (i.e., not part of either block)')

Complex decision trees using 'if' and 'else' is the basis for most programs.





comparison operators with numbers

>, <, <=, >= 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

With strings, this operator tests to see if two strings are identical.


var = 'hello'
var2 = 'hello'

if var == var2:
    print('these are equivalent strings')





the 'in' operator with 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.  The other...'

if 'Samsung' in article:
    print('Samsung was found')





'and' "compound" test

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. You should avoid parentheses wherever you can.





'or' "compound" test

Python uses the operator or to combine tests: either can be True.


The 'or' compound statement if either test is True, the entire statement is True.


aa = input('please enter "q" or "quit" to quit: ')
if aa == 'q' or aa == 'quit':
    exit()
print('continuing...')

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. You should avoid parentheses wherever you can.





testing a variable against two values

Bogth 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).





testing a variable against multiple values

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()




negating an 'if' test with 'not'

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.





boolean (bool) values True and False

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.





[pr]