0% found this document useful (0 votes)
10 views16 pages

Python Programspdf

The document contains a series of Python programming exercises covering various topics such as printing messages, calculating factorials, checking for even/odd numbers, determining prime numbers, and more. It also includes functions for recursion, string manipulation, and data structures like lists and dictionaries. Each program is presented with code snippets and explanations for clarity.

Uploaded by

dhirajsharma381
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)
10 views16 pages

Python Programspdf

The document contains a series of Python programming exercises covering various topics such as printing messages, calculating factorials, checking for even/odd numbers, determining prime numbers, and more. It also includes functions for recursion, string manipulation, and data structures like lists and dictionaries. Each program is presented with code snippets and explanations for clarity.

Uploaded by

dhirajsharma381
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 Programs

1.Write a program to print hello world


print(“hello world”)

2.Write a program to print factorial of a number


n=int(input (“enter a number”))
fact=1
if n<0:
Print(“factorial does not exist –ve number”)
elif n==0:
Print (“factorial of 0 is 1”)
else:
For i in range (1,n+1):
Fact= fact*i
print(“factorial of “,n”=”fact)

3.Write a program to check a number whether it is even or odd.


num=int(input("Enter
the number: ")) if
num%2==0:
print(num, " is
even number")else:
print(num, " is odd number")

4.Write a program in python to check a number whether it is prime or not.


num=int(input("Enter
the number: ")) for i in
range(2,num):
if num%i==0:
print(num, "is not
prime number")
break;
else:
print(num,"is prime number")
5. Write a program to check a year whether it is leap year or not.
year=int(input("Enter the year: "))
if year%100==0 and year%400==0:
print("It is a leap year")
elif year%4==0:
print("It is a leap year")
else:
print("It is not leap year")

6. Write a program to check a number whether it is palindrome or not.


num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")

7. A number is Armstrong number or not.


num=input("Enter a number : ")
length=len(num)
n=int(num)
num=n
sum=0
while n>0:
rem=n%10
sum=sum+rem**length
n=n//10
if num==sum:
print(num, "is armstrong number")
else:
print(num, "is not armstrong number")

8. To check whether the number is perfect number or not


num=int(input("Enter a number : "))
sum=0
for i in range(1,num):
if(num%i==0):
sum=sum+i
if num==sum:
print(num, "is perfect number")
else:
print(num, "is not perfect number")

9. Write a program to print Fibonacci series.


n=int(input("How many numbers : "))
first=0
second=1
i=3
print(first, second, end=" ")
while i<=n:
third=first+second
print(third, end=" ")
first=second
second=third
i=i+1

10. To print a pattern using nested loops


for i in range(1,5): 1
for j in range(1,i+1): 1 2
print(j," ", end=" ") 1 2 3
print('\n') 1 2 3 4

11. WAP To print a table


n=int(input(“enter a number”))
for n in range (n,n*10+1,n):
print (i)

12. Function returning one value

def my_function(x):
return 5 * x

13. Function returning multiple values:


def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple
print(S)

OUTPUT:
(7, 7, 11)

14. Storing the returned values separately:


def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)

OUTPUT:
7 7 11

15. WAP Program


Definition: A function calls itself, is called recursion.
Python program to find the factorial of a number using recursion:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
num=int(input("enter the number: "))
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 ", factorial(num))

OUTPUT:
enter the number: 5
The factorial of 5 is 120

16. Python program to print the Fibonacci series using recursion:


Program:
def fibonacci(n):
if n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))

num=int(input("How many terms you want to display: "))


for i in range(num):
print(fibonacci(i)," ", end=" ")

OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13

17. Program: Write a program to display ASCII code of a


character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")

print("Do you want to continue? Y/N")


option=input()
if option=='y' or option=='Y':
var=True
else:
var=False

18. Write a program that takes a string with multiple words and then capitalize
the firstletter of each word and forms a new string out of it.

s1=input("Enter a string : ")


length=len(s1)
a=0
end=length
s2="" #empty string while a<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!=''):
s2=s2+s1[a]
s2=s2+s1[a+1].upper()
a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ", s1)
print("Capitalized wrds string: ", s2)
19. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=str.lower()
print(s1)
elif choice==2:
s1=str.upper()
print(s1)
else:
print("Invalid choice entered")

Program-21 Write a program to find the minimum and maximum number in a list.

L=eval(input("Enter the elements: "))


n=len(L)
min=L[0]
max=L[0]
for i in range(n):
if min>L[i]:
min=L[i]
if max<L[i]:
max=L[i]

print("The minimum number in the list is : ", min)


print("The maximum number in the list is : ", max)
Program-22. Find the second largest number in a
list. L=eval(input("Enter the elements: "))
n=len(L)
max=second=L[0]
for i in range(n):
if max<L[i]>second:
max=L[i]
seond=max

print("The second largest number in the list is : ", second)

Program-23: Program to search an element in a list. (Linear Search).

L=eval(input("Enter the elements: "))


n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")

Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
24. Counting the frequencies in a list using a loop

def CountFrequency(my_list):

# Creating an empty dictionary

freq = {}

for item in my_list:

if (item in freq):

freq[item] += 1

else:

freq[item] = 1

for key, value in freq.items():

print("% d : % d" % (key, value))

# Driver function

if __name__ == "__main__":

my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2,
2, 2]

CountFrequency(my_list)
Output:
1 : 5
2 : 4
3 : 3
4 : 3
5 : 2
Time Complexity: O(N), where N is the length of the list.

25. WAP to sort 3 numbers and divisibility of a number


x = int(input("Input first number: "))
y = int(input("Input second number: "))
z = int(input("Input third number: "))

a1 = min(x, y, z)
a3 = max(x, y, z)
a2 = (x + y + z) - a1 - a3

print("Numbers in sorted order: ", a1, a2, a3)

26. count the number of times a character appears in a given string


using a dictionary
string = 'Python Programming'
dictionary = {}
for char in string:
if( char in dictionary.keys()):
dictionary[char] += 1
else:
dictionary[char]=1
for char in dictionary:
print(char,' -> ',dictionary[char])

Output:

P -> 2
y -> 1
t -> 1
h -> 1
o -> 2
n -> 2
-> 1
r -> 2
g -> 2
a -> 1
m -> 2
i -> 1

Q27. Write a program to enter names of employees and their salaries as


input and store them in a dictionary.
dic = { }
while True :
name = input("Enter employee name :-")
sl = int(input("Enter employee salary :-"))
dic[ name] = sl
user = input("Do you want to quit then enter yes :-")
if user == "yes" :
break
print(dic)
Python Scope
A variable is only available from inside the region it
is created. This is called scope.

Local Scope
A variable created inside a function belongs to the local scope of
that function, and can only be used inside that function.

A variable created inside a function is available inside that function:

def myfunc():
x = 300
print(x)

myfunc()

Function Inside Function


As explained in the example above, the variable x is not available outside the
function, but it is available for any function inside the function:

Example
The local variable can be accessed from a function within the function:

def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.

Global variables are available from within any scope, global and local.

Example
A variable created outside of a function is global and can be used by anyone:

x = 300

def myfunc():
print(x)

myfunc()

print(x)

Q-28 WAP in python generate a random floating


between specified range
import random
L= int (input (“enter the lower value:”))
U = int (input (“enter the upper value:”))
n= random()*(U-L)+L
print(int(n))
print(n)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy