You are on page 1of 17

EX.

NO: 4
BASIC PYTHON COMMANDS
DATE:

AIM:

To study and execute basic python commands.

PROCEDURE:

Starting Python

Start Python in interactive mode by invoking python in the command line.

$ python
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Arithmetic expressions

>>> celsius = 100


>>> farenheit = (9 * celsius / 5) + 32
>>> print farenheit
212
>>>

Indentation

Python programs get structured through indentation i.e code blocks are defined by
indentation,Python provides no braces to indicate block of code for class ,functions and
flow control.

The number of spaces in the indentation is not fixed value but all statements within the
block must be indented the same amount.

Control Flow

if condition:
statement1
statement2...
elif condition:
statement1
statement2...
else:
statement1
statement2..

initialization;
while(condition)
{
//Code block to execute something
}

for iterator_var in sequence:


statements(s)

Lists and slicing

Lists: There are the most versatile sequence type. The elements of a list can be any object
and lists are mutable.

The wind speed data (in km/hr) from a weather station, for a single day, obtained every 2
hours, starting from 12:00am: 3, 5, 3, 2, 0, 0, 5, 5, 11, 5, 10, 2.

1. Represent the data using a list.


2. Extract the wind speed at noon.
3. Extract all the wind speeds in the afternoon.
4. Extract the last measurement of the day.

>>> wind_speed = [3, 5, 3, 2, 0, 0, 5, 5, 11, 5, 10, 2]


>>> noon = wind_speed[6]
>>> print noon
5
>>> afternoon = wind_speed[7:12]
>>> print afternoon
[5, 11, 5, 10, 2]
>>> last = wind_speed[-1]
>>> print last
2
>>>

>>>myList = [1, 'hello', 2.35, True]


>>>print(myList)
List iteration
>>> wind_speed = [3, 5, 3, 2, 0, 0, 5, 5, 11, 5, 10, 0]
>>> sum = 0
>>> for item in wind_speed:
sum = sum + item
>>> avg = sum / len(wind_speed)
>>> print avg
4

List Methods
mylist=[10,20,30,40,50]
m=len(mylist)
print(mylist)
mylist.insert(0,5)
print(mylist)
mylist.append(60)
print(mylist)

Tuples and Slicing

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square brackets.These are like lists, But Tuples
are immutable.

tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
slice = tuplex[3:5]
print(_slice)
slice = tuplex[:6]
print(slice)
slice = tuplex[5:]
print(_slice)
slice = tuplex[:]
print(_slice)
slice = tuplex[-8:-4]
print(_slice)
tuplex = tuple("HELLO WORLD")
print(tuplex)
slice = tuplex[2:9:2]
print(_slice)
_slice = tuplex[::4]
print(_slice)
slice = tuplex[9:2:-4]
print(_slice)

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print tup1[0];
print tup2[1:5]

tup1 = (12, 34.56);


tup2 = ('abc', 'xyz');

tup3 = tup1 + tup2;


print tup3

tup = ('physics', 'chemistry', 1997, 2000);


print tup;
del tup;
print "After deleting tup : ";
print tup;

Dictionary and Slicing

Dictionary in Python is an unordered collection of data values, used to store data values
like a map, which unlike other Data Types that hold only single value as an element,
Dictionary holds key:value pair. Key value is provided in the dictionary to make it more
optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is
separated by a ‘comma’.
A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary
must be unique and of immutable data type such as Strings, Integers and tuples, but the
key-values can be repeated and be of any type.

phonenumbers = {'Jack':'555-555', 'Jill':'555-556'}


phonebook = {}
phonebook["Jack"] = "555-555"
phonebook["Jill"] = "555-556"
print phonebook

dict={‘Name’:’SteveJobs’,’Age’:70,’’class’:’First’};
print(dict[‘Name’])
print(dict[‘Age’])
Strings and slicing
These are a special type of sequence that can store only characters and having special
notations.

Perform the following operations, on the word "newsworthy":


1. Extract the second letter.
2. Extract the first four letters.
3. Extract the last six letters.

>>> word = "newsworthy"


>>> print len(word)
10
>>> print word[1]
e
>>> print word[0:4]
news
>>> print word[4:10]
worthy
>>>

String iteration and concatenation


Reverse the word "linux" using string iteration and concatenation

>>> word = "linux"


>>> reversed = ""
>>> for ch in word:
... reversed = ch + reversed
...
>>> print reversed
xunil
>>>

String multiplication
Print a 5 step right-angled triangle using string multiplication.

>>> max = 5
>>> for i in range(0, max):
... print "*" * (i+1)
...
*
**
***
****
*****
>>>

EX.NO: 5
PYTHON PROGRAMMING
DATE:

A. Write a program to check whether a number entered by user is prime or not.

AIM:To write a program to check whether a number entered by user is prime or not.

Algorithm:

Step 1: Start
Step 2: Declare variables n,i,flag.
Step 3: Initialize variables
flag←1
i←2
Step 4: Read n from user.
Step 5: Repeat the steps until i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop

PROGRAM
# take input from the user
num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

OUTPUT
user@boss:/$ vi prime.py
user@boss:/$ python prime.py
Enter a number: 7
(7, 'is a prime number')
user@boss:/$ python prime.py
Enter a number: 123
(123, 'is not a prime number')
(3, 'times', 41, 'is', 123)
RESULT:
Thus, we implemented a python program to find the prime number.

B.Write a program to find the Fibonacci series till n term

AIM :

To Write a program to find the Fibonacci series till n term

ALGORITHM :

Step 1: Start
Step 2: Declare variables first_term,second_term and temp.
Step 3: Initialize variables first_term←0 second_term←1
Step 4 : Get the input as nterm
Step 5: Display first_term and second_term
Step 6: Repeat the steps until second_term≤nterm
temp←second_term
second_term←second_term+first term
first_term←temp
Display second_term
Step 7: Stop

PROGRAM :

nterms = int(input("How many terms? "))


# first two terms
n1 = 0
n2 = 1
count = 0

# check if the number of terms is valid


while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

OUTPUT

user@boss:/$ python fib.py


How many terms? 5
0
1
1
2
3

RESULT:

Thus, we implemented a python program to find the Fibonacci number.

C. Write a program to find how many times an element occurred in list and find the sum of
elements in the list.

AIM:

To write a program to find how many times an element occurred in list and find the sum of
elements in the list using predefined function and userdefined function

ALGORITHM:

Step 1:Take in the number of elements for the first list and store it in a variable.
Step 2:Take in the elements of the list one by one.
Step 3: Then take in the number to be searched in the list.
Step 4: Use a for loop to traverse through the elements in the list and increment the count
variable.
Step 5:. Display the value of the count variable which contains the number of times a
particular number occurs in a list

Step 6: In the for loop append each number to the list.

Step7 find the sum of all the elements in a list.


Step 8:Print the result.

#-*-coding:utf-8-*-

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
k=0
num=int(input("Enter the number to be counted:"))
for j in a:
if(j==num):
k=k+1
print("Number of times",num,"appears is",k)

for ele in range(0, len(a)):

total = total + a[ele]

# printing total value


print("Sum of all elements in given list: ", total)

OUTPUT

user@boss:/$ python list.py

Enter number of elements:5


Enter element:2
Enter element:3
Enter element:4
Enter element:5
Enter element:6
Enter the number to be counted:2
('Number of times', 2, 'appears is', 1)
('Sum of all elements in given list: ', 20)

RESULT:

Thus, we implemented a python program to find how many times an element occurred in
list and find the sum of elements.

D. Write a program to do different operations on tuple

AIM:

To perform different operations on tuple

ALGORITHM

STEP 1: Create tuple from list.


STEP 2. check whether an element exists within a tuple

STEP 3:. to remove an item from a tuple


Step 4: To find the index of an item of a tuple

Step 5: To create dictionary from tuple

#convert list to tuple


listx = [5, 10, 7, 4, 15, 3]
print(listx)
#use the tuple() function built-in Python, passing as parameter the list
tuplex = tuple(listx)
print(tuplex)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it will create a new tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print("r" in tuplex)
print(5 in tuplex)
index = tuplex.index("w")
print(index)
#define the index from which you want to search
index = tuplex.index("u", 5)
print(index)
tuplex = ((2, "w"),(3, "r"))
print(dict((y, x) for x, y in tuplex))

OUTPUT

user@boss:/$ python tuple.py

[5, 10, 7, 4, 15, 3]

(5, 10, 7, 4, 15, 3)

(5, 10, 4, 15, 3)

True

False

{'r': 3, 'w': 2}

RESULT:

Thus, we implemented a python program to create a Tuple.


E. Write a program to create a telephone database using dictionaries.

AIM:

To create a program to create a telephone database using dictionaries.

ALGORITHM:

STEP 1: Enter Input either Add/Search/Delete/Update/View/Exit

STEP 2: If option A or a is entered add the number in Dictionary

STEP 3: If option D or d delete the number in Dictionary

STEP 3: If option S or s search the number in Dictionary and print .

STEP 4: If option U or u update the number in Dictionary and print .

STEP 5: If option V or v View the number in Dictionary and print .

STEP 6: If option is Q or q quit

STEP 7: If any other option print invalid command

PROGRAM:

print "*****TELEPHONE DIRECTORY***"


list1=[]
list2=[]
dict1={}
temp=100
n=input("Enter the number of contacts : ")
for i in range(0,n):
name1=raw_input("Enter your name: ")
num=input("Enter your phone number: ")
list1.extend([name1])
list2.extend([num])
dict1=dict(zip(list1,list2))#to convert two list into dictionary
print dict1

print """
1:Add a contact
2:Search a contact
3:Delete a contact
4:Update a contact
5:View directory
6:Exit"""
choice=input("Enter your choice")

def add(dict1):
name3=raw_input("Enter the new name you want to add: ")
num3=input("Enter the number: ")
dict1[name3]=num3
print dict1

def search(dict1,n,list1,temp):
name2=raw_input("Enter the name whose number is to be found: ")
for i in range(0,n):
if list1[i]==name2:
temp=i
if temp!=100:
print "Number is : ",list2[temp]

def delete(dict1):
name4=raw_input("Enter the name you want to delete: ")
del dict1[name4]
print dict1

def update(dict1,n,list1):
name5=raw_input("Enter the name which you want to update: ")
for i in range(0,n):
if list1[i]==name5:
temp=i
if temp!=100:
num5=input("Enter the new number")
dict1[name5]=num5
print dict1
def view(dict1):
print dict1

if (choice==1):
add(dict1)
elif (choice==2):
search(dict1,n,list1,temp)
elif (choice==3):
delete(dict1)
elif (choice==4):
update(dict1,n,list1)
else:
view(dict1)

OUTPUT
Enter the number of contacts : 4
Enter your name: stevejobs
Enter your phone number: 99123456
Enter your name: hilary
Enter your phone number: 7689092341
Enter your name: kavin
Enter your phone number: 897654321
Enter your name: athithi
Enter your phone number: 90213456
{'athithi': 90213456, 'kavin': 897654321, 'stevejobs': 99123456, 'hilary': 7689092341L}

1:Add a contact
2:Search a contact
3:Delete a contact
4:Update a contact
5:View directory
6:Exit
RESULT:

Thus, we implemented a python program to create a Dictionary.

F. To write a python program to concatenate first two characters from two string and
reverse a string with string operation.

AIM: To write a python program to concatenate first two characters from two string and
reverse a string with string operation.

ALGORITHM:
STEP 1:Get two strings from the user .
STEP 2:Find a length of the both string .
STEP 3:Print the length of the both string .
STEP 4:Using “if else” condition, check whether the two strings are equal or not.
STEP 5:Concatenate first two characters of the first string and last two character of the
second string.
STEP 6:Print the concatenated string .

string1 = input("Enter first string: ")


string2 = input("Enter second string: ")
print("\nLength of the first string =", len(string1))
print("\nLength of the second string =", len(string2))
if string1 == string2:
print("\nBoth strings are equal to each other.")
else:
print("\nStrings are not equal.")
s1=string1[:2]+string2[:2]
print(s1);
s=""
length = len(s1) - 1
while length >= 0:
s = s + s1[length]
length = length - 1
print s

OUTPUT

user@boss:/$ python string.py


Enter first string: "hello"
Enter second string: "world"
('\nLength of the first string =', 5)
('\nLength of the second string =', 5)

Strings are not equal.


hewo
oweh

RESULT:

Thus, we implemented a python program to manipulate string operations.

You might also like