CHAPTER 5. CONDITIONALS, LOOPS, AND SOME OTHER STATEMENTS

print 

python 2 -statement, python 3 -function

Arguments of print do not form Tuples

>>> 1,2,3
(1, 2, 3)
>>> print 1,2,3
1 2 3
>>> print (1,2,3)

(1, 2, 3)
________________________________

>>> name = 'Gumby'
>>> salutation = 'Mr.'
>>> greeting = 'Hello,'
>>> print greeting, salutation, name
Hello, Mr. Gumby
________________________________
Issues about comma and space before

>>> name = 'Gumby'
>>> name = 'Gumby'
>>> salutation = 'Mr.'
>>> greeting = 'Hello'
>>> print greeting,',',salutation,name
Hello , Mr. Gumby
>>> print greeting+',',salutation,name
Hello, Mr. Gumby
------------------------------------------
print 'Hello,',
print 'world!'
print out Hello, world!
________________________________

>>> import math as foobar
>>> foobar.sqrt(4)
2.0

OR

>>> from math import sqrt as foobar
________________________________

ASSIGNMENTS

>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
>>> x,y = y,x
>>> x,y,z
(2, 1, 3)
>>> print x,y,z
2 1 3
_____________________

>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1____________________

>>> d = {'name':'John','age':42}
>>> key,value = d.popitem()
>>> key
'age'
>>> value
42
>>> d
{'name': 'John'}
__________________________

CHAINED ASSIGNMENTS

x = y = somefunction()
__________________________

AUGMENTED ASSIGNMENT

X = X+1   IS THE SAME AS   X+=1  OR *=, / ,%

>>> x = 2
>>> x +=1
>>> x
3
>>> x*=2
>>> x

6
__________________________________________
>>> fnord = 'foo'
>>> fnord += 'bar'
>>> fnord
'foobar'
>>> fnord *=2
>>> fnord
'foobarfoobar'
__________________________________________

BOOLEAN

>>> True == 1
True
>>> False == 0
True
>>> True + False + 42

43
_________________________________________
>>> bool('Me')
True
>>> bool(42)
True
>>> bool(0)
False
>>> bool(None)
False
_________________________________________
>>> bool(())
False
>>> bool({})
False
>>> bool("")
False
__________________________________________
name =  raw_input('What is your name? ')
if name.endswith('Gumby'):
    print 'Hello, Mr.Gumby'
__________________________________________
else:

name =  raw_input('What is your name? ')
if name.endswith('Gumby'):
    print 'Hello, Mr.Gumby'
else:
    print 'Hello, %s' % name
__________________________________________
elif:

num = input ('Enter the number: ')
if num > 0:
    print 'Number is positive'
elif num < 0:
    print 'Number is negative'
else:
    print 'Number is ZERO'
_________________________________________

Nesting Blocks

name = raw_input('What is your name? ')
if name.endswith ('Gumby'):
    if name.startswith ('Mr.'):
        print 'Hello, Mr.Gumby'
     elif name.startswith ('Ms.'):
        print 'Hello, Ms.Gumby'
    else:
        print 'Hello, Gumby'
else:
    print 'Hello, stranger'
________________________________________
x == y x equals y.
x < y x is less than y.
x > y x is greater than y.
x >= y x is greater than or equal to y.
x <= y x is less than or equal to y.
x != y x is not equal to y.
x is y x and y are the same object.
x is not y x and y are different objects.
x in y x is a member of the container (e.g., sequence) y.
x not in y x is not a member of the container (e.g., sequence) y.
________________________________________

is operator

>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x is y
True
>>> x is z
False
>>> x == z
True
_________________________________________
>>> x = [1,2,3]
>>> y = [2,4]
>>> x is not y
True'
>>> del x[2]
>>> y[1] = 1
>>> x
[1, 2]
>>> y
[2, 1]
>>> x == y
False
>>> y.reverse()
>>> y
[1, 2]
>>> x == y
True
>>> x is y
False
_________________________________________
To summarize: use == to see if two objects are equal, and use is to see if they are identical
(the same object).
____________________________________________________________________________

in operator

name = raw_input('Your name? ')
if 's' in name:
    print "Your name contains 's'"
else:
    print "No 's'"
___________________________

BOOLEAN

num = input('Enter number between 1 and 10: ')
if num <= 10:
    if num >=1:
        print 'Ok'
    else:
        print 'Wrong'
else:
    print 'Wrong'
____________________________________

But it'sclumsy, so Chained comparison

num = input('Enter number between 1 and 10: ')
if num <= 10 and num >= 1:
    print "It's OK"
else:

    print 'Wrong'
_______________________________________

Assertions 
Useful, if you want to check your program for correct value

>>> age = 5
>>> assert 0 < age <100 nbsp="" p="">>>> age = 102
>>> assert 0 < age <100>>> age = -4
>>> assert 0 < age <100 age="" be="" he="" must="" p="" realistic="">
Traceback (most recent call last):
  File "", line 1, in
    assert 0 < age <100 age="" be="" he="" must="" p="" realistic="">AssertionError: The age must be realistic
___________________________________________________


 LOOPS

while Loops

x = 1
while x <= 100:
    print x
    x +=1
________________________________________________

name = ''
while not name or name.isspace():
    name = raw_input('Enter your name: ')

    print 'Your name is %s' % name

Question will be asked while not name
>>>
Enter your name:
Your name is
Enter your name:
Your name is
Enter your name: Bred
Your name is Bred
>>>
_________________________________________________
Another way

name = ''
while not name.strip():
    name = raw_input('Enter your name: ')
    print 'Your name is %s' % name
__________________________________________________

for Loops

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:

print number
>>> 
1
2
3
4

5

_______________
words = ['ff','gg','kk']
for word in words:

    print word
>>> 
ff
gg
kk

>>>
___________________________________

range

>>> range(1,10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

___________________________________
beginning from 0

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
___________________________________
for number in range(1,10):

    print number
>>>
1
2
3
4
5
6
7
8
9

>>>
___________________________________
Iterating over dictionaries

d = {'x':1,'y':2,'z':3}
for key in d:
    print key,'corresponds to',d[key]
>>>
y corresponds to 2
x corresponds to 1
z corresponds to 3
___________________________________
d = {'x':1,'y':2,'z':3}
for key,value in d.items():
    print key,'corr. to',value
>>>
y corr. to 2
x corr. to 1
z corr. to 3
___________________________________
Parallel Iteration

names = ['adel','ben','steven']
ages = [20,30,40]
for i in range (len(names)):
    print names[i],'is',ages[i],'years old'
names = ['adel','ben','steven']
ages = [20,30,40]
for i in range (len(names)):
    print names[i],'is',ages[i],'years old'
____________________________________
>>> names
['anne', 'beth', 'george', 'damon']
>>> ages
[12, 45, 32, 102]
>>> zip(names,ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
>>>

for name, age in zip(names, ages):
      print name, 'is', age, 'years old'
>>>
anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old
____________________________
xrange calculates only those numbers needed.
>>> zip(range(5),xrange(100))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
-----------------------------------------
Numbered iteration

for string in strings:
    if 'xxx' in strings:
        index = strings.index(string)
        string[index]='[censored]'
________________________________
better version

index = 0
   for string in strings:
   if 'xxx' in string:
  strings[index] = '[censored]'
index += 1
 ________________________________
another solution - built-in function enumerate

for index, string in enumerate(strings):
if 'xxx' in string:

strings[index] = '[censored]'
____________________________________
Reversed and sorted iteration

>>> sorted([1,2,3,4,5,6,7,8,9])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sorted([2,4,3,1,6,5,7,9,8])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sorted('Hello,world')
[',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world'))
['d', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello,world'))
'dlrow,olleH'
_____________________________________

Break out loop

from math import sqrt
for n in range(99,0,-1):
    root = sqrt(n)
    if root == int(root):
        print n
        break
>>>
81
____________________________________
>>> range (1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,3)
[1, 4, 7]
>>> range (1,10,2)
[1, 3, 5, 7, 9]
>>> range(10,1,-1)
[10, 9, 8, 7, 6, 5, 4, 3, 2]
____________________________________
Continue

for x in seq:
if condition1: continue
if condition2: continue
if condition3: continue
do_something()
do_something_else()
do_another_thing()
etc()
____________________________________
The while True/break idiom

while True:
    name = raw_input('Enter: ')
    if not name: break
    #doing something with word
    print  'The ' + name
_____________________________________

else Clauses in LOOPs

from math import sqrt
for n in range(99,80,-1):
    root = sqrt(n)
    if root == int(root):
        print n
        break
    else:
        print "Did't find it"
____________________________________
List Comprehension - making lists from another list

[x*x for x in range(0,10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
__________________________
Printing out squares that are divisible by 3

>>> [x*x for x in range(10) if x % 3 ==0]
[0, 9, 36, 81]
________________________________
[(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>>
________________________________________________
>>> boys = ['arnold','bob','chris']
>>> girls = ['alice','bernice','clarice']
>>> [b+'+'+g for b in boys for g in girls if b[0]==g[0]]
['arnold+alice', 'bob+bernice', 'chris+clarice']
________________________________________________
pass - if something incompleted

if name == 'Ralph Auldus Melish':
print 'Welcome!'
elif name == 'Enid':
# Not finished yet...
pass
elif name == 'Bill Gates':
print 'Access Denied'
__________________________

del

>>> x = ['Hello','world']
>>> y = x
>>> y[1] = 'Python'
>>> x
['Hello', 'Python']
>>> y
['Hello', 'Python']
>>> del x
>>> x

Traceback (most recent call last):
  File "", line 1, in
    x
NameError: name 'x' is not defined
>>> y
['Hello', 'Python']
>>>
________________________________
exec
The statement for executing a string

>>> from math import sqrt
>>> exec 'sqrt = 1'
>>> sqrt(4)

Traceback (most recent call last):
  File "", line 1, in
    sqrt(4)

TypeError: 'int' object is not callable

So it must be:

>>> from math import sqrt
>>> scope = {}
>>> exec 'sqrt = 1' in scope
>>> sqrt(4)
2.0
__________________________
>>> len(scope)
2
>>> scope.keys()
['__builtins__', 'sqrt']
_________________________________

eval - functionevaluates a Python expression (written in a string) and returns the
resulting value

>>> eval(raw_input('Enter an ariphmetic expression: '))
Enter an ariphmetic expression: 3*5
15
_______________________________________________________
>>> scope = {}
>>> scope['x'] = 2
>>> scope['y'] = 3
>>> eval('x*y',scope)
>>>6
________________________________________________________
Actually, exec and eval are not used all that often, but they can be nice tools to keep in your back
pocket (figuratively, of course)
___________________________.

Popular posts from this blog

Ketamine: The Past, Present, and Potential Future of an Anesthetic Drug

Fast track anesthesia approaches