0% found this document useful (0 votes)
4 views28 pages

User Input and Data Processing in Python

Uploaded by

rajatkumars965.2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views28 pages

User Input and Data Processing in Python

Uploaded by

rajatkumars965.2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#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="))
[Link](x)
if x%2==0:
[Link](x)
e+=1
else:
[Link](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="))
[Link](m1)
[Link](m2)
[Link](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
[Link]
[Link]
[Link]
[Link] 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
[Link]
[Link]
[Link]
[Link] 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
[Link](x)
if x % 2 == 0:
[Link](x)
else:
[Link](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 = [Link]([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 = [Link]([1, 2, 3, 4])
s2 = [Link](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 = [Link](d1)
[Link] = '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 = [Link]([Link](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 = [Link](d1)
[Link] = 'Capitals'
print(s1)
print([Link])
print([Link])
print([Link])
print([Link](2))
print([Link](3))
print([Link]())

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 [Link] as plt
date = ['25/11', '26/11', '27/11']
temp = [8.5, 10.5, 6.8]
[Link](date, temp)
[Link]()

#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]
[Link](date, temp)
[Link]("Date")
[Link]("Temperature")
[Link](True)
[Link](temp)
[Link]()
#23 How can we display the relationship between average height and average weight using a line graph
with markers and a custom style?
import [Link] 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 = [Link]({"height": height, "weight": weight})
[Link]("Weight in kg")
[Link]("Height in cm")
[Link]("Average weight with respect to average height")
[Link](marker='*', markersize=10, color='green', linewidth=2, linestyle='dashdot')
[Link]()
#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 [Link] 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 = [Link](data)
[Link](kind='hist')
[Link]()
#25 How can we create a histogram to visualize a normal distribution of random data points?
import numpy as np
y = [Link](1000)
[Link](y, 25, edgecolor='white')
[Link]()
#26 How can we create two vertically stacked subplots showing two related datasets?
t = [Link](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]
[Link](2, 1, 1)
[Link](t, s)
[Link]('Value')
[Link]('First Chart')
[Link](True)
[Link](2, 1, 2)
[Link](t, s2)
[Link]('Item(s)')
[Link]('Value')
[Link]('\n\n Second Chart')
[Link](True)
[Link]()
#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 [Link] as plt
df = pd.read_csv('D:\\12 CD Projects\\[Link]')
[Link](kind='line')
[Link]('Marks of Students')
[Link]("Students")
[Link]('Marks')
[Link]()

#28 How can we create a bar plot to visualize sales data for different products?
import pandas as pd
import [Link] as plt

# Creating sales data for products


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

# Plotting bar plot


[Link](df['Product'], df['Sales'], color='skyblue')
[Link]('Products')
[Link]('Sales (in units)')
[Link]('Sales Data for Products')
[Link]()

#29 How can we visualize the market share distribution of different companies using a pie chart?
import pandas as pd
import [Link] as plt

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


market_share = [35, 25, 20, 20]
[Link](market_share, labels=companies, autopct='%1.1f%%', startangle=90, colors=['lightgreen',
'lightcoral', 'lightskyblue', 'lightpink'])
[Link]('Market Share Distribution')
[Link]('equal') # Equal aspect ratio ensures that pie chart is drawn as a circle.
[Link]()
#30 How can we visualize the relationship between height and weight of individuals using a histogram
plot?
import pandas as pd
import [Link] 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 = [Link](data)
# Plotting histogram for Height
[Link](df['Height'], bins=5, color='blue', alpha=0.7, edgecolor='black')
[Link]('Height (in cm)')
[Link]('Frequency')
[Link]('Histogram of Height')
[Link]()

# Plotting histogram for Weight


[Link](df['Weight'], bins=5, color='green', alpha=0.7, edgecolor='black')
[Link]('Weight (in kg)')
[Link]('Frequency')
[Link]('Histogram of Weight')
[Link]()

Common questions

Powered by AI

Simple input-driven algorithms, while accessible and straightforward, can become a bottleneck in larger software applications due to non-scalable design patterns, limited user engagement, and increased maintenance overhead. Utilizing more advanced frameworks or introducing UI components can mitigate these limitations, offering better scalability, more efficient user handling, and improved interaction through event-driven architectures and ergonomic UI designs .

User-driven decision-making through conditional statements allows applications to cater dynamically to user choices, enhancing interactivity. By responding to user inputs with specific operations, like arithmetic choices or digit-to-word outputs, applications become more flexible and personalized, leading to a more engaging user experience. This design encourages developers to create user-centric interfaces .

Pandas and Matplotlib provide higher-level features for data representation compared to basic printing, enabling structured data manipulation and comprehensive visualizations. Pandas allow data analysis through series and dataframes, enhancing readability. Matplotlib offers visual representation capabilities like graphs and plots, providing users with intuitive insights into data trends and distributions, unlike text outputs that require more interpretation effort .

Sorting numbers in descending order helps highlight the largest values at a glance, facilitating quick analysis of which numbers dominate a dataset. Sorting can be achieved using simple comparisons, as shown in the document, but using Python's built-in sorted() function offers an alternative, more scalable solution that leverages Python's efficient sorting algorithms. This approach is particularly beneficial for larger datasets .

Looping allows for iterative processing of data, enabling the computation of sums and averages incrementally, as each number can be evaluated and accumulated in sequence. Optimizations can include using list comprehensions or numpy arrays for bulk operations, which avoids explicit loops and takes advantage of faster, vectorized operations in professional data analysis scenarios .

Efficient handling of user data through input-output mechanisms can be achieved by utilizing built-in functions such as input() for receiving data and print() for displaying results. For example, users can input their name and age using input statements, which are then displayed using print(). The code effectively separates data acquisition, processing, and output stages, making it efficient and modular .

The digit-to-word conversion method utilizes a series of if-elif statements to check the input digit and print the corresponding word. This linear approach, while straightforward for a limited range of numbers, becomes cumbersome with larger ranges or different languages. To simplify or expand this method, one could use a dictionary to map digits to words, reducing repetition and improving readability and efficiency by avoiding multiple conditional branches .

Calculating the sum of digits can be useful in digital root computation or in validations such as Luhn algorithm for credit cards. The presented method uses while loops to iteratively reduce the number and sum the modulus of 10 outcomes. More efficient algorithms could employ recursive strategies or inline calculations that consume less stack space, particularly important in embedded systems .

Using loops for prime number generation, as demonstrated by iterating from a lower to upper boundary, allows direct computation but scales poorly for large ranges due to its O(n^2) complexity. More sophisticated algorithms like the Sieve of Eratosthenes reduce processing time for large datasets through more intelligent candidate selection and elimination, improving efficiency by orders of magnitude .

Data structures such as dictionaries and lists provide efficient methods to store, retrieve, and manipulate data. Dictionaries allow fast lookup through key-value pairs, useful during data categorization, such as student marks. Lists manage ordered collections facilitating iteration and element retrieval. Their combination enables structured management of complex datasets, improving both speed and clarity in data handling .

You might also like