Python Programs
Python Programs
(Take input from user and use For loop and normal Print
function.)
2.Write a Python program to print first N natural
numbers.
(Take limit (N)from user, Use for loop and print the output
in one line)
3.Write a Python program to print the sum of first N
natural numbers.
6.Write a Python program to create list of first 5
rainbow colours and add rest of the colours using
append method.
Print the list before updating and after updating.
7.Write a Python program to create a list of 5
different fruits and remove one fruit from the list
using pop method and another fruit using remove
method. Print the list before deleting and after
deleting.
Extra
1.Questions
Find the factorial of a given number using for loop
(Example 5! = 1*2*3*4*5 = 120)
2. Display an multiplication table of a given number
using for loop.
(Example 8 Table
8 x 1 =8
8 x 2= 16
….)
Question 1
#To print the entered name ‘n’ number of
times
name = input("Enter the name")
n = int(input("Enter the number of times"))
for i in range(1,n+1):
print(name,end=" ") Output
Enter the name Joy
Enter the number of times 7
Joy Joy Joy Joy Joy Joy Joy
Question 2
#program to print first N natural numbers.
limit = int(input ("Enter the limit: "))
print("The first",limit,"natural numbers
are:")
Output
for i in range(1,limit+1):
print(i,end=" ") Enter the limit: 10
1 2 3 4 5 6 7 8 9 10
Question 3
#program to print the sum of first N natural
numbers.
limit = int(input ("Enter the limit: "))
sum=0
for i in range(1,limit+1):
sum+=i
print("The sum of first Enter
N natural
the limit: 5 numbers Output
is :",sum) The sum of first N natural numbers is : 15
Output
Question 4 Enter the limit: 5
#program to print first 10 odd numbers.
***** List of odd numbers are *****
limit=int(input("Enter the limit: ")) 1
print("***** List of odd numbers are 3
*****") 5
for i in range(1,limit+1,1): 7
odd=2*i-1 9
print(odd)
Output
Question 5 Enter the limit: 7
#program to print first 10 even
***** List of even numbers are *****
numbers. 2
limit=int(input("Enter the limit: ")) 4
print("***** List of even numbers are 6
*****") 8
for i in range(1,limit+1,1): 10
even=2*i-1 12
print(even) 14
Output
Question 6 *** List items before appending ***
Violet
#program to create list of first 5 rainbow Indigo
colours Blue
Green
color Yellow
=["Violet","Indigo","Blue","Green","Yell
*** List items after appending ***
ow"] Violet
print("***** List items before appending Indigo
Blue
*****") Green
Yellow
print(*color, sep="\n") Orange
color.append("Orange") Red
color.append("Red")
print("\n***** List items after appending
*****")
print(*color, sep="\n")
# Program to Use Sep and end Parameters
a="Happy"
b="Holidays"
print(a,b)
print(a,b,sep="-")
print(a,b,end="-") Output
Happy Holidays
Happy-Holidays
Happy Holidays-
Data Types
Data Structures or Collection in
Data Type
List
Python
Usage
Ordered List, Changeable collection and Allows Duplicate members
Eg: lis =[10,20,30,10,15]
Tuple Ordered List, Unchangeable collection and Allows Duplicate members
Eg:tup=('a','e',1,5,'a',4)
Set Unordered and Unindexed List and does not allow Duplicate members.
Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
Dictionary Unordered , Changeable and indexed collection and does not allow
Duplicate members
Eg: dic = {1: "one", 2: "three"}
Tuple
• Tuples are used to store multiple items in a single variable.
• Tuples allows duplicate Values
• A tuple is an immutable object, which means it cannot be changed,
and we use it to represent fixed collections of items.
• Like list both positive indexing and negative Indexing is possible in
Tuple
Method Description
len() This method returns number of elements in a tuple.
min() This method returns largest element of a tuple.(All should be of Same type)
max() This method returns smallest element of a tuple.(All should be of Same type)
index() Searches the tuple for a specified value and returns the position of where it was found
count() This function is used to count and return number of times a value exists in a tuple. If the
given value is not in the tuple, it returns zero.
Tuple
# program to learn Tuples
b=(25,35,45,35)
print(b)
Print(b[-2]) #prints the value in the second last position
print("No of Items present in the tuple are",len(b))
print("Item occurred frequently",b.count(35))
print("Min value",min(b))
print("Max value",max(b)) Output
print("Position of 35“ is,b.index(35)) (25, 35, 45, 35)
45
No of Items present in the tuple are 4
Item occurred frequently 2
Min value 25
Max value 45
Position of 35 is 1
Set
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable(but you can
remove items and add new items), and unindexed.
Method Description
add() This method is used to add an item to a set.
remove() This method is used to to remove the specified element from a set.
len() This method returns number of elements present in a Set
union() This method is used to perform the set union operation
intersection() This method is used to perform the set intersection operation
Set
# create a set of programming languages
pl1= {'cobol','C#','Pascal'}
pl1.add('C')
pl2 ={'LISP','Python','C#','C++'}
print('Programming languages in set1 are:', pl1, sep="\t")
print('Programming languages in set2 are:', pl2, sep="\t")
print("Union")
u=pl1|pl2 #Using Vertical bar operator (|) we can get union of sets
print(*u) Output
u.remove('Pascal') Programming languages in set1 are: {'C', 'Pascal', 'C#', 'cobol'}
print(*u) Programming languages in set2 are: {'C++', 'C#', 'LISP', 'Python'}
Union
print("Intersection") cobol C Pascal LISP C++ C# Python
i=pl1&pl2 cobol C LISP C++ C# Python
Intersection
print(*i) C#
Python -
The dictionary is an unordered collection that
Dictionary
contains key:value pairs separated by commas inside curly brackets.
Dictionaries are optimized to retrieve values when the key is known.
The following declares a dictionary object.
Example: Dictionary
capitals = {"USA":"Washington D.C.", "France":"Paris",
"India":"New Delhi"}
The left side of : is a key, and the right side is a value. The key
should be unique and an immutable object.
numNames={1:"One", 2: "Two", 3:"Three"} #int key, string
value
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} #string key, int
value
Python -
Dictionary
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Dictionary
dic = {1: "one", 2: "three"}
print("Dictionary before updation") Output
print(dic) Dictionary before updation
d1 = {2: "two"} {1: 'one', 2: 'three'}
dic.update(d1) # updates the value of key 2 Dictionary after updation
print("Dictionary after updation") {1: 'one', 2: 'two'}
print(dic) Dictionary after adding new key
{1: 'one', 2: 'two', 3: 'three'}
d1 = {3: "three"} three
dic.update(d1) # adds element with key 3 Items of Dictionary
print("Dictionary after adding new key") dict_items([(1, 'one'), (2, 'two'), (3, 'three')])
print(dic) Keys of Dictionary
print(dic.get(3)) #Returns the value of the specified key dict_keys([1, 2, 3])
print("Items of Dictionary") Dictionary after pop
{1: 'one', 2: 'two'}
print(dic.items())
print("Keys of Dictionary")
print(dic.keys())
dic.pop(3)
print("Dictionary after pop")
print(dic)
LAB-2
1. Write a Python program to add 5 programming languages such
as C, C, C#, C++, Python in a set and display the elements of the
set.
2.Write a Python program to add 3 domains of Artificial
Intelligence in a Tuple and display each element from the Tuple
using index operator.
3.Write a Python program to enter the parameters of a car in a
dictionary and display the brand value of the dictionary. The
parameters are the following:
Brand: Ford
Model: Mustang
Year: 2015
LAB-2
5. Write a menu driven Python program for the calculator. Accept
the inputs from the user. The choices are the following:
Choice = 1 for Addition
Choice = 2 for Subtraction
Choice = 3 for Multiplication
Choice = 4 for Division
Choice = 5 for Invalid Choice
6. Write a Python program to input the lengths of the three sides of
a triangle and display whether a triangle will be scalene, isosceles
or equilateral triangle.
7. Write a Python program to input a string and display the count
of vowels and consonants in the given string.
LAB-2
8.Write a Python program to check and display a person is eligible
to cast a vote (Minimum voting age: 18 years)
9.Write a Python program to find the factorial of a number
provided by the user.
10. Write a Python program to find the sum of n odd numbers.
11.Write a Python program to find the sum of n even numbers.
Question 1
# create a set of 5 programming languages
pl= {'cobol'}
Output
Using Set to print Programming languages are:
pl.add('C') LISP
pl.add('LISP') Python
pl.add('Python') C
cobol
pl.add('C#') C++
pl.add('C++’) C#
print(‘Using Set to print Programming languages are:', *pl, sep="\n")
Question 2
# To add 3 domains of Artificial Intelligence in a Tuple and
display each element from the Tuple using index operator
dom=("Data","Computer Vision","NLP")
n = len(dom)
for i in range(0,n):
print(dom[i],sep="\n")
Output
Data
Computer Vision
NLP
Question 3
# Program to enter the parameters of a car in a dictionary and display the
brand value of the dictionary
car={"Brand":"Ford","Model": "Mustang","Year": 2015}
print("The Brand of the entered car is")
print(car["Brand"])
Output
The Brand of the entered car is
Ford
Question 4
# Program to find the largest among 3 numbers
a = int(input('Enter first number : '))
b = int(input('Enter second number : '))
c = int(input('Enter third number : '))
if a > b and a > c:
largest = a
elif b > a and b > c: Output
largest = b
Enter first number : 65
else:
Enter second number : 45
largest = c Enter third number : 92
print(largest, "is the largest of",a,b,c)
92 is the largest of 65 45 92
Question 5
# Program for menu driven calculator
num1 = int(input('Enter first number : '))
num2 = int(input('Enter second number : '))
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
Output
choice = int(input('Enter your choice: '))
if choice == 1: Enter first number : 45
print(num1, "+", num2, "=", num1+num2) Enter second number : 36
elif choice == 2: Select operation.
print(num1, "-", num2, "=", num1-num2)
1.Add
elif choice == 3:
print(num1, "*", num2, "=", num1*num2) 2.Subtract
elif choice == 4: 3.Multiply
print(num1, "/", num2, "=", num1/num2) 4.Divide
else: Enter your choice: 2
print("Please enter the correct choice") 45 - 36 = 9
Question 6
# Program to check the type of triangle
x = int(input("Enter the first side:"))
y = int(input("Enter the second side:"))
z = int(input("Enter the third side:"))
Output
if x == y == z: Enter the first side: 5
print("Its an Equilateral triangle")Enter the second side:6
Enter the third side:7
elif x==y or y==z or z==x: Its an Scalene triangle
Output
Enter your age 35
You are eligible to Vote.. please cast your vote
Question 9
# Program to check the type of triangle
num = int(input("Enter a number: "))
f=1
for i in range(1, num + 1):
f=f*i
print("factorial of ", num, " is ", f)
Output
Enter a number: 5
factorial of 5 is 120
Output
Question Enter the limit: 5
10
#program to find the sum of odd
numbers.
***** List of odd numbers are *****
1
limit=int(input("Enter the limit: ")) 3
sum=0 5
print("***** List of odd numbers are 7
*****") 9
for i in range(1,limit+1,1): The Sum of 5 odd numbers is: 25
odd=2*i-1
print(odd)
sum=sum+odd
print("The Sum of",limit,"odd numbers
is:",sum)
Output
Question Enter the limit: 7
11
#program to find the sum of even
numbers.
***** List of even numbers are *****
2
limit=int(input("Enter the limit: ")) 4
sum=0 6
print("***** List of even numbers are 8
*****") 10
for i in range(1,limit+1,1): 12
even=2*i-1 14