You are on page 1of 17

PROGRAMMING IN PYTHON LAB FILE

LAB NO. 01

A. Installation of Python.
 Go to the official Python website: python.org.
 Click on the "Downloads" tab.
 Choose the latest version of Python that is compatible with your Windows
version.
 Download the installer (executable) for Windows.
 Once the installer is downloaded, double-click on it to run.
 You may see a checkbox that says "Add Python to PATH". Make sure to check
this box as it will allow you to use Python from the command line.
 Follow the instructions in the Python installer.
 You can choose the default settings for most options unless you have specific
preferences.
 After the installation is complete, you can verify if Python is installed correctly
by opening the command prompt:
 Press Win + R to open the "Run" dialog.
 Type cmd and press Enter to open the command prompt.
 In the command prompt, type python --version and press Enter.
 If Python is installed correctly, it will display the version number.
 You can use any text editor or integrated development environment (IDE) to
write Python code. Some popular choices include Visual Studio Code,
PyCharm.
B. Write a program to print different types of data types with multiline and single
line comments.

# This is a single-line comment


print(" Samkit Jain")
print("Data Types Example:")
# Integer
int_var = 42
print("Integer:", integer_var)

# Float
float_var = 3.14
print("Float:", float_var)
# String
string_var = “hello, world!”
print(“string:”, string_var)
# Boolean
boolean_var = True
print("Boolean:", boolean_var)

# List
list_var = [1, 2, 3, 4]
print("List:", list_var)

# Tuple
tuple_var = (5, 6, 7, 8)
print("Tuple:", tuple_var)

# Dictionary
dict_var = {'name': 'John', 'age': 25}
print("Dictionary:", dict_var)
"""
This is a multiline comment.
You can use triple-quotes for multiline comments.
"""
# Set
set_var = {1, 2, 3, 4, 5}
print("Set:", set_var)
C. Write a program to print the largest number of three numbers using if else and
elif.
print("Samkit Jain")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
print("The largest number is:", largest)
D. Write a program to print number 1-10 using a while loop.

print("samkit jain")
Number = 1
while Number <= 10:
print(Number)
Number += 1

E. Write a program to check prime numbers between 1 -70 using a for loop.
print("samkit jain")
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
print("Prime numbers between 1 and 70:")
for number in range(1, 70):
if is_prime(number):
print(number)
LAB NO. 02
A. Write a program to concatenate two string using + operator.
print("samkit jain")
string1 = "Hello, "
string2 = "World!"
result = string1 + string2
print("Concatenated String:", result)

B. Write a program to reverse a string using slicing.


print("samkit jain")
original_string = "Hello, World!"
reversed_string = original_string[::-1]
print("Original String:", original_string)
print("Reversed String:", reversed_string)

C. Write a program to perform different methods of string like len(atleast 5).

print("samkit jain")
input_string = "Python Programming"
print("Original String:", input_string)

length_of_string = len(input_string)
print("Length of the String:", length_of_string)

uppercase_string = input_string.upper()
print("Uppercase String:", uppercase_string)

lowercase_string = input_string.lower()
print("Lowercase String:", lowercase_string)

count_e = input_string.count('e')
print("Occurrences of 'e':", count_e)

index_of_program = input_string.find("Program")
print("Index of Program:", index_of_program)

replaced_string = input_string.replace("Python", "Java")


print("String after replacement:", replaced_string)

split_string = input_string.split(" ")


print("String after spliting:", split_string)

capitalize_string = input_string.capitalize()
print("String after capitalizing:", capitalize_string)

D. Write a program to traverse all the characters of a string using a for loop.
print("samkit jain")
input_string = "Hello, World!"
print("Traversing characters of the string:")
for char in input_string:
print(char)

E. Write a program to print abecederian series.

print("samkit jain")
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew"]
print("Abecedarian Series:")
for word in words:
print(word)

F. Write a program to check whether a string is present in another string or not.


print("samkit jain")
def is_substring_present(main_string, substring_to_check):
return substring_to_check in main_string

main_string = input("Enter the main string: ")


substring_to_check = input("Enter the substring to check: ")
if is_substring_present(main_string, substring_to_check):
print(f"'{substring_to_check}' is present in the string.")

else:
print(f"'{substring_to_check}' is not present in the string.")

G. Write a program to print


A
AB
ABC
ABCD

print("samkit jain")
def left_side_pattern(chars):
for i in range(1, len(chars) + 1):
print(chars[:i])

left_side_pattern("ABCD")

LAB NO. 03

INTRODUCTION TO LIST, PROPERTIES OF LIST


A. Write a program to create a list with different data types.

print("samkit jain")
mixed_list = [1, 'two', 3.0, True, [4, 5]]
print("Mixed List:", mixed_list)
first_element = mixed_list[0]
second_element = mixed_list[1]
third_element = mixed_list[2]
fourth_element = mixed_list[3]
fifth_element = mixed_list[4]
print("First Element:", first_element)
print("Second Element:", second_element)
print("Third Element:", third_element)
print("Fourth Element:", fourth_element)
print("Fifth Element:", fifth_element)

B. Write a progarm to take user input in a list from eval().

print("samkit jain")
max_inputs = 5
user_list = []

for _ in range(max_inputs):
user_input = input("Enter an element (or type 'done' to finish): ")
if user_input.lower() == 'done':
break
if eval(f'isinstance({user_input}, (int, float, str, list, tuple, dict))'):
user_list.append(eval(user_input))
else:
print("Error: Please enter a valid input (int, float, str, list, tuple, dict).")

print("User Input List:", user_list)

C. Write a program to append five elements in a list by using for loop and
append().
print("samkit jain")
my_list = [1, 2, 3]
print("Existing list:", my_list)
for _ in range(5):
element = input("Enter an element to append to the list: ")
my_list.append(element)
print("Final List:", my_list)

D. write a program to sort a list in both ascending and descending order.

print("samkit jain")
my_list = [5, 2, 8, 1, 3]
print("List is:", my_list)
my_list.sort()
print("Ascending Order:", my_list)
descending_order = sorted(my_list, reverse=True)
print("Descending Order:", descending_order)

E. Write a program to find the occurrences of an element in the list.

print("samkit jain")
my_list = [1, 2, 3, 2, 4, 2, 5]
print("List is:", my_list)
element_to_count = 2
occurrences = my_list.count(element_to_count)
print(f"The element {element_to_count} occurs {occurrences} times in the list.")

LAB NO. 04

A. Write a program to find the index of an element in the list.

print("samkit jain")
my_list = [10, 20, 30, 40, 50]
print("List is:", my_list)

element_to_find = 30

if element_to_find in my_list:
# Using the index() method to find the index of the element
index = my_list.index(element_to_find)
print(f"The index of {element_to_find} in the list is {index}.")
else:
print(f"{element_to_find} is not present in the list.")

B. Write a program to swap the first and last element of a list.

print("samkit jain")
my_list = [1, 2, 3, 4, 5]
print("List is:", my_list)
if len(my_list) >= 2:
my_list[0], my_list[-1] = my_list[-1], my_list[0]

print("List after swapping the first and last elements:", my_list)

C. Write a program to swap two number in list with given position.


print("samkit jain")

def swap_elements(my_list, position1, position2):


if 0 <= position1 < len(my_list) and 0 <= position2 < len(my_list):
my_list[position1], my_list[position2] = my_list[position2], my_list[position1]
print(f"List after swapping positions {position1} and {position2}:", my_list)
else:
print("Invalid positions.")

user_list = input("Enter elements of the list separated by spaces: ").split()


print("List is:", user_list)
user_list = [int(element) for element in user_list]

position_to_swap1 = int(input("Enter the first position to swap: "))


position_to_swap2 = int(input("Enter the second position to swap: "))

swap_elements(user_list, position_to_swap1, position_to_swap2)

D. Write a program to check whether a number is in the list or not sublist even and
odd.
print("samkit jain")

def check_and_separate(my_list, number):


if number in my_list:
print(f"{number} is present in the list.")
number_type = "even" if number % 2 == 0 else "odd"
print(f"{number} is {number_type}.")
even_numbers = [num for num in my_list if num % 2 == 0]
odd_numbers = [num for num in my_list if num % 2 != 0]
print("Even numbers in the list:", even_numbers)
print("Odd numbers in the list:", odd_numbers)
else:
print(f"{number} is not present in the list.")

user_list = input("Enter elements of the list separated by spaces: ").split()


user_list = [int(element) for element in user_list]
number_to_check = int(input("Enter a number to check in the list: "))

check_and_separate(user_list, number_to_check)

E. Write a program to demonstrate the difference between remove and pop in a


list.
print("samkit jain")

def demonstrate_remove_and_pop(my_list):
print("Original List:", my_list)
element_to_remove = int(input("Enter an element to remove using remove(): "))
if element_to_remove in my_list:
my_list.remove(element_to_remove)
print(f"List after removing {element_to_remove} using remove(): {my_list}")
else:
print(f"{element_to_remove} is not present in the list.")

index_to_pop = int(input("Enter an index to pop using pop(): "))


if 0 <= index_to_pop < len(my_list):
popped_element = my_list.pop(index_to_pop)
print(f"List after popping element at index {index_to_pop} using pop(): {my_list}")
print(f"Popped element: {popped_element}")
else:
print(f"Index {index_to_pop} is out of range. Cannot pop from the list.")

user_list = input("Enter elements of the list separated by spaces: ").split()


user_list = [int(element) for element in user_list]
demonstrate_remove_and_pop(user_list)

F. Write a program to insert an element into a list at a position given by the user.
print("samkit jain")

def insert_element_at_position(my_list, element, position):


if 0 <= position <= len(my_list):
my_list.insert(position, element)
print(f"List after inserting {element} at position {position}: {my_list}")
else:
print(f"Invalid position. Please enter a position between 0 and {len(my_list)}.")

user_list = input("Enter elements of the list separated by spaces: ").split()


user_list = [int(element) for element in user_list]
element_to_insert = int(input("Enter an element to insert: ")) # corrected this line
position_to_insert = int(input(f"Enter a position to insert {element_to_insert} at: "))
insert_element_at_position(user_list, element_to_insert, position_to_insert)

You might also like