Python Lab Practice
Python Lab Practice
4. Write a program to store one value in variable and print that variable?
5. Write a program to take string from user input and print that string?
6. Program to add two integer values.
7. Write a program to do a sum of two value by input function?
8. Program to subtract two entered integer values.
9. Program to multiply two entered integer values.
10.Program to input two integer values and calculate first number raised to the
power second.
11.Write a program that converts a given number of days into years, weeks and
days.
12.Create a program that calculates and displays the area of a triangle using the
base and height provided by the user? Area=b*h/2
13.Develop a program that calculates the volume of a cylinder. Ask the user for
the radius and height?
pi = 3.14
volume = pi * radius * radius * height
14. Program to find the Simple Interest and the total amount when the
Principal, Rate of Interest and Time are entered by the user.
Lab-2
ASCII code
Ques: Given a character and we have to find its ASCII value.
Explain: An ASCII value is a code (numeric value) of keys. We put the any character, symbol etc., then the
computer can’t understand. A computer can understand only code and that code against each key is
known as ASCII Code.
Sample Input 0
a
Sample Output 0
97
Sample Input 1
A
Sample Output 1
65
Sample Input 2
c
Sample Output 2
99
Ques: In this program we are going to learn how to convert given feet into inches? Let’s understand
what are feet and inches first...
Word Feet is a plural of foot which is a measurement unit of length and inch is also a measurement of
unit length. A foot contains 12 inches. So the logic to convert feet to inches is quite very simple, we have
to just multiply 12 into the given feet (entered through the user) to get the measurement in inches.
In this example, we will read value of feet from the user and displays converted inches to the standard
output device.
Sample Input 0
15
Sample Output 0
180
Sample Input 1
2
Sample Output 1
24
Product of 2 numbers
Ques: The Program to read two integer numbers and display the product of both numbers taken as an
input.
Sample Input 0
10
20
Sample Output 0
200
Sample Input 1
4
5
Sample Output 1
20
Swapping
Ques: Take 2 integer from the user and then swap both the value and print as the output.
Sample Input 0
24
Sample Output 0
42
Sample Input 1
213 7863
Sample Output 1
7863 213
Number System
Print an entered value in Decimal, Octal and Hexadecimal format.
Sample Input 0
15
Sample Output 0
15
17
f
F
Sample Input 1
3
Sample Output 1
3
3
3
3
FLOOR & CEIL
E.g.
floor (123.46) then it will return 123.000000
ceil (123.46) then it will return 124.000000
Sample Input 0
123.45
Sample Output 0
123.000000
124.000000
Sample Input 1
69.98
Sample Output 1
69.000000
70.000000
Maths_Fun
Use of pow, sqrt functions on floating point values. take three variables from user ex: a,b,c.
a and b use in power and c use in sqrt function.
Both functions are library functions and declare in math header file.
E.g.
pow(2.0,3.0) then it will return 8.000000
sqrt(8.0) then it will return 2.828427
Sample Input 0
23
8
Sample Output 0
8.000000
2.828427
Sample Input 1
6.0 8.0
2976
Sample Output 1
1679616.000000
54.552727
Wonderful Chocolate Offer
Scenario: You have an uncle who daily gives you D chocolates up to N days. Also, you have C chocolates
already but your parents allow you only to eat one chocolate per day. Calculate the total chocolates at
the end of N days.
Input Format
Space separated C , N and D
Output Format
Single Integer representing the total chocolates at the end of N days.
Sample Input 0
555
Sample Output 0
25
Simple Interest
Scenario: You are given Principal Amount P, rate R and time T. Calculate Final Amount with Simple
Interest on it.
Input Format
A single line containing P, R and T space separated
Output Format
An integer representing the total amount.
Sample Input 0
1000 10 10
Sample Output 0
2000
Given two integers A and B, determine the minimum number of bit flips required to convert A to B.
Example:
Input:
A = 10
B=7
Output:
3
Test Cases:
Input: A = 15, B = 8 → Output: 3
Input: A = 5, B = 1 → Output: 1
Input: A = 0, B = 255 → Output: 8
Divisibility check
Given an integer number and two divisors d1 and d2, we have to check whether number is
divisible by d1 and d2 or not.
Input Format
Take an integer n whose divisibilty is to be checked.
Take the first divisor value d1.
Take the second divisor value d2.
Output Format
Print "Yes." if number is divisible by both the entered divisors.
Print "No." if number is not divisible by both or any of the entered divisors.
Sample Input 0
100
10
20
Sample Output 0
Yes.
Sample Input 1
90
10
20
Sample Output 1
No.
Profit or Loss 1
Your friend asks you for help. He tells you his Cost Price CP and Selling Price SP of an article. You have to
tell him whether it is profit or loss along with the percentage of loss/profit.
Output Format
First line should print Profit/Loss. Second line containing the profit/loss percentage rounding up to 2
decimal places.
Sample Input 0
1456
4655
Sample Output 0
Profit
219.71%
Sample Input 1
2400
1300
Sample Output 1
Loss
45.83%
Sample Input 2
1200
1200
Sample Output 2
No profit no loss
Question:
A farmer needs to determine whether a given number of animals can fit into a specific number of
pens(cage), with the following conditions:
Write a Python expression (without using loops or lists) to determine if all animals can be placed into the
pens based on the rules above.
Assume the inputs are two integers:
pens (the number of pens available).
animals (the number of animals to be placed).
Spy Number?
A particular number is known as a Spy number if the sum of its digits is exactly equal to the
product of its digits. Let’s look at some examples:
Example 1: 1421
Sum of digits ==> 1+4+2+1 = 8
Product of digits ==> 1*4*2*1 = 8
Since the product and the sum of the digits are exactly the same, the number is a spy number
Example 2: 1342
Sum of digits ==> 1+3+4+2 = 10
Product of digits ==> 1*3*4*2 =24
Clearly, the product and sum are not equal and hence, the number is not a spy number.
Lab-3
1. Write a program to input two numbers (A & B) from user and print the
maximum element among A & B.
2. Write a program to input three numbers (A, B & C) from user and print the
minimum element among A, B & C.
3. Develop a Python program to find the largest among three numbers.
4. Make a program that asks the user for their age and determines whether
they are eligible to vote or not based on a minimum voting age (e.g., 18
years old).
5. Write a Python program to check if a given number is even or odd.
6. Write a program to determine if a year is a leap year or not using
conditional statements.
7. Write a program to take a single digit number from the key board and print
is value in English word? (Same as switch case)0 to 9
8. Write a program to take a single digit number from the key board and print
is value in English word? (Same as switch case)0 to 99
Wish me
You are given a time in format HH and MM. You have to print Good Morning, Good Afternoon, Good
Evening, Good Night according to time.
Constraints
0 < HH < 23 0 < MM < 59
Output Format
Single line containing wish message.
Sample Input 0
23 12
Sample Output 0
Good Night
Example:Input:
S1 = "abcde"
S2 = "deabc"
Output:
True
Test Cases:
----------------------------------------------------------------------------------------------------------
Lab-4
1. Program to find whether an entered number is prime or not. N….
2. Program to find the factorial of an entered number.
3. Program to print the Fibonacci series of an entered number.
4. Program to find the sum of digits of an entered number.
5. Program to find the series of all three digits Armstrong numbers.
6. Program to display the table of an entered number in the following format:
2*1=2
2*2=4
………..
2*10=20
7. Write a program to find whether a given string or number is palindrome or not.
Vowel or Consonant 1
This program will read a character from user and check whether it is VOWEL or CONSONANT if
entered character was an alphabet using conditional operators statement.
Input Format
Take a char ch form the user.
Constraints
If other than alphabet is entered, then print "Not an alphabet."
Output Format
If entered character is vowel, then print "Vowel."
If entered character is consonant, then print "Consonant."
If entered character is not alphabet, then print "Not an alphabet."
Sample Input 0
e
Sample Output 0
Vowel.
Sample Input 1
X
Sample Output 1
Consonant.
Sample Input 2
2
Sample Output 2
Not an alphabet.
String Programs:
1. input: Pragya
output: aygarP
Q2. Write a program to merge characters of 2 strings into a single string by taking character
alternatively?
input: s1=Anshu
s2=Mini
output: AMnisnhiu
Q3. Find the Number of Vowels, Consonants, Digits and White space in a String
Q4. Remove all Characters including space in a String except alphabet
Q5. Print all the duplicates in the input string.
Q6. Write a program to remove duplicate characters from the given input string?
input: ABCDABBCDABBBCCCDDEEEF
Q7. Write a program to print characters at odd position and even position for the given String?
Q8. Write a program to sort the characters of the string and first alphabet symbols followed by numeric
values
input: B4A1D3
Output: ABD134
Q1.
1. WAP to Traversing the elements of List using while loop.
2. Sort the list in reverse order
3. Write a program to display unique vowels present in the given word?
4. WAP which will select a random name from a list of names and the person
selected will have to pay for everybody’s food bill.
5. Write a Python program to print the even numbers from a given list.
Sample List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result: [2, 4, 6, 8]
Expected Output:
Unique Elements: [3, 1, 2, 4, 5]
Expected Output:
Maximum Element: 15
Leetcode:
Q1: Read the input string and Identify all distinct vowels present in the string. Return the list of unique
vowels and the total count of these unique vowels.
Input: Input:
hello world Python Programming
13. Write a program to find a missing number in an consecutive integers array: (always has a pattern)
Sample Output
Array = [1, 2, 4, 5, 6, 7]
Missing Array Number = 3
14. Write a program to Find prime and non-prime numbers in the array
Sample input
Array = {3, 12, 21, 11}
Output
3 - Prime
12 - Not Prime
21 - Not Prime
11 – Prime
15. Write a program to Move all zero at the end of the array
Sample Output
Array = [1,0,45,34,0,67,2,0]
Array after Moving Zeros to End = [1 45 34 67 2 0 0 0]
16. Write a Python program to convert decimal number into any base.
17. Write a Python program to convert any base to decimal number.
18. Write a Python program to convert any base number into any base number.
19. Design simple matrix using list.
Problem: Given a list and a number k, rotate the list to the right by k positions.
Explanation: if we rotate our array n times then we will get original array to remove the time complexity
we can use k%arr.len.eg: 50%4=2
Example:
Input: list = [1, 2, 3, 4, 5], k = 2
Output: [4, 5, 1, 2, 3]
input:["flower","flow","flight"]
output: "fl"
input:["dog","rececar","car"]
output: " "
Lab-5
Two sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they
add up to target.
You may assume that each input would have exactly one solution, and you may not use
the same element twice. You can return the answer in any order.
Example 1:
Input:
nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Output: [1,2]
Example 3:
Output: [0,1]
Given two non-negative integers low and high. Return the count of odd numbers
between low and high (inclusive).
Example 1:
Output: 3
Example 2:
Output: 1
Majority Element:
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the
majority element always exists in the array.
Example 1:
Example 2:
Output: 2
Constraints:
n == nums.length
Constraints:
The number of nodes in the list is in the range [0, 200].
-100 <= Node.val <= 100
-200 <= x <= 200
List Comprehensions:
1. Filter Positive Numbers and Double Them
Problem Statement: Given a list of integers nums, return a list containing only the positive
numbers from nums, where each positive number is doubled.
Constraints:
1≤len(nums)≤104
−104 ≤nums[i]≤104
Example:
Input:
nums = [-3, -2, 0, 2, 5]
output:
[4, 10]
Problem Statement: Given a list of words words, return a list containing only the words that have
more than 3 letters.
Example:
Input:
words = ["hi", "is", "this", "an", "example"]
Output:
["this", "example"]
Problem Statement: Given a list of words words, return a list containing only the words that
start with a vowel, but each word should be reversed.
Example:
Input:
words = ["Niharika", "Orange", "GLA","Umbrella"]
Output:
["egnarO", "allebmU"]
Trip or Not
Your exams are near and you have to prepare for that. You are given N days left for your exams in which
you have to prepare S subjects each having C chapters. Each chapter takes H hour to prepare. Goa trip is
before exams and it is L days long trip during which you cannot study. You want to go Goa so you are
ready to study T hours daily. You have to calculate and find whether or not you can go Goa. If you can go
Goa, print Goa Jaayenge otherwise print Padhai Karenge.
Input Format
Single line containing space separated N,S,C,H,L,T
Output Format
Single line contain message mentioned in question.
Sample Input 0
111111
Sample Output 0
Padhai Karenge
Funny or Not
Hemant Sir makes questions for Hacker Rank funny so that students can understand questions
better. This time most of the sections were misbehaving so Hemant Sir decide not to keep
questions funny, but this is only because of few sections. So, he found a new way to decide
whether to make funny questions or not. If at the end of the week, his anger level will be
positive, then he will make simple questions otherwise he will make funny questions. There are
total N sections out of which B sections are misbehaving due to which his anger level increases
by I unit per section and G sections are behaving very well due to which his anger level falls
down by D unit per section. Find out whether questions will be funny or not ? If questions will
be funny print Funny Questions. If questions will not be funny, print Simple Questions. In case of
confusion, print God Knows!.
Input Format
Single Line containing five space separated integers N, B, G, I, D.
Output Format
Single line containing the appropriate message.
Sample Input 0
23 5 7 9 7
Sample Output 0
Funny Questions
9. Write a Python program to create a function that takes one argument, and that argument
will be multiplied with an unknown given number .
Sample Output:
Double the number of 15 = 30
Triple the number of 15 = 45
Quadruple the number of 15 = 60
Quintuple the number 15 = 75
10. Write a Python program to square and cube every number in a given list of integers using
Lambda.
Original list of integers:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Square every number of the said list:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Cube every number of the said list:
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
12. Write a Python program to rearrange positive and negative numbers in a given array using
Lambda.
Original arrays:
[-1, 2, -3, 5, 7, 8, 9, -10]
Rearrange positive and negative numbers of the said array:
[2, 5, 7, 8, 9, -10, -3, -1]
Nested list
13. Write a Python program that generates random alphabetical characters, alphabetical
strings, and alphabetical strings of a fixed length. Use random.choice()
import random
import string
print("Generate a random alphabetical character:")
print(random.choice(string.ascii_letters))
print("\nGenerate a random alphabetical string:")
max_length = 255
str1 = ""
for i in range(random.randint(1, max_length)):
str1 += random.choice(string.ascii_letters)
print(str1)
print("\nGenerate a random alphabetical string of a fixed length:")
str1 = ""
for i in range(10):
str1 += random.choice(string.ascii_letters)
print(str1)
# Usage
# Define the numerator and denominator values.
numerator = 100
denominator = 0
# Call the divide_numbers function with the provided numerator and denominator.
divide_numbers(numerator, denominator)
15. Write a Python program that prompts the user to input two numbers and raises a
TypeError exception if the inputs are not numerical.
# Usage
# Call the get_numeric_input function to get the first numeric input from the user with the
provided prompt.
n1 = get_numeric_input("Input the first number: ")
# Call the get_numeric_input function to get the second numeric input from the user with the
provided prompt.
n2 = get_numeric_input("Input the second number: ")
# Calculate the product of the two input numbers.
result = n1 * n2
# Print the result, which is the product of the two numbers.
print("Product of the said two numbers:", result)
16. Write a Python program that executes a list operation and handles an AttributeError
exception if the attribute does not exist.
17.Write a Python program that opens a file and handles a FileNotFoundError exception if the
file does not exist.
# Usage
# Prompt the user to input a file name and store it in the 'file_name' variable.
file_name = input("Input a file name: ")
# Call the open_file function with the provided file name.
open_file(file_name)
18.Write a NumPy program to create a new array of given shape (5,6) and type, filled with
zeros.
Change the said array in the following format:
Given array:
[[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
New array:
[[3 0 3 0 3 0]
[7 0 7 0 7 0]
[3 0 3 0 3 0]
[7 0 7 0 7 0]
[3 0 3 0 3 0]]
# Creating a NumPy array 'nums' with shape (5, 6) filled with zeros of integer type
nums = np.zeros(shape=(5, 6), dtype='int')
# Assigning value 3 to every alternate row and column starting from index 0
nums[::2, ::2] = 3
# Assigning value 7 to every alternate row starting from index 1 and every column starting from
index 0
nums[1::2, ::2] = 7
# Printing the updated array after assigning values 3 and 7
print("\nNew array:")
print(nums)
Q1. Write a Python script to display the various Date Time formats.
import time
import datetime
print("Current date and time: " , datetime.datetime.now())
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))
Q2.Write a Python program to determine whether a given year is a leap year using function and if the
year is leap year return True otherwise return false.
Test case:1
Input: year=1900
Output: False
Test case:2
Input: year=2024
Output: True
def leap_year(y):
if y % 400 == 0:
return True
if y % 100 == 0:
return False
if y % 4 == 0:
return True
else:
return False
print(leap_year(1900))
print(leap_year(2004))
3. Write a Python program to convert a string to datetime.
Sample String : Jan 1 2014 2:43PM
Expected Output : 2014-07-01 14:43:00
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days = 1)
tomorrow = today + datetime.timedelta(days = 1)
print('Yesterday : ',yesterday)
print('Today : ',today)
print('Tomorrow : ',tomorrow)
5. Write a Python program to find the date of the first Monday of a given week.
Sample Year and week : 2024, 5
Expected Output : Mon Jan 29 00:00:00 2024
import time
print(time.asctime(time.strptime('2024 5 1', '%Y %W %w')))
def sum(numbers):
# Initialize a variable 'total' to store the sum of numbers, starting at 0
total = 0
7. Write a Python function that takes a list and returns a new list with distinct elements from
the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
# Define a function named 'unique_list' that takes a list 'l' as input and returns a list of unique
elements
def unique_list(l):
# Create an empty list 'x' to store unique elements
x = []
# Print the result of calling the 'unique_list' function with a list containing duplicate elements
print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))