06 Python Tutorial
06 Python Tutorial
# This is a comment
>>> help()
>>> quit()
Operation Result
--------- ------
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y (floored) quotient of x and y
x % y remainder of x / y
x ** y x to the power y
Python-2
> Examples
1. parentheses ()
2. exponents **
3. multiplication *, division \, and remainder %
4. addition + and subtraction -
> Expressions
Operation Notes
--------- -----
x | y bitwise or of x and y
x ^ y bitwise exclusive or of x and y
x & y bitwise and of x and y
x << n x shifted left by n bits
x >> n x shifted right by n bits
~x the bits of x inverted
Operation
---------
x or y eg: a>b or x>y
x and y eg: a>b and x>y
not x eg: not (a == b)
Python-3
> Exercises
1. Write a program that prints your full name and your birthday
as separate strings.
name = "Biju"
age = 20
print("My name is {0}. I am {1} years old" . format(name,age))
# --- OR ---
> Reading numbers from the Keyboard. Also print their type.
Concatenation
Repetition
str = "Hello"
print str*2 # HelloHello
print "world"*3
> Exercise
count = 1
while count <= 10 :
print count
count = count + 1
# use Ctrl+Z to end
Python-5
sum = 0
n = 0
while n >= 0 :
sum = sum + n
n = input("Enter a number: ")
print sum
count = 0
max_count = 7
A = 0
B = 1
while count < max_count :
firstNum = A
secondNum = B
A = secondNum
B = firstNum + secondNum
print firstNum,
count = count + 1
> There are several different tests that a expression can have.
Here is a table of all of them:
operator function
-------- --------
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal
<> another way to say not equal
# Guessing a number
aNumber = 5
guess = 0
while aNumber != guess :
guess = input("Guess a number: ")
if guess < aNumber :
print "Too low."
elif guess > aNumber :
print "Too High."
else :
print "Right Guess"
> Exercises
1. Write a program that asks for two numbers. If the sum of the
numbers is greater than 100, print “That is big number”.
2. Write a program that asks the user their name, if they enter
Biju say ”Biju is a nice name”, if they enter ”Ramu”, tell them
Ramu is a good name, otherwise tell them ”You can find a better
name”.
strPasswd = "123456"
count = 1
guessPasswd = raw_input("Enter the password: ")
while strPasswd != guessPasswd or count <= 3 :
if guessPasswd != strPasswd :
print "Wrong Guess"
if count != 3 :
count = count + 1
else :
print "No further chance.."
break
guessPasswd = raw_input("Enter the password: ")
else :
print "Right Guess"
break
width = 20
height = 2
print "width = ", width, " height = ", height, \
" Area = ", area(width, height)
def factorial(n) :
if n <= 1 :
return 1
else :
return n * factorial(n-1)
> Exercises
def showMenu() :
print "----"
print "MENU"
print "----"
print "1. Show Menu:"
print "2. Convert from celsius: "
print "3. Convert from fahrenheit: "
print "4. Quit the program: "
return
def celsiusToFahrenheit(ctemp) :
return (9.0/5.0*ctemp+32)
def fahrenheitToCelsius(ftemp) :
return (ftemp-32)*5.0/9.0
choice = 1
while choice != 4 :
if choice == 1 :
showMenu()
elif choice == 2 :
ctemp = input("Enter temperature in celsius: ")
print "Temperature in Fahrenheit is : ",
celsiusToFahrenheit(ctemp)
elif choice == 3 :
Python-10
- Printing a List
print demolist
- Length of list
len(demolist)
index = 0
while index < len(demolist)
print "demolist[", index, "] :", demolist[index]
index = index + 1
- OR -
- Sorting a list
demolist.sort()
if 'life' in demolist :
print "Item found in the list"
else :
print "Item not found in the list"
- Slicing a list
list = [0,’Fred’,2,’S.P.A.M.’,’Stocking’,42,"Jack","Jill"]
list[2:4]
[2, ’S.P.A.M.’]
Python-12
list[1:5]
[’Fred’, 2, ’S.P.A.M.’, ’Stocking’]
demolist = [1,2,3,4]
sum = 0
for item in demolist :
sum = sum + item
print sum
Python-13
- OR -
oneToTen = range(1,11)
print oneToTen #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
oneToTen = range(1,11)
for count in oneToTen :
print count
- OR -
> Dictionary
A dictionary have keys and values. The Keys are used to find the
values. Keys must be unique. Keys can be strings or numbers. Keys
point to values. Values can be any type of variable (including
lists or even dictionaries).
d = {
key1 : value1,
key2 : value2
}
dict = {
'Biju' : 'biju@rediffmail.com',
Python-14
'Raju' : 'raju@hotmail.com',
'Dipu' : 'dipu@gmail.com'
}
if 'Biju' in dict :
print "Email id of {0} is {1}".format('Biju', dict['Biju'])
# ---- OR ----
if dict.has_key('Biju'):
print "Email id of {0} is {1}".format('Biju', dict['Biju'])
def showMenu() :
print "1. Add a phone number"
print "2. Print phone numbers"
print "3. Remove phone number"
print "4. Lookup a phone number"
print "5. Quit"
def addPhoneNo() :
name = raw_input("Name: ")
phoneNo = raw_input("Telephone no: ")
phoneBook[name] = phoneNo
def showPhoneBook() :
print "** Telephone Book **"
for name, phoneNo in phoneBook.items():
print "Name: {0} \t PhoneNo: {1}".format(name, phoneNo)
def removePhoneNo() :
name = raw_input("Enter name: ")
if phoneBook.has_key(name) :
del phoneBook[name]
else :
print "No such name"
def searchPhoneBook() :
name = raw_input("Enter name: ")
if phoneBook.has_key(name) :
print "Phone number of {0} is {1}".format(name,phoneBook[name])
else :
print "No such name"
phoneBook = {}
showMenu()
choice = 0
while choice != 5 :
choice = input("Enter your choice: ")
if choice == 1 :
addPhoneNo()
elif choice == 2 :
showPhoneBook()
elif choice == 3 :
removePhoneNo()
elif choice == 4 :
searchPhoneBook()
Python-16
import calendar
year = input("Type in the year number:")
calendar.prcal(year)
# -- OR --
- Spliting strings
import string
string.split("This is a bunch of words")
[’This’, ’is’, ’a’, ’bunch’, ’of’, ’words’]