0% found this document useful (0 votes)
2 views26 pages

Python Lab Practice

The document outlines a series of programming tasks and exercises across multiple labs, focusing on basic Python programming concepts such as input/output, arithmetic operations, control structures, and string manipulation. It includes tasks like calculating areas, converting units, checking for prime numbers, and working with lists. Additionally, it covers advanced topics like cyclic rotation checks and determining profit or loss based on user input.

Uploaded by

pragyas847
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)
2 views26 pages

Python Lab Practice

The document outlines a series of programming tasks and exercises across multiple labs, focusing on basic Python programming concepts such as input/output, arithmetic operations, control structures, and string manipulation. It includes tasks like calculating areas, converting units, checking for prime numbers, and working with lists. Additionally, it covers advanced topics like cyclic rotation checks and determining profit or loss based on user input.

Uploaded by

pragyas847
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
You are on page 1/ 26

Lab-1

1. Write a program to print Hello python


2. Program to Use one print function and print strings “Hello” and “World” in
different lines.
3. Program to print strings as it is as shown:

Hello Welcome to GLA


Hello Welcome to “GLA”
Hello ‘Welcome’ to “GLA”

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

Ques: Use of floor and ceil functions on floating point values.


Explain: Both functions are library functions and declare in math header file. Floor ignores the fraction
part and just print the same in floating point.

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

Question: Minimum Bit Flips

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:

 Each pen can hold only one animal.


 However, if the number of pens is odd, one additional animal can be placed in one of the pens.
 The farmer must use logical operators (and, or, not, etc.) to determine if all animals can fit into
the pens.

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).

Inputs and Outputs:


Example 1:
Input: pens = 7, animals = 8
Output: True (One extra animal can fit since pens are odd.)
Example 2:
Input: pens = 4, animals = 5
Output: False (Pens are even, and there aren't enough for the animals.)
Example 3:
Input: pens = 3, animals = 4
Output: True (One extra animal can fit since pens are odd.)
Example 4:
Input: pens = 6, animals = 6
Output: True (Pens are even, and the exact number of animals fits.)

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.

Good Morning: 4:00AM to 11:59AM


Good Afternoon: 12:00PM to 15:59PM
Good Evening: 16:00PM to 20:59PM
Good Night: 22:00PM to 23:59AM and 1:00AM to 3:59 AM

NOTE: Hour and Minutes are given in 24 Hour Format


Input Format
Single line containing space separated hour H and minute MM.

Constraints
0 < HH < 23 0 < MM < 59

Output Format
Single line containing wish message.
Sample Input 0
23 12
Sample Output 0
Good Night

Find The Operator


You are given two integers A and B. Your friend have applied some operator on those integers
and produced some result R. You have to find the operator. Note: 1. Operator can be one of
the + - / * % only. 2. In case of division compare only quotient. 3. If operator is not commutative,
you have to check every possible combination of operands with operator.
Input Format
Single line containing three space separated integers A, B and R.
Constraints
0 < |A,B,R| < 10000000
Output Format
Single line containing the operator O.
Sample Input 0
448
Sample Output 0
+

Question: Cyclic Rotation Check

Two strings S1 and S2 are given. Check if S2 is a cyclic rotation of S1.

Example:Input:
S1 = "abcde"
S2 = "deabc"
Output:
True
Test Cases:

Input: S1 = "hello", S2 = "lohel"


Output: True
Input: S1 = "rotation", S2 = "tionrota"
Output: True
S1 =Python S2 =theynp
False

----------------------------------------------------------------------------------------------------------

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:

Q1. Program to reverse order of words.

1. input: Pragya
output: aygarP

2. input: Learning Python is very Easy


output: Easy Very is Python Learning

3. input: Learning Python is very Easy


output: gninraeL nohtyP si yrev ysaE

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]

1. Accept a list of integers as input.


2. Display the resulting list of unique elements.
Example:
Consider the following input and expected output:
Input:
[3, 1, 2, 2, 4, 1, 5]

Expected Output:
Unique Elements: [3, 1, 2, 4, 5]

3. Determine the maximum element within the given list.


4. Display the maximum element.
Example:
Consider the following input and expected output:
Input:

[8, 15, 3, 12, 7, 10]

Expected Output:
Maximum Element: 15

5. Write a program to print the sum values of an list.


6. Write a program to calculate the average value of array elements.
7. Write a program to array elements and print all Odd number.
8. Write a program to array elements to print sum of Odd Numbers
9. Write a program to merge two array elements to store a third array
Sample Output
First Array = [1, 2, 3, 4, 5]
First Array = [6, 7, 8, 9, 10]
Merge two Array Elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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

Output: ['e', 'o'] Output:['o', 'a', 'i']


Count of unique vowels: 2 Count of unique vowels: 3

2.Write a program to array elements and print all Positive number.


Sample Output
Array = {67, -4, 3, -5, 44}
Sample Output
Positive Array Elements = {67, 3, 44}

10. Write a program to search an element in an array.


11. Write a program to find the second-largest element from a sorted and unsorted array.
12. Write a program to find the common elements between two arrays of integers
Sample input:
First Array = [10, 20, 30, 40, 50]
Second Array = [10, 30, 60, 50, 70]
Common Array Elements = [10, 30, 50]

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.

20. first solve one rotation:


Rotate a list by k elements: right=0---1 left= 1---0

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]

5.Longest common -Prefix(leetcode)

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:

Input: nums = [3,2,4], target = 6

Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6

Output: [0,1]

2. Count odd numbers in an interval range

Given two non-negative integers low and high. Return the count of odd numbers
between low and high (inclusive).

Example 1:

Input: low = 3, high = 7

Output: 3

Explanation: The odd numbers between 3 and 7 are [3,5,7].

Example 2:

Input: low = 8, high = 10

Output: 1

Explanation: The odd numbers between 8 and 10 are [9].

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:

Input: nums = [3,2,3]


Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]

Output: 2

Constraints:

n == nums.length

1 <= n <= 5 * 104

-109 <= nums[i] <= 109

86. Partition List


Given the head of a list and a value x, partition it such that all nodes less than x come before nodes
greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example 1:

Input: head = [1,4,3,2,5,2], x = 3


Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2
Output: [1,2]

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]

2. Extract Words with More Than 3 Letters

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"]

3. Filter and Reverse Words

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

Rock paper Scissors

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)

14.Write a Python program to handle a ZeroDivisionError exception when dividing a number


by zero.

# Define a function named divide_numbers that takes two parameters: x and y.


def divide_numbers(x, y):
try:
# Attempt to perform the division operation and store the result in the 'result' variable.
result = x / y
# Print the result of the division.
print("Result:", result)
except ZeroDivisionError:
# Handle the exception if a division by zero is attempted.
print("The division by zero operation is not allowed.")

# 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.

# Define a function named get_numeric_input that takes a prompt as a parameter.


def get_numeric_input(prompt):
# Use a while loop to repeatedly prompt the user until a valid numeric input is provided.
while True:
try:
# Attempt to get a numeric input (float) from the user and store it in the 'value' variable.
value = float(input(prompt))
# Return the numeric value.
return value
except ValueError:
# Handle the exception if the user's input is not a valid number.
print("Error: Invalid input. Please Input a valid number.")

# 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.

# Define a function named 'test_list_operation' that takes 'nums' as a parameter.


def test_list_operation(nums):
try:
# Attempt to access the 'length' attribute of the 'nums' list and assign it to 'r'.
r = len(nums) # Trying to access the length attribute
# Print the length of the list 'nums'.
print("Length of the list:", r)
except AttributeError:
# Handle the exception if an AttributeError occurs when attempting to access the 'length'
attribute.
print("Error: The list does not have a 'length' attribute.")

# Create a list 'nums' containing integer values.


nums = [1, 2, 3, 4, 5]
# Call the 'test_list_operation' function with the 'nums' list as a parameter to check for the
'length' attribute.
test_list_operation(nums)

17.Write a Python program that opens a file and handles a FileNotFoundError exception if the
file does not exist.

# Define a function named open_file that takes a filename as a parameter.


def open_file(filename):
try:
# Attempt to open the specified file in read mode ('r').
file = open(filename, 'r')
# Read the contents of the file and store them in the 'contents' variable.
contents = file.read()
# Print a message to indicate that the file contents will be displayed.
print("File contents:")
# Print the contents of the file.
print(contents)
# Close the file to release system resources.
file.close()
except FileNotFoundError:
# Handle the exception if the specified file is not found.
print("Error: File not found.")

# 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]]

# Importing the NumPy library with an alias 'np'


import numpy as np

# Creating a NumPy array 'nums' with shape (5, 6) filled with zeros of integer type
nums = np.zeros(shape=(5, 6), dtype='int')

# Printing a message indicating the original array


print("Original array:")
print(nums)

# 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.

a) Current date and time


b) Current year
c) Month of year
d) Week number of the year
e) Weekday of the week
f) Day of year
g) Day of the month
h) Day of week

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

from datetime import *


d = strptime('Jul 1 2014 2:43PM', '%b %d %Y %I:%M%p')
print(d)

4. Write a Python program to print yesterday, today, tomorrow with date.


Yesterday : 2017-05-05
Today : 2017-05-06
Tomorrow : 2017-05-07

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')))

6. Write a Python function to sum all the numbers in a list.


Sample List : (8, 2, 3, 0, 7)
Expected Output : 20

def sum(numbers):
# Initialize a variable 'total' to store the sum of numbers, starting at 0
total = 0

# Iterate through each element 'x' in the 'numbers' list


for x in numbers:
# Add the current element 'x' to the 'total'
total += x

# Return the final sum stored in the 'total' variable


return total
# Print the result of calling the 'sum' function with a tuple of numbers (8, 2, 3, 0, 7)
print(sum((8, 2, 3, 0, 7)))

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 = []

# Iterate through each element 'a' in the input list 'l'


for a in l:
# Check if the element 'a' is not already present in the list 'x'
if a not in x:
# If 'a' is not in 'x', add it to the list 'x'
x.append(a)

# Return the list 'x' containing unique elements


return 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]))

You might also like