0% found this document useful (0 votes)
8 views23 pages

Fycs Python

The document contains various practical programming exercises in Python, focusing on control statements, functions, lists, dictionaries, and file handling. It includes code examples for tasks such as calculating the year a user will turn 100, checking if a number is even or odd, generating Fibonacci series, and more. Additionally, it covers advanced topics like checking for pangrams, cloning lists, and reading from files.

Uploaded by

mohdsami39rollno
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)
8 views23 pages

Fycs Python

The document contains various practical programming exercises in Python, focusing on control statements, functions, lists, dictionaries, and file handling. It includes code examples for tasks such as calculating the year a user will turn 100, checking if a number is even or odd, generating Fibonacci series, and more. Additionally, it covers advanced topics like checking for pangrams, cloning lists, and reading from files.

Uploaded by

mohdsami39rollno
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

Practical No.

1
1. Write the program for the following: (by using control statements and
control structure)

A. Create a program that asks the user to enter their name and their age.
Print out a message addressed to them that tells them the year that they will
turn 100 years old.

import datetime
name = input("Hello! Please enter your name: ")
print("Hello " + name)
age = int(input("Enter your age: "))
year_now = [Link]()
# print(year_now.year)
print("You will turn 100 in " + str(int(100-age) + int(year_now.year)))

Output

Page 9

[Link]
B. Enter the number from the user and depending on whether the number is
even or odd, print out an appropriate message to the user.

Code :

# 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("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Python Code :-

Output:-

Page 10

[Link]
C. Write a program to generate the Fibonacci series.

# Program to display the Fibonacci sequence up to n-th term where n is provided


by the user
# change this value for a different result
nterms = 10

# uncomment to take input from the user


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

# first two terms


n1 = 0
n2 = 1
count = 2

# check if the number of terms is valid


if nterms<= 0:
print("Please enter a positive integer")
elifnterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence upto",nterms,":")
print(n1,",",n2,end=', ')
while count <nterms:
nth = n1 + n2

Page 11

[Link]
print(nth,end=' , ')
# update values
n1 = n2
n2 = nth
count += 1

Output

Page 12

[Link]
Fibonacci series by using function

D. Write a function that reverses the user defined value.

# Python Program to Reverse a Number using While loop by using function


defreverse_number(number):
reverse = 0
while(number > 0):
reminder = number %10
reverse = (reverse *10) + reminder
number = number //10
print("Reverse number is ", reverse)
reverse_number(1546)

Page 13

[Link]
Python code :

Output

Same Program on Python2.7 on Command prompt

Page 14

[Link]
E. Write a function to check the input value is Armstrong and also write the
function for Palindrome.

Code:
# Python program to check if the number provided by the user is an Armstrong
number or not
defarmstrong(num):
sum=0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

def palindrome(num):
n = num
rev = 0
while num != 0:
rev = rev * 10
rev = rev + int(num%10)
num = int(num / 10)
if n == rev:
print(n,"is palindrome number")
else:
print(n,"is not a palin")

# take input from the user


num = int(input("Enter a number to chk it is armstrong or not: "))
armstrong(num)
# take input from the user
num = int(input("Enter a number to chk it is palindrome or not: "))
palindrome(num)

Page 15

[Link]
Output

Page 16

[Link]
F. Write a recursive function to print the factorial for a given number.

# Python program to find the factorial of a number using recursion

defrecur_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")
elifnum == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

Page 17

[Link]
Output

Page 18

[Link]
Practical No.2

Write the program for the following: ( by using functions)

A. Write a function that takes a character (i.e. a string of length 1) and


returns True if it is a vowel, False otherwise.

The code and the output is shown in the following screenshot.

B. Define a function that computes the length of a given list or string.

The code and the output is shown in the following screenshot.

Page 19

[Link]
C. Define a procedure histogram() that takes a list of integers and prints a
histogram to the screen. For example, histogram([4, 9, 7]) should print the
following:
****
*******
** *
******
The code and the corresponding output is shown in the following screen shot.

Page 20

[Link]
Practical No.-3
Write the program for the following: ( by using list)

A. A pangram is a sentence that contains all the letters of the English alphabet
at least once, for example: The quick brown fox jumps over the lazy dog.
Your task here is to write a function to check a sentence to see if it is a
pangram or not.

import string, sys


if sys.version_info[0] < 3:
input = raw_input
defispangram(sentence, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset<= set([Link]())
print ( ispangram(input('Sentence: ')) )

Output

Page 21

[Link]
B. Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less
than 5.

# Program to trim list list_trim.py


l1=[1,1,2,3,5,8,13,21,34,55,89]
l2=[]
for i in l1:
if i <5:
[Link](i)
print (l2)

Page 22

[Link]
Practical No.4
Write the program for the following: ( by using list)

A. Write a program that takes two lists and returns True if they have at least
one common member.

Code :
l1=[1,2,3,4,5,6,]
l2=[11,12,13,14,15,6]
for i in l1:
for j in l2:
if i==j:
print ('The 2 list have at least one common element')

Output

B. Write a Python program to print a specified list after removing the 0th,
2nd, 4th and 5th elements.

#print list after removing the 0th, 2nd, 4th and 5th elements.
l1=[1,2,3,4,5,6,7,8,9,0]
print("Original List is",l1)

Page 23

[Link]
print("According to question we have to remove 0th->1,2nd->3,4th->5,5th->6")
[Link](l1[0]) #this line will remove 1 from the list, Therefore l1[0]=2
print("After Removal of 0th element Now List is",l1)
print("Now we have to remove 3 from list which is at 1th position of index")
[Link](l1[1])
print("After Removal of 1st element of New List (original 2nd index element)
is",l1)
print("Now we have to remove 5 from list which is at 2nd position of index")
[Link](l1[2])
print("After Removal of 3rd element of New List (original 4th index element)
is",l1)
print("Now we have to remove 6 from list which is at 2nd position of index")
[Link](l1[2])
print (l1)

Output

Page 24

[Link]
You can try without print statements

Output

C. Write a Python program to clone or copy a list

l1=[2, 4, 7, 8, 9, 0]
print ("Original List is", l1)
l2=l1
print ("Clone List is ",l2)

Page 25

[Link]
Output

Page 26

[Link]
Practical No.5
Write the program for the following: ( by using Dictionary)

A. Write a Python script to sort (ascending and descending) a dictionary by


value.

>>> released={'Python 3.6': 2017,'Python 1.0': 2002, 'Python 2.3': 2010}


>>> for key,value in sorted([Link]()):
print (key,value)
Output:
Python 1.0 2002
Python 2.3 2010
Python 3.6 2017
Only keys sorted:
>>> print (sorted(released))
['Python 1.0', 'Python 2.3', 'Python 3.6']

B. Write a Python script to concatenate following dictionaries to create a new


one.

Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60}


Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Output:
>>> dic1={1:10,2:20}
>>> dic2={3:30,4:40}
>>> dic3={5:50,6:60}
>>> [Link](dic2)
>>> print (dic1)
{1: 10, 2: 20, 3: 30, 4: 40}
>>> [Link](dic3)
>>> print (dic1)

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Page 27

[Link]
C. Write a Python program to sum all the items in a dictionary.
>>> d= {'One':10,'Two':20,'Three':30}
>>> sum([Link]())
60
Practical No.6

Write the program for the following: ( File handling)

A. Write a Python program to read an entire text file.

Code:
'''
Write a Python program to read an entire text file.
'''
deffile_read(fname):
txt = open(fname)
print([Link]())
file_read('[Link]')

Output

Page 28

[Link]
B. Write a Python program to append text to a file and display the text.

Code:
def main():
f=open("[Link]","a+")
[Link]("Welcome to Workshop on Python")
[Link]()
if __name__=="__main__":
main()

Page 29

[Link]
Output:

C. Write a Python program to read last n lines of a file.

Code:
'''
Write a Python program to read last n lines of a file.
'''
import sys
import os
deffile_read_from_tail(fname,lines):
bufsize = 8192
fsize = [Link](fname).st_size
iter = 0
with open(fname) as f:
if bufsize>fsize:
bufsize = fsize-1
data = []
while True:
iter +=1
[Link](fsize-bufsize*iter)
[Link]([Link]())
if len(data) >= lines or [Link]() == 0:

Page 30

[Link]
print(''.join(data[-lines:]))
break
file_read_from_tail('[Link]',2)

Output:

Page 31

[Link]

You might also like