0% found this document useful (0 votes)
4 views

06 Python Tutorial

The document provides an overview of Python programming, covering topics such as the IDLE environment, basic arithmetic operations, string manipulation, control flow with loops and conditionals, functions, lists, and dictionaries. It includes sample code snippets and exercises for practice. The content is structured to guide beginners through fundamental concepts and practical applications in Python.

Uploaded by

Biju Kuttan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

06 Python Tutorial

The document provides an overview of Python programming, covering topics such as the IDLE environment, basic arithmetic operations, string manipulation, control flow with loops and conditionals, functions, lists, and dictionaries. It includes sample code snippets and exercises for practice. The content is structured to guide beginners through fundamental concepts and practical applications in Python.

Uploaded by

Biju Kuttan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Python-1

> Python GUI is called IDLE (Integrated DeveLopment Environment).

Python 2.0 (#4, Dec 12 2000, 19:19:57)


[GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
Type "copyright", "credits" or "license" for more information.
IDLE 0.6 -- press F1 for help
>>>

The >>> is python prompt. It indicates that you are in interactive


mode.

> Sample Program

#Python is easy to learn


print "Hello, World!"
print "Welcome to Python"

> Comment start with a #

# This is a comment

> Getting Help on python

Go to the Python prompt and type help():

>>> help()

To quit use quit():

>>> quit()

> Arithmetic operations:

Python has six basic operations for numbers:

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

Operation Symbol Example


----------------------------------------------
Exponentiation ** 5 ** 2 == 25
Multiplication * 2 * 3 == 6
Division / 14 / 3 == 4
Remainder % 14 % 3 == 2
Addition + 1 + 2 == 3
Subtraction - 4 - 3 == 1

> Heirarchy of operations is same as in math:

1. parentheses ()
2. exponents **
3. multiplication *, division \, and remainder %
4. addition + and subtraction -

> Expressions

print "2 + 2 is", 2 + 2


print "3 * 4 is", 3 * 4
print 100 - 1 , " = 100 - 1"

> Bitwise Operators

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

> Boolean operators

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.

2. Write a program that shows the use of all 6 math functions.

> Reading a string from the Keyboard

a = raw_input("What is your name ? ")


print "My name is ", a

> Storing data in variables

strName = raw_input("What is your name ? ")


print "My name is ", strName
nAge = 20
print "I am ", nAge, " years old."

> Two ways of printing data on the screen

name = "Biju"
age = 20
print("My name is {0}. I am {1} years old" . format(name,age))

# --- OR ---

print "My name is",name,".I am",age,"years old"

> input and raw_input

raw_input() returns a string while input() returns a number. When


you want the user to type in a number use input() but if you want
the user to type in a string use raw_input().

> Reading numbers from the Keyboard. Also print their type.

aNumber1 = input("Enter an integer : ")


print type(aNumber1)
aNumber2 = input("Enter a floating point number : ")
print type(aNumber2)
Python-4

> String operations - Concatenation and Repetition

Concatenation

strMessage = "Hello " + "World"


print strMessage

Repetition

str = "Hello"
print str*2 # HelloHello
print "world"*3

> Exercise

Write a program that gets 2 string variables and 2 integer


variables from the user, concatenates (joins them together with
no spaces) and displays the strings, then multiplies the two
numbers on a new line.

> Program to calculate area and perimeter of a rectangle

length = input("Enter length: ")


breadth = input("Enter breadth: ")
area = length * breadth
perimeter = 2 * (length + breadth)
print "Area is ", area
print "Perimeter is ", perimeter

> Using While loop

# Program will print from 1 to 10

count = 1
while count <= 10 :
print count
count = count + 1
# use Ctrl+Z to end
Python-5

> Program to print sum of n numbers in interactive mode

sum = 0
n = 0
while n >= 0 :
sum = sum + n
n = input("Enter a number: ")
print sum

> Program to find the sum of numbers

print "Enter numbers to add."


print "Enter 0 to quit. "
sum = 0
aNumber = 1
while aNumber != 0 :
print "Current Sum: " , sum
aNumber = input("Number ? ")
sum = sum + aNumber
print "Total is ", sum

> Program to print fibonacci series - 0 1 1 2 3 5 8

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

> Using if..else statement

# Program to find absolute value of a number

aNumber = input("Enter a number: ")


if aNumber < 0 :
print "Absolute value is ", -aNumber
else :
print "Absolute value is ", aNumber
Python-6

> 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

> Using if..elif statement

# 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"

> Using if..elif statement

# Check whether a number is even or not

aNumber = input("Enter a number: ")


if aNumber % 2 == 0 :
print "Number is even"
elif aNumber % 2 == 1 :
print "Number is odd"
else :
print "Strange number"
Python-7

> 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”.

Answer in file: 01bignumber.txt

# print a message based on sum of two numbers

num1 = input("Enter first number: ")


num2 = input("Enter second number: ")
sum = num1 + num2
if sum > 100 :
print "Sum is greater than 100"
else :
print "Sum is smaller than 100"

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”.

Answer in file: 02aName.txt

# print a message based on the name entered by user

aName = raw_input("Enter your name: ")


if aName == "biju" :
print "It is a good name.."
elif aName == "ramu" :
print "It is a nice name.."
else :
print "You can have a better name.."

3. Modify the password guessing program to keep track of how many


times the user has entered the password wrong. If it is more than
3 times, print “No further chance.”

Answer in file: 03whileORboolean.txt


Python-8

# password guessing program - use of OR operator

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

> Define functions

def (short for define) starts a function definition. It is


followed by a function name and brackets. Parameters are written
inside the brackets. The statements after the : are executed when
the function is used. The statements continue until either the
indented statements end or a return is encountered. The return
statement returns a value back to the place where the function was
called. When a function doesn’t need to send back a value, a
return is optional.

> Using function.

#Finding area of a rectangle.

def area(width, height) :


area = width * height
return area

width = 20
height = 2
print "width = ", width, " height = ", height, \
" Area = ", area(width, height)

Note: a \ can be used to split a long line.


Python-9

> Finding factorial of a number

def factorial(n) :
if n <= 1 :
return 1
else :
return n * factorial(n-1)

num = input("Enter a number to find factorial : ")


print factorial(num)

> Exercises

Rewrite the area.py program done in 3.2 to have a separate


function for the area of a square, the area of a rectangle, and
the area of a circle. (3.14 * radius**2). This program should
include a menu interface.

#program to convert temperature to fahrenheit or celsius

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

ftemp = input("Enter temperature in fahrenheit: ")


print "Temperature in Celsius is : ", fahrenheitToCelsius(ftemp)
choice = input("Enter your choice: ")

> Lists - Variables with more than one value

List is a variable that can hold more than one value.

months=[’January’, ’February’, ’March’, ’April’, ’May’, ’June’, \


’July’, ’August’, ’September’, ’October’, ’November’, \
’December’]

A list consists of items that are numbered starting at 0. In other


words if you wanted January you would use months[0]. Give a list a
number and it will return the value that is stored at that
location.

/ is used as Line continuation character.

Lists can be thought of as a series of boxes. For example, the


boxes created by

demolist = [’life’,42,’the universe’, 6,’and’,7]

would look like this:

Each box is referenced by its number so the statement demolist[0]


would get ’life’, demolist[1] would get 42 and so on up to
demolist[5] getting 7.

- Printing a List
print demolist

- Length of list
len(demolist)

- Storing a value in the list


demolist[6] = 'everything'

- Append an item to the list


demolist.append('everything')
Python-11

- Get index of an item in the list


demolist.index('life')
demolist.index(42)

- Looping through the List

index = 0
while index < len(demolist)
print "demolist[", index, "] :", demolist[index]
index = index + 1

- OR -

demolist = ['life',42,'the universe',6,'and',7 ]


for item in demolist :
print item

- Sorting a list
demolist.sort()

- Searching for an item in the list

if 'life' in demolist :
print "Item found in the list"
else :
print "Item not found in the list"

- Deleting 3rd item from the list


del demolist[2]

- Copy a list into another list

demolist = ['life',42,'the universe',6,'and',7 ]


copy = demolist[:]
print copy

- Slicing a list

Slices are used to return part of a list. The slice operator is in


the form list[first_index:following_index]. The slice goes from
the first_index to the index before the following_index.

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’]

# example to demonstrate usage of List

months=['January', 'February', 'March', 'April', 'May', 'June', \


'July', 'August', 'September', 'October', 'November', \
'December' ]

choice = input("What month (1-12): ")


if choice >= 1 and choice <=12 :
print "Month is : ", months[choice-1]

# ----- using if..else with List --------

months=['January', 'February', 'March', 'April', 'May', 'June', \


'July', 'August', 'September', 'October', 'November', \
'December' ]

print "Check whether an item is in the list."


if "January" in months :
print "Item found in list at ", months.index('January')
else :
print "Item not in list"

# ------ using for loop with List --------

demolist = ['life',42,'the universe',6,'and',7 ]


for item in demolist :
print item

# ------ find sum of elements in the list -------

demolist = [1,2,3,4]
sum = 0
for item in demolist :
sum = sum + item
print sum
Python-13

> Using range()

Syntax: range(start, finish)

Returns a list of numbers. start indicate starting number. finish


is one larger than last number.

>>>print range(1,11) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

- OR -

oneToTen = range(1,11)
print oneToTen #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>>print range(-30,-25) #[-30, -29, -28, -27, -26]

> Using for loop with lists

oneToTen = range(1,11)
for count in oneToTen :
print count

- OR -

for count in range(1,11):


print count

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

Pairs of keys and values are specified in a dictionary by using


the notation:

d = {
key1 : value1,
key2 : value2
}

dict = {
'Biju' : 'biju@rediffmail.com',
Python-14

'Raju' : 'raju@hotmail.com',
'Dipu' : 'dipu@gmail.com'
}

print dict # print contents of dictionary


print dict['Biju']

print "There are {0} items in the dictionary".format(len(dict))

for name, address in dict.items():


print "Key {0} has the value {1} ".format(name,address)

# items() is a method of dictionary class

dict['Siju'] = 'siju@hotmail.com' #adding a key value pair

ab = dict.copy() #creating a copy of dictionary

del dict['Raju'] #deleting a key value pair

ab.clear() #remove all items from dict

# checking whether a key is present in a dictionary

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

#> Creating a phone book with functionalities like:


# 1. Add a phone numbers
# 2. Print phone numbers
# 3. Remove phone numbers
# 4. Lookup a phone number
# 5. Quit
Python-15

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

> Using Modules

import calendar
year = input("Type in the year number:")
calendar.prcal(year)

# -- OR --

from calendar import prcal


year = input("Type in the year number:")
prcal(year)

Import actually looks for a file named calendar.py and reads it


in. If the file is named calendar.py and it sees a ’import
calendar’ it tries to read in itself.

from time import time, ctime


the_time = ctime(time())
print "The time is:",ctime(time())
prev_time = the_time

- Spliting strings

Split converts a string into a list of strings. The string is


split by spaces by default or by the optional second argument (in
this case a comma).

import string
string.split("This is a bunch of words")
[’This’, ’is’, ’a’, ’bunch’, ’of’, ’words’]

string.split("First batch, second batch, third, fourth",",")

[’First batch’, ’ second batch’, ’ third’, ’ fourth’]

You might also like