Chapter 7: Functions,Part One: The Fundamentals

Example 7.1, Page Number: 129

In [1]:
def f1():
    print "Enter something: "
    str= "Hello"           #User-input
    print str
    
#Variable decleration
str="This is str in main"

print str
f1()        #function call
print str
This is str in main
Enter something: 
Hello
This is str in main

Example 7.2, Page Number: 130

In [1]:
#Variable decleration
choice=0

print "(1) add numbers or (2) concatenate strings?: "
choice=2                           #User Input taken as 2

if choice==1:
    print "Enter two numbers: "
    a=5            #Variable decleration; User Input
    b=7
    print a+b      #Result
else :
    print "Enter two strings: "
    s1="Hello"     #Variable decleration; User Input
    s2="World"
    s1+=s2         #Concatenation
    print s1       #Result
(1) add numbers or (2) concatenate strings?: 
Enter two strings: 
HelloWorld

Example 7.3, Page Number: 131

In [2]:
#Variable decleration
i=10
j=100

if j>0:
    i=None  
    i= j/2
    print "inner i: ",i   #Result

print "outer i: ",i       #Result
inner i:  50
outer i:  50

Example 7.4, Page Number: 132

In [4]:
a=5                      #Variable decleration; user input

b=10                     #declaration of another variable; user input

#Result
print "Product: ",a*b
Product:  50

Example 7.5, Page Number: 134

In [5]:
import random

#Variable decleration
count=None
num_right=0

#Function for the drill
def drill():
    #Generate two numbers between 0 and 99.
    a=random.randint(0,99)
    b=random.randint(0,99)
    #The user gets three tries to get it right.
    for count in range(3):
        print "What is ",a," + ",b,"? "
        ans = random.randint(0,200)            #user input
        if ans==a+b:
            print "Right"
            num_right+=1
    print "You've used up all your tries."
    print "The answer is ",a+b
    
#Main function    
print "How many practice problems: "
count=2                              #User input taken as 2
num_right=0
while True:
    drill()
    count-=1
    if(count==0):
        break
        
#Result
print "You got ",num_right," right. "  
How many practice problems: 
What is  9  +  89 ? 
What is  9  +  89 ? 
What is  9  +  89 ? 
You've used up all your tries.
The answer is  98
What is  85  +  98 ? 
What is  85  +  98 ? 
What is  85  +  98 ? 
You've used up all your tries.
The answer is  183
You got  0  right. 

Example 7.6, Page Number: 136

In [5]:
from ctypes import *
 
def f(j):
    j[0]=100          #j is assigned 100

#Variable decleration
i=c_int(1)
p=pointer(i)

#Calling the function
f(p)      

print i
c_long(100)

Example 7.7, Page Number: 137

In [6]:
from ctypes import *

 
def f(j):
    j[0]=100          #j is assigned 100

#Variable decleration
i=c_int(1)
p=pointer(i)

#Calling the function
f(p)      

print i
c_long(100)

Example 7.8, Page Number: 137

In [7]:
 
def display(num):
    for i in range(10):
        print num[i],
    
#Variable declaration
t=[]

for i in range(10):
    t.append(i)
#Pass list to a function
display(t)
0 1 2 3 4 5 6 7 8 9

Example 7.9, Page Number: 138

In [8]:
 
def display(num):
    print num,

#Variable declaration
t=[]

for i in range(10):
    t.append(i)
    
#Printing without passing entire list
for i in range(10):
    display(t[i])
0 1 2 3 4 5 6 7 8 9

Example 7.10, Page Number: 139

In [10]:
 
def cube(n,num):
    num-=1
    while num:
        n[num]=n[num]*n[num]*n[num]
        num-=1

#Variable declaration
nums=[]

for i in range(10):
    nums.append(i+1)
    
print "Original contents: ",
for i in range(10):
    print nums[i],
print

cube(nums,10)           #Compute cubes

#Result
print "Altered contents: ",
for i in range(10):
    print nums[i],
Original contents:  1 2 3 4 5 6 7 8 9 10
Altered contents:  1 8 27 64 125 216 343 512 729 1000

Example 7.11, Page Number: 140

In [7]:
import string

def stringupper(str):
    str=string.upper(str) #convert to uppercase
    return str

#Variable declaration    
str="this is a test"

#Calling the function
str=stringupper(str)

#Result
print str
THIS IS A TEST

Example 7.12, Page Number: 141

In [11]:
 
def mystrlen(str):
    l=len(str)
    return l

#Result
print "Length of Hello There is: ",
print mystrlen("Hello There")
Length of Hello There is:  11

Example 7.13, Page Number: 142

In [2]:
import sys

def main():
    if len(sys.argv)!=2:
        print "You forgot to type your name."                                            #CHECK!!!!
        return
    #Result
    print "Hello ",sys.argv[1]

main()
You forgot to type your name.

Example 7.14, Page Number: 143

In [2]:
import sys

#Result
for t in range(len(sys.argv)):
    i=0
    print sys.argv[t]  
-c
-f
C:\Users\Anandi\.ipython\profile_default\security\kernel-6e851974-75ff-4911-bdf9-e089a03e5741.json
--KernelApp.parent_appname='ipython-notebook'
--interrupt=904
--parent=876

Example 7.15, Page Number: 144

In [3]:
import sys

if len(sys.argv)!=3:
    print "usage: add num num"    
else :
    #Variable Decleration
    a=sys.argv[1]
    b=sys.argv[2]
    #Result
    print a+b
    
usage: add num num

Example 7.16, Page Number: 145

In [13]:
import string

#Variable Decleration
i=string.atoi("100")
j=string.atoi("100000")
k=string.atof("-0.123")

#Result
print i," ",j," ",k
100   100000   -0.123

Example 7.17, Page Number: 147

In [5]:
#Variable Decleration
i=abs(-10)

#Result
print abs(-23)
abs(100)
23
Out[5]:
100

Example 7.18, Page Number: 148

In [6]:
 
def find_substr(sub,str):
    l=str.find(sub)
    return l

#Variable decleration;Calling the function
index=find_substr("three","one two three four")

#Result
print "Index of three is ",index
Index of three is  8

Example 7.19, Page Number: 149

In [14]:
import sys

def print_vertical(str):
    l=len(str)
    for i in range(l):
        print str[i],
        
print_vertical(sys.argv[1])
    
- f

Example 7.20, Page Number: 150

In [2]:
 
def find_substr(sub,str):
    return str.find(sub)

#Variable declaration
s="one two three four"

substr = find_substr("three",s)

#Result
print "substring found:",s[substr:]
substring found: three four

Example 7.21, Page Number: 154

In [3]:
 
def factr(n):
    if n==1:
        return 1
    answer=factr(n-1)*n
    return answer

#Iterative version
def fact(n):
    answer=1
    for t in range(n):
        answer=answer*(t+1)
    return answer

#Using recursion version
print "4 factorial is ",factr(4)

#Using iterative version
print "4 factorial is ",fact(4)

 
4 factorial is  24
4 factorial is  24

Example 7.22, Page Number: 155

In [9]:
 
def reverse(s):
     r = ""
     for c in s:
            r=c+r
     print r
     
#VariabDecleration      
str="this is a test"

#Calling function
reverse(str)
tset a si siht
In [ ]: