0% found this document useful (0 votes)
13 views27 pages

Python Basics: Input, Output, and Operations

The document contains a series of practical programming exercises in Python, covering basic input/output, arithmetic operations, control structures, and functions. Each practical includes multiple questions that guide the user through tasks such as displaying values, performing calculations, and implementing logic for various scenarios. The exercises are aimed at building foundational programming skills and understanding of Python syntax.

Uploaded by

thushimileni2007
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)
13 views27 pages

Python Basics: Input, Output, and Operations

The document contains a series of practical programming exercises in Python, covering basic input/output, arithmetic operations, control structures, and functions. Each practical includes multiple questions that guide the user through tasks such as displaying values, performing calculations, and implementing logic for various scenarios. The exercises are aimed at building foundational programming skills and understanding of Python syntax.

Uploaded by

thushimileni2007
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 01

Q1
#display your name and school in two separate lines

name=input("enter your name")

school=input("enter your school")

print(name)

print(school)

Q2
#Display the following output using print() statements

#*

#**

#***

#****

#*****

print("*")

print("**")

print("***")

print("****")

Q3
# Input values for int, float and string data types and display the value of each of the variable.

int_value=int(input("enter an integer value:"))

float_value=float(input("enter a float value"))

string_value=input("enter a string value ")

print("\nThe values you entered are:")

print(f"integer:{int_value}")
print(f"float:{float_value}")

print(f"string:{string_value}")

Q4
#Input two integers and display the total.

no1=int(input("enter a number"))

no2=int(input("enter a number"))

sum=no1+no2

print(f"sum of 2 numbers:{sum}")

Q5
# Input two numbers with decimals(fractions) and display the average with decimals.

no1=float(input("enter a number"))

no2=float(input("enter a number"))

sum=no1+no2

average=sum/2

print (f"the average is:{average}")

Q6
#Input a student name, birth year and display student name with age.

name=input("enter a name")

byear=int(input("enter birthyear"))

current_year=2024

age=current_year-byear
print(f"my name is {name} and i'm {age} years old")

Q7
#Input two numbers, swap the values and display the output. (Before swap and after swap)

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# before swap

print(f"Before swap: num1 = {num1}, num2 = {num2}")

num1, num2 = num2, num1

# after swap

print(f"After swap: num1 = {num1}, num2 = {num2}")

practical 02
Q1
#Have the computer print

#HI, HOW OLD ARE YOU?

#on one line. The user then enters his or her age immediately after the question mark. The
computer then skips two lines and prints on two consecutive lines.

#WELCOME (age)

#LET’S BE FRIENDS!

#Write a complete Python program to do the above.

print("HI HOW OLD ARE YOU?",end="")

age = input()

print(f"\n\nWELCOME {age}")
print("LET'S BE FRIENDS!")

Q2
#Write a simple program to evaluate the average speed of a car traveled in meters per second
(ms-1). Given that

#average speed=distance travelled\time taken

#Try using integer variables. What would be the problem? Why? How to fix the problem?

distance=int(input("enter the distance travelled"))

time=int(input("enter the time taken"))

speed=distance/time

print(f"average speed is {speed}")

Q3
#Convert a temperature reading in degrees Fahrenheit to degrees Celsius, using the formula

#C = ( 5 / 9 ) x ( F – 32 )

#Test the program with the following values: 68, 150, 212, 0, -22, -200 (degree Fahrenheit).

test_values = [68, 150, 212, 0, -22, -200]

for f in test_values:
c = (5 / 9) * (f - 32)
print(f"{f}°F = {c:.2f}°C")
Practical 03
Q1
#Write a program to add two numbers and subtract the second number from the first.

num1=int(input("enter the first number"))

num2=int(input("enter the second number"))

difference=num2-num1

print(f"the answer is:{difference}")

Q2
#Input a number and increment the value of a number by 1 and display it.

x=int(input("enter a number"))

increment=x+1

print(f"the answer is:{increment}")

Q3
#Decrement the value of a number by 1 and display it.

x=int(input("enter a number:"))
decrement=x-1

print(f"the answer is:{decrement}")

Q4
#Write a program to multiply two numbers and divide the first number by the second.

x=int(input("enter the first number"))

y=int(input("enter the second number"))

multiplication=x*y

division=x/y

print(f"the answer to multiplication is:{multiplication} and division:{division}")

Q5
#Find the square of a number.

x=float(input("enter a number"))

square=x**2

print(f"the square of {x} is :{square}")

Q6
#Find the remainder when one number is divided by another.

num1=float(input("enter the first number:"))

num2=float(input("enter the second number:"))


remainder=num1%num2

print(f"the remainder is :{remainder}")

Q7
# Perform floor division of two numbers.

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

floor_division = num1 // num2

print(f"The floor division of {num1} by {num2} is {floor_division}.")

Q8
#Swap the values of two variables using arithmetic operators.

a=int(input("enter 1st number(a):"))

b=int(input("enter 2nd number(b):"))

a=a+b

b=a-b

a=a-b

print("After swapping:")

print("a =",a)

print("b=",b)
Q9
#Find the average of three numbers.

num1=int(input("enter the first number"))

num2=int(input("enter the second number"))

num3=int(input("enter the third number"))

sum=num1+num2+num3

average = sum/3

print(f"the average is : {average}")

Q10
# Write a program to calculate the result of a + (b * c).

a=int(input("enter a value for a:"))

b=int(input("enter a value for b:"))

c=int(input("enter a value for c:"))

x=a+(b*c)

print("the result is:",x)

Q11
# Calculate the area of a rectangle given its length and width.

length=float(input("enter a value:"))

width=float(input("enter a value"))

area=length*width
print(f"the area of rectangle is:{area}")

Q12
# Calculate the perimeter of a rectangle.

length=float(input("enter a value"))

width=float(input("enter a value"))

perimeter=length*2+width*2

print(f"the perimeter of the rectangle is :{perimeter}")

Q13
#Check if a number is even or odd using the modulus operator.

num=int(input("enter a number"))

if num % 2 == 0:

print(f"{num} is an even number")

else:

print(f"{num} is an odd number")

Q14
#Swap two variables without using a temporary variable or addition/subtraction.

a=int(input("enter the first number (a):"))

b=int(input("enter the first number (b):"))

a= a^b
b= a^b

a= a^b

print("after swapping:")

print("a = ",a)

print("b = ",b)

Q15
#Calculate the BMI using the formula BMI = weight / (height ** 2).

weight=float(input("enter your weight(in kg):"))

height=float(input("enter your height(in meters):"))

BMI=weight/(height**2)

print(f"your BMI is:{BMI:.2f}")

practical 04
Q1
#write a python program to allow the user to input two numbers and display the highest number

num1=int(input("enter the 1st number"))

num2=int(input("enter the 2nd number"))

if (num1>num2):

print(f"{num1} is the highest")

else:

print(f"{num2} is the highest")


Q2

#write a program to input three number and display the highest number and smallest number

num1=float(input("enter 1st number"))

num2=float(input("enter 2nd number"))

num3=float(input("enter 3rd number"))

highest=max(num1,num1,num3)

smallest=min(num1,num2,num3)

print(f"the highest number:{highest}")

print(f"the smallest number:{smallest}")

Q3
#Display employee name, new salary, when the user inputs employee name, and basic salary.

# You can refer following formula and the table to calculate new salary:

# New Salary = Basic Salary + Increment

# Basic Salary Increment

# Less than 5000 5% of Basic Salary

# More than or equal 5000

# and less than 10000 10% of Basic Salary

# More than or equal 10,000 15% of Basic Salary

employee_name=input("enter the employee's name:")

basic_salary=int(input("enter the basic salary:"))


if basic_salary>5000:

increment=0.05*basic_salary

elif 5000 <= basic_salary>10000:

increment=0.10*basic_salary

else:

increment=0.15*basic_salary

new_salary=basic_salary + increment

print(f"\nEmployee Name: {employee_name}")

print(f"New salary: {new_salary:.2f}")

Q4
#Write a program that reads the radius of a circle and prints the circle’s diameter, circumference
and area.

#Use the constant value 3.14159 for π. Perform each of these calculations inside the print
statement(s).

radius=float(input("enter the radius of the circle:"))

print(f"Diameter:{2*radius}")

print(f"circumference:{2*3.14159*radius}")

print(f"Area:{3.14159*radius**2}")

Q5
#Write a program that reads in two integers and determines and prints if the first is a multiple of
the second.

num1=int(input("enter 1st number:"))

num2=int(input("enter 2nd number:"))


if num1 % num2 == 0:

print(f"{num1} is a multiple of {num2}")

else:

print(f"{num1} is not a multiple of {num2}")

Q6
# Write a program that inputs three numbers and displays the highest number among them. If
two or more numbers are equal,

#display a message indicating that they are equal.

num1=int(input("enter 1st number:"))

num2=int(input("enter 2nd number:"))

num3=int(input("enter 3rd number:"))

if num1==num2:

print(f"1st and 2nd numbers are equal")

elif num1==num3:

print(f"1st and 3rd numbers are equal")

elif num2==num3:

print(f"2nd and 3rd numbers are equal")

elif num1==num2==num3:

print("All the numbers are equal")

highest=max(num1,num2,num3)

print(f"highest number is {highest}")

Q7
# Write a program that takes a student's score as input and assigns a grade based on the
following criteria:

# 90–100: Grade A

#80–89: Grade B

#70–79: Grade C
#60–69: Grade D

#Below 60: Grade F

# Function to assign grade based on score

score=int(input("enter your marks(0-100): "))

if 90 <= score <= 100:

print("you have got a Grade A")

elif 80 <= score <= 89:

print("you have got a Grade B")

elif 70 <= score <= 79:

print ("you have got a Grade C")

elif 60 <= score <= 69:

print("you have got a Grade D")

elif 0 <= score < 60:

print("you have got a Grade F")

Q8
# Write a program that calculates the discount for a customer based on the total purchase
amount:

# Purchase below $100: No discount

#$100 to $500: 5% discount

#$500 to $1000: 10% discount

# Above $1000: 15% discount Display the total amount after applying the discount.

purchase_amount=float(input("please, enter the total purchase amount($) :"))

if purchase_amount < 100:

discount = 0

elif 100 <= purchase_amount <= 500:

discount = 0.05 * purchase_amount


elif 500 < purchase_amount <= 1000:

discount = 0.10 * purchase_amount

else:

discount = 0.15 * purchase_amount

total_amount = purchase_amount - discount

print(f"Original Purchase Amount: ${purchase_amount:.2f}")

print(f"Discount Applied: ${discount:.2f}")

print(f"Total Amount After Discount: ${total_amount:.2f}")

Q9
#Write a program to check if a given year is a leap year or not. A year is a leap year if:

#It is divisible by 4, but not by 100.

#OR it is divisible by 400.

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print(f"{year} is a leap year.")

else:

print(f"{year} is not a leap year.")

Q10
# Write a program that takes three angles of a triangle as input and determines whether the
triangle is valid.

# A triangle is valid if the sum of its angles equals 180 degrees.

# Function to check if a triangle is valid

angle1 = float(input("Enter the first angle of the triangle: "))


angle2 = float(input("Enter the second angle of the triangle: "))

angle3 = float(input("Enter the third angle of the triangle: "))

if angle1 > 0 and angle2 > 0 and angle3 > 0 and (angle1 + angle2 + angle3 == 180):

print("The triangle is valid.")

else:

print("The triangle is not valid.")

practical 05
Q1
# Write a Python program to print numbers from 0 to 100. (You are required to write 2 separate
answers each using While

#and For looping structures).

# Using while loop

num = 0

while num <= 100:

print(num, end="\n ")

num += 1

# Using for loop

for num in range(101):

print(num, end=" ")

Q2
#Write a Python program to calculate and print the total of 10 marks and the average. If the

#average is less than 50 program should print “Fail!” otherwise “Pass!”

marks=[]

total = 0
for i in range(1, 11):

mark = float(input(f"Enter mark {i}: "))

[Link](mark)

total = sum(marks)

average = total / 10

print(f"\nTotal Marks: {total:.2f}")

print(f"Average Marks: {average:.2f}")

if average < 50:

print("Fail!")

else:

print("Pass!")

Q3
#Write a Python program to calculate factorial of a user given number. Hint:

#Select an appropriate looping structure.

#Factorial of ‘0’ is ‘1’ (0! = 1)

#Ex: factorial of number 5 is #calculated as 5! = 5*4*3*2*1

number = int(input("Enter a number to calculate its factorial: "))

result = 1

i=1

while i <= number:

result *= i

i += 1
print(f"Factorial of {number} is {result}")

Q4
# Write a Python program to calculate the sum of all digits of a user given number.

#If user input 123 your program should output 6. (calculated as 1+2+3)

# Get input from the user

number = int(input("Enter a number to calculate the sum of its digits: "))

digit_sum = 0

while number > 0:

digit_sum += number % 10

number //= 10

print(f"The sum of the digits is: {digit_sum}")

Q5
# Write a Python program to calculate nth power of a given integer. The user input base
#and exponent

#(Do NOT use inbuilt functions, instead use a loop)

base = int(input("Enter the base number: "))

exponent = int(input("Enter the exponent: "))

result = 1

if exponent >= 0:

for i in range(exponent):

result *= base

else:
for i in range(-exponent):

result *= base

result = 1 / result

print(f"{base}^{exponent} = {result}")

Q6
# Write a Python program to print first 10 numbers of “Fibonacci Sequence”.

a=0

b= 1

print("First 10 numbers of the Fibonacci Sequence:")

for _ in range(10):

print(a, end=" ")

a, b = b, a + b

Q7
#Write a Python program to check whether a given number is an Armstrong Number! (Refer to
previous flowcharts)

number = int(input("Enter a number: "))

num_str = str(number)

num_digits = len(num_str)

sum_of_powers = 0

for digit in num_str:

sum_of_powers += int(digit) ** num_digits

if sum_of_powers == number:
print(f"{number} is an Armstrong Number!")

else:

print(f"{number} is not an Armstrong Number.")

Q8
#Write a Python program to print all the ASCII values for letters A to Z.

for letter in range(65, 91):

print(f"{chr(letter)}: {letter}")

Q9
# Write a program to print this pattern.

#*

#**

#***

#****

#*****

rows=5

for i in range(1,rows+1):

for j in range(i):

print('*',end="")

print()

Q10

# Write a program to check whether a given number is prime or not.

num=int(input("enter a number"))
isPrime=True

if num < 2:

isPrime= False

else:

for i in range(2,num):

if num % i == 0:

isPrime = False

break

if isPrime:

print(f"{num} is a prime number")

else:

print(f"{num} is not a prime number")

Q11
# Write a program to print all factors of a given integer.
num=int(input("enter a number:"))
print(f"the factors of {num} are:")

for i in range(1,num+1):
if num % i == 0:
print(i,end=" ")

Q12
# Write a program to add all user inputs until user input ‘-1’. And then display the sum.

sum=0
while True:

number = int(input("enter a number:"))

if number == -1:

break

sum=sum+number #or sum += number

print("the sum of the numbers entered is:",sum)

Q13
# Write a program to read user inputs for an integer array (size = 10) and print the array.

array=[]

for i in range(10):

number = int(input(f"enter a number{i+1}:"))

[Link](number)

print("the entered array is:",array)

Q14
# Re-Write the above code to count all the even numbers in above integer array and display the
count.

array=[]

for i in range(10):

number = int(input(f"enter a number{i+1}:"))

[Link](number)

even_count=0

for num in array:

if num % 2 == 0:

even_count+=1
print("the entered array is:",array)

print(f"the number of even numbers in the array is:{even_count}")

Section B
Q1
#Input 10 numbers and output the number of positive, number of negative, number of zeros.

pos = 0

neg = 0

zeros = 0

for i in range(10):

num = int(input("enter an integer:"))

if num > 0:

pos =+ 1

elif num < 0:

neg += 1

else:

zeros += 1

print(f"the number of positive integers:{pos}")

print(f"the number of negative integers:{neg}")

print(f"the number of zeros:{zeros}")

Q2
#Input Marks of 10 students and output the maximum, minimum and average marks.

marks=[]

for i in range(10):

mark =float(input(f"enter mark of the student{i+1}:"))

[Link](mark)
M=max(marks)

N=min(marks)

ave=sum(marks)/len(marks)

print(f"the maximun score is {M} while minimum score is {N} and average is {ave}")

Q3
# Input price of 10 items and display the average value of an Item, number of items which the
price is greater than 200.

prices=[]

print("enter the prices of 10 items:")

for i in range(10):

price=float(input(f"enter price of an item{i+1}:"))

[Link](price)

average_price=sum(prices)/len(prices)

count_greater_than_200=0

for price in prices:

if price >200:

count_greater_than_200 += 1

print(f"the average price of an item is:{average_price:.2f}")

print(f"the number of items with prices greater than 200:{count_greater_than_200}")

Q4
# Input the Employee No and the Basic Salary of the Employees in an organisation, ending with
the dummy value -999 for Employee No and

#count the number Employees whose Basic Salary > = 5000.


employee_count=0

salary_5000_or_more=0

print("Enter employee number and basic [Link] -999 as employee number to stop.")

while True:

employee_no=int(input("enter the employee number:"))

if employee_no== -999:

break

basic_salary=float(input("enter the basic salary:"))

if basic_salary >=5000:

salary_5000_or_more += 1

employee_count+=1

print(f"Total number of employees entered:{employee_count}")

print(f"number of employees with basic salary >=5000: {salary_5000_or_more}")

Q5
#. Input Employee Number and Hours worked by employees to display the following:

#• Employee Number, Over Time Payment, and the percentage of employees whose Over Time
Payment exceed Rs. 4000/-.

#• The user should input –999 as Employee Number to end the program, and the normal Over
Time Rate is Rs.150 per hour

#and Rs. 200 per hour for hours in excess of 40.

employee_data = []
total_employees = 0

employees_with_high_overtime = 0

print("Enter employee number and hours worked. Enter -999 for hours worked to stop.")

while True:

emp_no = int(input("Enter employee number: "))

hours_worked = float(input("Enter hours worked (enter -999 to stop): "))

if hours_worked == -999:

break

if hours_worked > 40:

overtime_hours = hours_worked - 40

else:

overtime_hours = 0

overtime_payment = overtime_hours * 200

total_employees += 1

if overtime_payment > 4000:

employees_with_high_overtime += 1

employee_data.append((emp_no, overtime_payment))

if total_employees > 0:

percentage_high_overtime = (employees_with_high_overtime / total_employees) * 100

else:

percentage_high_overtime = 0
print("\nEmployee Details:")

for emp_no, overtime_payment in employee_data:

print(f"Employee Number: {emp_no}, Overtime Payment: Rs. {overtime_payment:.2f}")

print(f"\nPercentage of employees with overtime payment exceeding Rs. 4000:


{percentage_high_overtime:.2f}%")

You might also like