Python Lab Manuals 2015
Familiarization of Hardware components
SMPS
Switched mode power supply. Which provides different voltage levels for different devices in system. Mainly +5v and +12v supply is needed.MOTHERBOARD
Motherboard is the physical platform on which the components are inserted. The motherboard uses +12v supply to work. On motherboard it have a power connector for this.
CPU Socket - Based of the processor type and technology and the number of pins
CPU Fan – Along with the heat sink, it cools down the processor from reaching extreme temperatures
IDE – Integrated Development Environment for developing programs
Jumpers – For changing the default hardware configuration
PANELS – For external devices
PCI slots – For connecting addon cards
AGP – Accelerated Graphics Port for Graphics cards
FDDI connector – Fiber-optic Digital Data Interface
DIMM slots – Dual In-line Memory Module for connecting memory cards
PROCESSOR
Main part of the system. It process the input and produce a result. The processors are of different types. It depends on applications and also specifications are different for different companies and versions. It uses the IP property which is different for different companies. Processor are not only used with computers but also with many other devices such as mobiles. Processors are also available for special purposes such as DSP(embedded system applications).Most popular manufacturersRAM
Random Access Memory is the primary storage device in the system. It may be upto 4gb available now. It is mainly of 2 types SDRAM and DDRAM. In other devices such as mobile phones another type of memory devices such as flash memory are used. it is connected to the DIMM socket.
HARDDISK
It is the permanent storage device of a system.It can store several 100 GBs of data.
It uses platters to store data. It has actuators and heads for access data.
It divide the disk in tracks and sectors.
KEYBOARD
Keyboard controller detects a key press, Controller sends a code to the CPU represents the key pressed. Controller notifies the operating system Operating system responds Controller repeats the letter if heldMOUSE
All modern computers have variants. Allows users to select objects Pointer moved by the mouseMechanical mouse – Uses electro-mechanical wheels to convey 2D information
Optical mouse – Uses optical sensors to detect changes in the 2D space
Touch screens – Uses touch and pressure sensors to move cursors and objects on screen, also used with stylus for drawing and modeling tools
MONITORS
Most common output device. Connects to the video card categorized by color output.Monochrome
Color
Cathode Ray Tube (CRT)
Most common type of monitor Electrons fired from the back i.e. from the electron gun Electrons excite phosphor to glow. Phosphor is arranged in dots (triads) called pixels dot mask ensures proper pixel is lit
CRT drawbacks
Very large & heavy
Consumes a lot of power
Liquid Crystal Display (LCD)
Commonly found on laptops
Desktop versions exist
Solve the problems of CRT
Fluorescent lights provide illumination
More expensive than CRT
Must sit directly in front of screen
Plasma monitor
Gas is excited to produce light
Familiarization of Linux Operating system
Operating Systems: An operating system (OS) is a set of computer programs that manage the hardware and software resources of a computer. OS acts as the interface between the user and the hardware.
Linux
Linux is a free open-source operating system based on Unix. Linux was originally created by Linus Torvalds with the assistance of developers from around the globe. Linux is free to download, edit and distribute. Linux is a very powerful operating system and it is gradually becoming popular throughout the world.Following are some commonly using LINUX commands.
LINUX Command Effect
mkdir make a directory
cd change directory
pwd identifying current working directory
rmdir removing a directory
cd changing current working directory
ls listing directory contents
mv renaming files
cp copying a file
rm deleting files
sort sorting files
cat displaying the contents of a file
pg displaying the contents of a file page by page
file displaying file type
more displaying the contents of a file page by page
passwd changing the password
man getting online help
who am i displaying the login details of the users who gives this command
date displaying the date
cal displaying the calendar
tail displaying the last few lines of a file
head displaying the last few lines of a file
Expt1. Python Program to Add Two Numbers
Aim: Implement a program to add two numbers .Algorithm:
1.Start
2.Input 2 numbers num1 and num 2
3.Let sum= num1+num2
4.Print sum
5.Stop
Program:
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = num1+num2
# Display the sum
print sum
Output:
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
Expt2. Python Program to find the area of triangle
Aim: Implement a program to find the area of triangleAlgorithm:
1.Start
2.Read three sides (a,b,c)
3.calculate s=(a+b+c)/2
4. calculate area=sqrt(s*(s-a)*(s-b)*(s-c))
5.print area
6.Stop
Program:
# Three sides of the triangle a, b and c are provided by the user
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
# calculate the semi-perimeter
s = (a + b + c) / 2
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Output:
Enter first side: 5
Enter second side: 6
Enter third side: 7
The area of the triangle is 14.70
Expt3. Python Program to swap two variables
Aim: Implement a program to swap two variables provided by the user.Algorithm
1: Start
2: read 'a' and 'b' value
3: inter change the values
4.temp=a
5.a=b
6.b=temp
7. write a and b values.
8.stop
Program:
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print 'The value of x after swapping:”,x
print 'The value of y after swapping: “,y
Output:
Enter value of x: 5
Enter value of y: 10
The value of x after swapping: 10
The value of y after swapping: 5
.
Expt4. Python Program to convert temperature in Celsius to Fahrenheit
Aim: Implement a program to convert temperature in Celsius to FahrenheitAlgorithm
1: start
2: read the temperature in centigrade
3: store the value in celsius
4: set farenheit to 32+ (1.8*celsius)
5: print value of celsius, farenheit
6: stop
Program:
# Input is provided by the user in degree Celsius
# take input from the user
celsius = float(input('Enter degree Celsius: '))
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
Output:
Enter degree Celsius: 37.5
37.5 degree Celsius is equal to 99.5 degree Fahrenheit
Expt5 . Check if the number is positive or negative or zero
Aim: Implement a program to check if the number is positive or negative or zero
Algorithm:
1.Start
2. Read Num
3.Is Num > 0
4.Print “Positive”
5.Else if Num<0
6.Print “Negative”
7.Else Print “Zero
8.Stop
Program:
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Output :
Enter a number: 2
Positive number
Expt6. Check if the number is odd or even
Aim: Implement a program to check if the number is odd or even.
Algorithm:
1.Start
2.If (n%2=0) then
3.Print number is even
4.else
5.Print number is odd
6.Stop
Program:
# Python program to check if the input number is odd or even.
# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd number.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print “Even"
else:
print “Odd”
Output :
Enter a number: 43
Odd
Expt7. Largest number among the three input numbers
Aim: Implement a program to find the largest number among the three input numbers
Algorithm
Start
Read variables num1,num2 and num3
If num1>num2 and If num1>num3
Display num1 is the largest number.
Else Display num3 is the largest number.
Else If num2>num3
Display num2 is the largest number.
Else num3 is largest number
Stop
Program:
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
Output :
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14.0
Expt8 Multiplication table
Aim: Implement a program to print the multiplication table (from 1 to 10) of a number input by the user
Algorithm:
1.Start
2.Input Number ‘num’
3.repeat step 4 for i=1 to 11
4.print num X i = num*i
5Stop
Program:
# take input from the user
num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)
Output:
Display multiplication table of? 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
Expt9 Factorial of a number
Aim: Implement a program to find the factorial of a number provided by the user.
Algorithm:
1:Start
2:Declare variables n,factorial and i.
3:Initialize variables factorial←1,i←1
4:Read value of n
5:Repeat the steps until i=n
5.1: factorial←factorial*i
5.2: i←i+1
6:Display factorial
7:Stop
Program:
# take input from the user
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output :
Enter a number: -2
Sorry, factorial does not exist for negative numbers
Expt10 Sum of N natural numbers
Aim: Implement a program to find the sum of natural numbers up to n where n is provided by user.
Algorithm:
1.Start
2.Read the limit ‘n’
3. let i=0
4.for i<=n repeat steps 5&6
5.sum=sum+i
6.i=i+1
7.print sum
8.Stop
Program:
# take input from the user
num = int(input("Enter the limit: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
Output:
Enter the limit: 16
The sum is 136
Expt11 Fibonacci sequence
Aim: Implement a program to find the Fibonacci sequence up to n-th term where n is provided by the user.
Algorithm:
1: Start
2: set a=0,b=1,c=0,i=1
3:Input value for n
4:print a,b
5: if i<=n go to step6 else go to step 10
6:c=a+b
7:print c
8:a=b,b=c,i=i+1
9:repeat step 5
10:stop
Program:
# Program to display
# take input from the user
nterms = int(input("How many terms? "))
# first two terms
a = 0
b = 1
c=0
print a,b
for i in range (2,n-1):
c=a+b
a=b
b=c
print c
Output:
How many terms? 10
Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
Expt12 Add 2 numbers using function
Aim: Implement a program to add 2 numbers using functions.
Algorithm:
1.Start
2.Input 2 numbers
3.Call add(a,b)
4.print sum
5.stop
Function add()
1.Start
2 return a+b
3.stop
Program:
def add(a,b):
return a + b
print "The first number you want to add?"
a = input("First no: ")
print "What's the second number you want to add?"
b = input("Second no: ")
result = add(a, b)
print "The result is”,result
Output:
The first number you want to add? 2
What's the second number you want to add? 3
The result is:5
Expt13 Calculator
Aim: Implement a program to make a simple calculator that can add, subtract, multiply and divide using functions.
Algorithm:
1.Start
2.Enter the two inputs x & y
3 Choose which operation
4.if addition call function add()
5.if subtraction call function sub()
6. if multiplication call function mul()
7. if division call function div()
8.stop
Function add():
Return x+y
Function sub():
Return x-y
Function mul():
Return x*y
Function div():
Return x/y
Program:
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x / y
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
Output:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210
Expt14 Python Program to Add Two arrays using function
Aim: Implement a program to add two matrix
Algorithm:
1.Start
2.Enter The first matrix
3.Enter the second matrix
3.call function Add(m1,m2)
4.print result
5.Stop
Function add(m1,m2)
1.Start
2.sum= append(m1[i][j]+m2[i][j])
4.Stop
Program:
def add(m1,m2):
result=[]
for i in range(0,n):
sum1=[]
for j in range(0,m):
result.append(m1[i][j]+m2[i][j])
sum1.append(result)
return sum1
n=input("enter matrix limit")
m=input("enter matrix limit")
a=[]
print "first matrix"
for i in range(0,n):
b=[]
for i in range(0,m):
b.append(input())
a.append(b)
print "second matrix"
c=[]
for i in range(0,n):
d=[]
for i in range(0,m):
d.append(input())
c.append(d)
print add(a,c)
Output :
enter matrix limit:2
enter matrix limit:2
first matrix:2 3 4 5
second matrix:4 5 6 7
6 8
10 12
Expt15 Factorial of a number
Aim: Implement a program to find the factorial of a number using recursion
Algorithm:
1.Start
2.Enter he number ‘n’
3.call function factorial(n)
4.print result
5.Stop
Function factorial()
1.Start
2.if n=1 return n
3.if not return n*factorial(n-1)
4.Stop
Program:
# Python program to find the factorial of a number using recursion
def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
Output :
Enter a number: 7
The factorial of 7 is 5040
Expt16 String Palindrome
Aim: Implement a program to check if a string is palindrome or not
Algorithm:
Input a String
Make it suitable for caseless comparison using casefold() function
Reverse the string
Check if the string is equal to its reverse then go to 5 else go to 6
Print string Is a Palindrome go to step 7
Print string Is Not a Palindrome
Stop
Program:
# Program to check if a string is palindrome or not
# take input from the user
my_str = input("Enter a string: ")
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")
Output :
Enter a string: malayalam
It is palindrome
Expt17 Lexicographic sorting
Aim: Implement a program to illustrate how words can be sorted lexicographically (alphabetic order).
Algorithm:
Start.
Read the string .
Breakdown the string into a list of words using split() function.
Sort the list using sort() function.
Display the sorted words.
Stop.
Program:
# take input from the user
my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
Output:
Enter a string: Hello this Is an Example With cased letters
Example
Hello
Is
With
an
cased
letters
this
Expt18 Number of each vowel in a string
Aim: Implement a Program to count the number of each vowel in a string
Algorithm:
1.Start
2.Enter the string s.
3.Take each character in the string and compare with ‘a,e,i,o,u’.
4.If found increment corresponding counter by one.
5.Print the counter values.
6.Stop
Program:
# string of vowels
vowels = 'aeiou'
# take input from the user
ip_str = input("Enter a string: ")
# make it suitable for caseless comparisions
ip_str = ip_str.casefold()
# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)
# count the vowels
for char in ip_str:
if char in count:
count[char] += 1
print(count)
Output:
Enter a string: Hello, have you tried our turorial section yet?
{'e': 5, 'u': 3, 'o': 5, 'a': 2, 'i': 3}4)
Expt19 Set operations
Aim: Implement a Program to implement set operations
Algorithm:
1.Start
2.Enter 2 sets E,N
3.Perform set union
4.Perform set intersection
5.Perform set difference and symmetric difference
6.Print results
7.Stop
Program:
# define two sets
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)
Output:
Union of E and N is {0, 1, 2, 3, 4, 5, 6, 8}
Intersection of E and N is {2, 4}
Difference of E and N is {8, 0, 6}
Symmetric difference of E and N is {0, 1, 3, 5, 6, 8}
Expt20: LIST and SLICING
Aim: Implement a Program to implement list and slicing operations.
Algorithm:
1.Start
2.Define a list
3. Slice from third index to index one from last
4.stop
Program:
values = [100, 200, 300, 400, 500]
# Slice from third index to index one from last.
slice = values[2:-1]
print(slice)
Output:
[200, 300]
Expt21: Dictionary
Aim: Implement a Program to implement a dictionary comprehension.
Algorithm:
1.Start
2. Create a dictionary
3.Update existing entry
4.Add a new entry.
5.Print the updates.
6.Stop
Program:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # update existing entry
dict['School'] = "DPS School" # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Output:
dict['Age']: 8
dict['School']: DPS School
Expt22 TUPLES
Aim: Implement a Program to implement the concept of tuples.
Algorithm:
1.Start
2.Create a Zero-element tuple tuple a=()
3. Create a One-element tuple b = ("one",)
4. Create a Two-element tuple c = ("one", "two")
5.Print tuples and length.
6.Stop
Program:
# Zero-element tuple.
a = ()
# One-element tuple.
b = ("one",)
# Two-element tuple.
c = ("one", "two")
print(a)
print(len(a))
print(b)
print(len(b))
print(c)
print(len(c))
Output:
()
0
('one',)
1
('one', 'two')
2
Expt23 Pickling
Aim: Implement a Program to implement the concept of pickling.
Algorithm:
1.Start
2.Create a dictionary
3.Save a dictionary into a pickle file.
4. Load the dictionary back from the pickle file.
5.Dispaly the dictionary.
6.Stop
Program:
# Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.p", "wb" ) )
# Load the dictionary back from the pickle file.
import pickle
favorite_color = pickle.load( open( "save.p", "rb" ) )
print favorite_color
# favorite_color is now { "lion": "yellow", "kitty": "red" }
Output:
{ "lion": "yellow", "kitty": "red" }
Expt24 File handling
Aim: Implement a Program to implement the concept of files
Algorithm:
1.Start
2.Open a file in write mode
3.Save some data.
4.Display the content in the file
6.Stop
Program:
colors = ['red\n', 'yellow\n', 'blue\n']
f = open('colors.txt', 'w')
f.writelines(colors)
f.close()
Output:
Red
Yellow
blue
Expt1 HCF
Aim: Implement a Python program to find the H.C.F of two input numbers.
Program:
# define a function
def hcf(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return
# take input from the user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", hcf(num1, num2))
Output:
Enter first number: 54
Enter second number: 24
The H.C.F. of 54 and 24 is 6
Expt2 REMOVE PUNCTUATION
Aim: Implement a Python program to remove to all punctuation from the string provided by the user
Program:
# Program
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# take input from the user
my_str = input("Enter a string: ")
# remove punctuation from the string
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
# display the unpunctuated string
print(no_punct)
Output:
Enter a string: "Hello!!!", he said ---and went.
Hello he said and went
Expt3 DECIMAL TO BINARY,OCTAL & HEXA DECIMAL
Aim: Implement a Python program to convert decimal number into binary, octal and hexadecimal number system
Program:
# Python program to convert decimal number into binary, octal and hexadecimal number system
# Take decimal number from user
dec = int(input("Enter an integer: "))
print("The decimal value of",dec,"is:")
print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")
Output:
Enter an integer: 344
The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal
Expt1 CALENDAR
Aim: Implement a Python program to display calendar of given month of the year
Program:
# import module
import calendar
# ask of month and year
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
# display the calendar
print(calendar.month(yy,mm))
Output:
Enter year: 2014
Enter month: 11
November 2014
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30.
Expt2 ASCII VALUE
Aim: Implement a Python program to find the ASCII value of the given character
Program:
# Take character from user
c = input("Enter a character: ")
print("The ASCII value of '" + c + "' is",ord(c))
Output
Enter a character: p
The ASCII value of 'p' is 112
VIVA QUESTIONS
1) The various cards in a PC require _______ voltage to function.
a) AC
b) DC
2) A byte is equivalent to...?
a) 8 bits
b) 10 bits
3) SMPS stands for:
a) Switch Mode Power Supply
b) Simple Mode Power Supply
4) Which of these in not a core datatype?
a) Lists
b) Dictionary
c) Tuples
d) Class
5) Following set of commands are executed in shell, what will be the output?
>>>str="hello"
>>>str[:2]
>>>str
a) he
b) lo
c) olleh
d) hello
6) What dataype is the object below ?
L = [1, 23, 'hello', 1]
a) List
b) dictionary
c) array
d) tuple
7) In order to store values in terms of key and value we use what core datatype.
a) List
b) tuple
c) class
d) dictionary
8) What is the average value of the code that is executed below ?
>>>grade1 = 80
>>>grade2 = 90
>>>average = (grade1 + grade2) / 2
a) 85
b) 85.0
c) 95
d) 95.0
9) Select all options that print
hello-how-are-you
a) print(‘hello’, ‘how’, ‘are’, ‘you’)
b) print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-’ * 4)
c) print(‘hello-’ + ‘how-are-you’)
d) print(‘hello’ + ‘-’ + ‘how’ + ‘-’ + ‘are’ + ‘-’ + ‘you’)
10) What is answer of this expression, 22 % 3 is?
a) 7
b) 1
c) 0
d) 5
11) What is the output of this expression, 3*1**3?
a) 27
b) 9
c) 3
d) 1
12) Int(x) means variable x is converted to integer.
a) True
b) False
13) Which one of the following have the same precedence?
a) Addition and Subtraction
b) Multiplication and Division
c) a and b
d) None of the mentioned
14) What is the output when following statement is executed ?
>>>"a"+"bc"
a)b
b) bc
c) bca
d) abc
15) What is the output when following statement is executed ?
>>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc
16) What is the output when following code is executed ?
>>> str1 = 'hello'
>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]
a) olleh
b) hello
c) h
d) o
17) What arithmetic operators cannot be used with strings ?
a) +
b) *
c) -
d) **
18) Say s=”hello” what will be the return value of type(s) ?
a) int
b) bool
c) str
d) String
19) What will be the output?
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
d1 == d2
a) True
b) False
c) None
d) Error
20) What is the output?
d = {"john":40, "peter":45}
d["john"]
a) 40
b) 45
c) “john”
d) “peter”
21)Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” what command do we use
a) d.delete(“john”:40)
b) d.delete(“john”)
c) del d["john"]
d) del d(“john”:40)
22) Which of the following is a Python tuple?
a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
23) What will be the output?
>>>t=(1,2,4,3)
>>>t[1:3]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
24)Suppose listExample is ['h','e','l','l','o'], what is len(listExample)?
a) 5
b) 4
c) None
d) Error
25) Suppose list1 is [1, 3, 2], What is list1 * 2 ?
a) [2, 6, 4]
b) [1, 3, 2, 1, 3]
c) [1, 3, 2, 1, 3, 2]
D) [1, 3, 2, 3, 2, 1]
26) Which keyword is use for function?
a) Fun
b) Define
c) Def
d) Function
27) What is the output of the below program ?
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x)
a) x is still 50
b) x is still 2
c) x is still 100
d) None of the mentioned
28) What is the range of values that random.random() can return?
a) [0.0, 1.0]
b) (0.0, 1.0]
c) (0.0, 1.0)
d) [0.0, 1.0)
29)What is the output of the below program?
def C2F(c):
return c * 9/5 + 32
print C2F(100)
print C2F(0)
a) 212
32
b) 314
24
c) 567
98
d) None of the mentioned
30) What is the output of the following?
for i in range(10):
if i == 5:
break
else:
print(i)
else:
print("Here")
a) 0 1 2 3 4 Here
b) 0 1 2 3 4 5 Here
c) 0 1 2 3 4
d) 1 2 3 4 5
Comments
Post a Comment