Conditionals and Recursion in Python

✓ Boolean Expressions

>>> 5 == 5
True
>>> 5 == 6
False>

>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>

✓ Relational operators

x != y
x > y
x < y x >= y
x <= y

✓ Logical Operators – There are three logical operators: and, or, and not.

n%2 == 0 or n%3 == 0 true if either of the conditions is true

>>> 6 and True # Any nonzero number is interpreted as true
True

✓ Conditional execution

if x < y:     print 'x is less than y' elif x > y:
    print 'x is greater than y'
else:
    print 'x and y are equal'

✓ Nested conditionals

if 0 < x:
    if x < 10:
        print 'x is a positive single-digit number.'

✓ Recursion – It is legal for one function to call another, and it is also legal for a function to call itself.

def countdown(n):
if n <= 0:
print 'Blastoff!'
else:
print n
countdown(n-1)

✓ Keyboard Input

>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> int(speed)
17
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s