0% found this document useful (0 votes)
12 views

Python

Uploaded by

rajatkumars965.2
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python

Uploaded by

rajatkumars965.2
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

#1 How to input and display a user's name and age?

name=input("Enter your name=")


age=input("Enter your age=")
print("Hello",name,"and your age is",age,"years."
Output:
Enter your name=John
Enter your age=2
Hello John and your age is 25 years.
#2 How to display the English word for a digit (0–9)?
a=int(input("Enter any number between 0-9="))
if a==0:
print("Zero")
elif a==1:
print("One")
elif a==2:
print("Two")
elif a==3:
print("Three")
elif a==4:
print("Four")
elif a==5:
print("Five")
elif a==6:
print("Six")
elif a==7:
print("Seven")
elif a==8:
print("Eight")
elif a==9:
print("Nine")
else:
print("Invalid entry")
Output:
Enter any number between 0-9=
Five
#3 How to display numbers using loops (all, even, or specific ranges)?
for i in range(1,11):
print(i)
for i in range(2,10,2):
print(i)
print("\n\n\n")
for i in range(1,21):
if i%2==0:
print(i)
Output:
1
2
3
...
10
2
4
6
8
10
2
4
6
...
20
#4 How to calculate sums and averages of even and odd numbers from user input?
sE=0
sO=0
cE=0
cO=0
n=int(input("Enter how any numbers you want to enter="))
for i in range(1,n+1):
a=int(input("Enter any value="))
if a%2==0:
sE+=a
cE+=1
else:
sO+=a
cO+=1
avgE=sE/cE
avgO=sO/cO
print("Total numbers entered",n)
print("Number of even number entered=",cE)
print("Number of odd number entered=",cO)
print("Sum of even number entered=",sE)
print("Sum of odd number entered=",sO)
print("Average of even number entered=",avgE)
print("Average of odd number entered=",avgO)
Output:
Enter how many numbers you want to enter=5
Enter any value=10
Enter any value=15
Enter any value=20
Enter any value=25
Enter any value=3
Total numbers entered 5
Number of even numbers entered= 3
Number of odd numbers entered= 2
Sum of even numbers entered= 60
Sum of odd numbers entered= 40
Average of even numbers entered= 20.0
Average of odd numbers entered= 20.0
#5 How to sort three numbers in descending order?
a=int(input("Enter 1st number="))
b=int(input("Enter 2nd number="))
c=int(input("Enter 3rd number="))
if a>b and a>c:
if b>c:
print(a,b,c)
else:
print(a,c,b)
elif b>a and b>c:
if a>c:
print(b,a,c)
else:
print(b,c,a)
else:
if a>b:
print(c,a,b)
else:
print(c,b,a)
Output:
Enter 1st number=25
Enter 2nd number=10
Enter 3rd number=35
35 25 10
#6 How to calculate the sum of digits of a number?
s=0
n=int(input("Enter any number="))
while n!=0:
a=n%10
s+=a
n=n//10
print("Sum of digits",s)
Output:
Enter any number=12345
Sum of digits 15
#7 How to separate even and odd numbers and find maximum/minimum?
e=o=0
l1=[]
e=[]
o=[]
x=-1
ma=0
mi=1001
while x!=0:
x=int(input("Enter any number="))
l1.append(x)
if x%2==0:
e.append(x)
e+=1
else:
o.append(x)
o+=1
if x>ma:
ma=x
if x<mi:
mi=x
Output:
Enter any number=10
Enter any number=15
Enter any number=20
Enter any number=0
Even numbers: [10, 20, 0]
Odd numbers: [15]
Maximum number: 20
Minimum number: 0
#8 How to store and display student marks using a dictionary?
n=int(input("Enter number of students="))
stu=dict()
l1=[]
for i in range(1,n+1):
r=int(input("Enter roll number="))
m1=int(input("Accountancy="))
m2=int(input("Business Studies="))
m3=int(input("Economics="))
l1.append(m1)
l1.append(m2)
l1.append(m3)
stu[r]=l1
l1=[]
for j in stu:
print("Roll number=",j,"Accountancy=",stu[j][0],'Business Studies',stu[j][1],"Economics",stu[j][2])
Output:
Enter number of students=2
Enter roll number=101
Accountancy=85
Business Studies=90
Economics=88
Enter roll number=102
Accountancy=78
Business Studies=80
Economics=7
Roll number= 101 Accountancy= 85 Business Studies 90 Economics 88
Roll number= 102 Accountancy= 78 Business Studies 80 Economics 76
#9 How to display all prime numbers within a range?
l=int(input("Enter lower range="))
u=int(input("Enter uppper range="))
for i in range(l,u+1):
if i>1:
for j in range(2,i):
if (i%j)==0:
break
else:
print(i)
Output:
Enter lower range=10
Enter upper range=20
11
13
17
19
#10 How to perform basic arithmetic operations based on user choice?
a=int(input("1st number="))
b=int(input("2ndnumber="))
op=int(input('''
**************************
Arithmetic Operators
1. Addition
2.Subtraction
3.Multiplication
4.Division
5.Floor Division
**************************
'''))
if op==1:
res=a+b
print(a,"+",b,"=",res)
elif op==2:
res=a-b
print(a,"-",b,"=",res)
elif op==3:
res=a*b
print(a,"X",b,'=',res)
elif op==4:
res=a/b
print(a,'/',b,'=',res)
elif op==5:
res=a//b
print(a,'//',b,'=',res)
else:
print("Invalid choice")
Output:
1st number=25
2nd number=5

**************************
Arithmetic Operators
1. Addition
2.Subtraction
3.Multiplication
4.Division
5.Floor Division
**************************

4
25 / 5 = 5.0
#11 How to calculate division, count of students in each division, and identify the highest scorer based on
marks in five subjects?
c1=c2=c3=c4=0
for i in range(1,6):
n=input("Enter your name=")
eng=int(input("English="))
acc=int(input("Accountancy="))
bst=int(input("Business Studies="))
eco=int(input("Economics="))
ip=int(input("IP="))
t=eng+acc+bst+eco+ip
p=t/500*100
if p>=65 and eng>=33 and acc>=33 and bst>=33 and eco>=33 and ip>=33:
d="First"
c1+=1
elif p>=45 and p<65 and eng>=33 and acc>=33 and bst>=33 and eco>=33 and ip>=33:
d="Second"
c2+=1
elif p>=33 and p<45 and eng>=33 and acc>=33 and bst>=33 and eco>=33 and ip>=33:
d="Third"
c3+=1
else:
d="Fail"
c4+=1
print("Hello",n,"you have scored",t,"marks and",p,"percentage")
div="First,Second,Third"
if d in div:
print("Congratulations! You have secured",d,"division")
else:
print("Better luck next time!")
if i==1:
n1=n
t1=t
elif i==2:
n2=n
t2=t
elif i==3:
n3=n
t3=t
elif i==4:
n4=n
t4=t
else:
n5=n
t5=t
if t1>t2 and t1>t3 and t1>t4 and t1>t5:
h=n1
elif t2>t1 and t2>t3 and t2>t4 and t2>t5:
h=n2
elif t3>t1 and t3>t2 and t3>t4 and t3>t5:
h=n3
elif t4>t1 and t4>t2 and t4>t3 and t4>t5:
h=n4
else:
h=n5
print(c1,"students have secured 1st division")
print(c2,"students have secured 2nd division")
print(c3,"students have secured 3rd division")
print(c4,"students have failed")
print("The highest scorer is",h)
Output:
Enter your name=John
English=80
Accountancy=75
Business Studies=70
Economics=85
IP=90
Enter your name=Emily
English=60
Accountancy=55
Business Studies=50
Economics=65
IP=70

Enter your name=Mike


English=40
Accountancy=45
Business Studies=40
Economics=50
IP=60
Enter your name=Alice
English=30
Accountancy=25
Business Studies=35
Economics=40
IP=45
Enter your name=Tom
English=90
Accountancy=95
Business Studies=85
Economics=88
IP=92
Hello John you have scored 400 marks and 80.0 percentage
Congratulations! You have secured First division
Hello Emily you have scored 300 marks and 60.0 percentage
Congratulations! You have secured Second division
Hello Mike you have scored 235 marks and 47.0 percentage
Congratulations! You have secured Third division
Hello Alice you have scored 175 marks and 35.0 percentage
Better luck next time!

Hello Tom you have scored 450 marks and 90.0 percentage
Congratulations! You have secured First division
2 students have secured 1st division
1 students have secured 2nd division
1 students have secured 3rd division
1 students have failed
The highest scorer is Tom
#12 How to separate even and odd numbers, find the maximum, minimum, and count of entered numbers
in a list?
l1 = []
even = []
odd = []
x = -1
ma = float('-inf')
mi = float('inf')
while x != 0:
x = int(input("Enter any number="))
if x == 0:
break
l1.append(x)
if x % 2 == 0:
even.append(x)
else:
odd.append(x)
if x > ma:
ma = x
if x < mi:
mi = x
print("Even numbers:", even)
print("Odd numbers:", odd)
print("Maximum number:", ma)
print("Minimum number:", mi)
Output:
Enter any number=12
Enter any number=5
Enter any number=8
Enter any number=20
Enter any number=0
Even numbers: [12, 8, 20, 0]
Odd numbers: [5]
Maximum number: 20
Minimum number: 0
#13 How to calculate the take-home salary by including allowances and deductions based on a given
basic salary?
n=input("Enter your name=")
bs=int(input("Enter basic salary="))
da=70/100*bs
ta=10/100*bs
hra=15/100*bs
pf=7/100*bs
tax=12/100*bs
ths=(bs+da+ta+hra)-(pf+tax)
print("Hello",n,"your take home salary is",ths)
Output:
Enter your name=John
Enter basic salary=50000
Hello John your take-home salary is 81950.0
#14 How to calculate the factorial of a given number using a loop?
n=int(input('Enter a value= '))
s=1
for i in range(1,n+1):
s*=i
print("Factorial of number=",s)
Output:
Enter a value= 5
Factorial of number= 120
#15 How to calculate the total amount for a product based on its cost and the number of units sold?
n=input("Enter name of product=")
c=int(input("Enter cost of product="))
q=int(input("Enter units sold="))
a=c*q
print("Your product name is",n,'and your total amount is',a)
Output:
Enter name of product= Laptop
Enter cost of product= 45000
Enter units sold= 50
Your product name is Laptop and your total amount is 2250000
#16 How can we create and print a simple Pandas Series?
import pandas as pd
s1 = pd.Series([10, 20, 30])
print(s1)
Output:
0 10
1 20
2 30
dtype: int64
#17 How can we create and print a Pandas Series from a NumPy array?
import numpy as np
a1 = np.array([1, 2, 3, 4])
s2 = pd.Series(a1)
print(s2)
Output:
0 1
1 2
2 3
3 4
dtype: int64
#18 How can we create a Pandas Series from a dictionary with labeled indexes, print it, and perform some
slicing?
d1 = {'India': 'New Delhi', 'UK': 'London', 'Japan': 'Tokyo'}
s3 = pd.Series(d1)
s3.index.name = 'Countries'
print(s3)
print(s3['India':'UK'])
print(s3[::-1])
Output:
Countries
India New Delhi
UK London
Japan Tokyo
dtype: object
Countries
India New Delhi
UK London
dtype: object
Countries
Japan Tokyo
UK London
India New Delhi
dtype: object
#19 How can we create a Pandas Series with custom index labels, modify its values using slicing, and
display the results?
salph = pd.Series(np.arange(11, 16, 1), index=['a', 'b', 'c', 'd', 'e'])
print(salph)
salph[1:3] = 50
print(salph)
salph['d':'e'] = 500
print(salph)
Output:
a 11
b 12
c 13
d 14
e 15
dtype: int64

a 11
b 50
c 50
d 14
e 15
dtype: int64

a 11
b 50
c 50
d 500
e 500
dtype: int64
#20 How can we create a Pandas Series from a dictionary, assign a name to the Series, and perform
various operations like checking size, empty status, and slicing?
d1 = {'India': 'New Delhi', 'UK': 'London', 'Japan': 'Tokyo', 'USA': 'Washington DC', 'France': 'Paris'}
s1 = pd.Series(d1)
s1.name = 'Capitals'
print(s1)
print(s1.values)
print(s1.size)
print(s1.empty)
print(s1.head(2))
print(s1.tail(3))
print(s1.count())

Output:
India New Delhi
UK London
Japan Tokyo
USA Washington DC
France Paris
Name: Capitals, dtype: object

['New Delhi' 'London' 'Tokyo' 'Washington DC' 'Paris']


5
False
India New Delhi
UK London
Name: Capitals, dtype: object

Japan Tokyo
USA Washington DC
France Paris
Name: Capitals, dtype: object

5
#21 How can we plot a simple line graph for temperature over three dates?
import pandas as pd
import matplotlib.pyplot as plt
date = ['25/11', '26/11', '27/11']
temp = [8.5, 10.5, 6.8]
plt.plot(date, temp)
plt.show()

#22 How can we enhance the previous temperature graph by adding labels, gridlines, and customized y-
axis ticks?
date = ['25/11', '26/11', '27/11']
temp = [8.5, 10.5, 6.8]
plt.plot(date, temp)
plt.xlabel("Date")
plt.ylabel("Temperature")
plt.grid(True)
plt.yticks(temp)
plt.show()
#23 How can we display the relationship between average height and average weight using a line graph
with markers and a custom style?
import matplotlib.pyplot as plt
import pandas as pd
height = [121.9, 124.5, 129.6, 134.6, 147.3, 152.6, 157.5, 162.6]
weight = [19.7, 21.3, 23.5, 25.9, 28.5, 32.1, 35.7, 39.6]
df = pd.DataFrame({"height": height, "weight": weight})
plt.xlabel("Weight in kg")
plt.ylabel("Height in cm")
plt.title("Average weight with respect to average height")
df.plot(marker='*', markersize=10, color='green', linewidth=2, linestyle='dashdot')
plt.show()
#24 How can we create a histogram to display the distribution of height and weight data for a group of
individuals?
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Name': ["Tajar", 'Sidhasnhu', 'Aaaadhyha', 'Baisnavi', 'Sivans', 'Chutki'],
'Height': [69, 67, 63, 63, 70, 64],
'Weight': [75, 60, 47, 52, 70, 12]
}
df = pd.DataFrame(data)
df.plot(kind='hist')
plt.show()
#25 How can we create a histogram to visualize a normal distribution of random data points?
import numpy as np
y = np.random.randn(1000)
plt.hist(y, 25, edgecolor='white')
plt.show()
#26 How can we create two vertically stacked subplots showing two related datasets?
t = np.arange(0, 20, 1)
s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
s2 = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
plt.subplot(2, 1, 1)
plt.plot(t, s)
plt.ylabel('Value')
plt.title('First Chart')
plt.grid(True)
plt.subplot(2, 1, 2)
plt.plot(t, s2)
plt.xlabel('Item(s)')
plt.ylabel('Value')
plt.title('\n\n Second Chart')
plt.grid(True)
plt.show()
#27 How can we create a line graph to represent data from a CSV file containing students and their
marks?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('D:\\12 CD Projects\\racky.csv')
df.plot(kind='line')
plt.title('Marks of Students')
plt.xlabel("Students")
plt.ylabel('Marks')
plt.show()

#28 How can we create a bar plot to visualize sales data for different products?
import pandas as pd
import matplotlib.pyplot as plt

# Creating sales data for products


data = {'Product': ['A', 'B', 'C', 'D', 'E'], 'Sales': [150, 200, 120, 180, 250]}
df = pd.DataFrame(data)

# Plotting bar plot


plt.bar(df['Product'], df['Sales'], color='skyblue')
plt.xlabel('Products')
plt.ylabel('Sales (in units)')
plt.title('Sales Data for Products')
plt.show()

#29 How can we visualize the market share distribution of different companies using a pie chart?
import pandas as pd
import matplotlib.pyplot as plt

companies = ['Company A', 'Company B', 'Company C', 'Company D']


market_share = [35, 25, 20, 20]
plt.pie(market_share, labels=companies, autopct='%1.1f%%', startangle=90, colors=['lightgreen',
'lightcoral', 'lightskyblue', 'lightpink'])
plt.title('Market Share Distribution')
plt.axis('equal') # Equal aspect ratio ensures that pie chart is drawn as a circle.
plt.show()
#30 How can we visualize the relationship between height and weight of individuals using a histogram
plot?
import pandas as pd
import matplotlib.pyplot as plt

# Creating height and weight data


data = {'Height': [160, 165, 170, 175, 180, 185, 190], 'Weight': [55, 60, 65, 70, 75, 80, 85]}
df = pd.DataFrame(data)
# Plotting histogram for Height
plt.hist(df['Height'], bins=5, color='blue', alpha=0.7, edgecolor='black')
plt.xlabel('Height (in cm)')
plt.ylabel('Frequency')
plt.title('Histogram of Height')
plt.show()

# Plotting histogram for Weight


plt.hist(df['Weight'], bins=5, color='green', alpha=0.7, edgecolor='black')
plt.xlabel('Weight (in kg)')
plt.ylabel('Frequency')
plt.title('Histogram of Weight')
plt.show()

You might also like