0% found this document useful (0 votes)
8 views4 pages

Python Lab Programs

The document contains several Python programs demonstrating basic programming concepts such as arithmetic operations, checking even or odd numbers, generating Fibonacci series, counting vowels and consonants in a string, managing student details with a dictionary, and using loop control statements like break, continue, and pass. Each section includes user input and displays results accordingly. The examples illustrate fundamental programming techniques and data handling in Python.

Uploaded by

velan7782
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)
8 views4 pages

Python Lab Programs

The document contains several Python programs demonstrating basic programming concepts such as arithmetic operations, checking even or odd numbers, generating Fibonacci series, counting vowels and consonants in a string, managing student details with a dictionary, and using loop control statements like break, continue, and pass. Each section includes user input and displays results accordingly. The examples illustrate fundamental programming techniques and data handling in Python.

Uploaded by

velan7782
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

In [1]: #1.

Write a Python program to declare variables, perform arithmetic operations, and di


# Take input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Perform arithmetic operations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulus = num1 % num2
exponent = num1 ** num2
floor_division = num1 // num2
# Display results
print("\n----- Results -----")
print("Number 1:", num1)
print("Number 2:", num2)
print("--------------------------")
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Modulus:", modulus)
print("Exponent:", exponent)
print("Floor Division:", floor_division)

----- Results -----


Number 1: 2.5
Number 2: 2.5
--------------------------
Addition: 5.0
Subtraction: 0.0
Multiplication: 6.25
Division: 1.0
Modulus: 0.0
Exponent: 9.882117688026186
Floor Division: 1.0

In [3]: #2. Create a program to check if a number is even or odd using if-else.
# Take input from the user
num = int(input("Enter a number: "))
# Check if the number is even or odd
if num % 2 == 0:
print(num, "is an Even number.")
else:
print(num, "is an Odd number.")

3 is an Odd number.

In [4]: #3. Write a Python program to print the first n Fibonacci numbers using a for loop.
# Take input from the user
n = int(input("Enter the number of terms: "))
# Initialize first two Fibonacci numbers
a, b = 0, 1
print("\nFibonacci Series:")
# Use a for loop to generate Fibonacci sequence
for i in range(n):
print(a, end=" ")
# Update values of a and b
a, b = b, a + b

Fibonacci Series:
0 1 1 2 3 5 8 13 21 34

In [5]: #4. Implement a program that accepts a string and counts the number of vowels and cons
# Take input from the user
text = input("Enter a string: ")

# Initialize counters
vowels = 0
consonants = 0

# Define vowel characters


vowel_chars = "aeiouAEIOU"

# Loop through each character in the string


for char in text:
if [Link](): # Check if the character is a letter
if char in vowel_chars:
vowels += 1
else:
consonants += 1

# Display the result


print("\n----- Result -----")
print("Input String:", text)
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)

----- Result -----


Input String: The Twilight
Number of vowels: 3
Number of consonants: 8

In [6]: # Create an empty dictionary to store student details


students = {}

# Get the number of students


n = int(input("Enter number of students: "))

# Input details for each student


for i in range(n):
print(f"\nEnter details for Student {i + 1}:")
roll_no = input("Enter Roll Number: ")
name = input("Enter Name: ")
course = input("Enter Course: ")
marks = float(input("Enter Marks: "))

# Store details in dictionary


students[roll_no] = {
"Name": name,
"Course": course,
"Marks": marks
}

# Retrieve details based on roll number


print("\n----- Retrieve Student Details -----")

while True:
search_roll = input("\nEnter Roll Number to search (or 'exit' to stop): ")

if search_roll.lower() == "exit":
print("Exiting search.")
break

# Check if roll number exists


if search_roll in students:
print("\nStudent Details Found:")
print("Roll Number:", search_roll)
print("Name:", students[search_roll]["Name"])
print("Course:", students[search_roll]["Course"])
print("Marks:", students[search_roll]["Marks"])
else:
print("\nNo student found with Roll Number:", search_roll)

Enter details for Student 1:


Enter details for Student 2:
----- Retrieve Student Details -----
Student Details Found:
Roll Number: 1
Name: itachi
Course: psychology
Marks: 100.0
Exiting search.

In [7]: #6. Demonstrate the use of break, continue, and pass in loops.
print("=== Demonstration of 'break' statement ===")
for i in range(1, 6):
if i == 4:
print("Break encountered at i =", i)
break # exits the loop when i == 4
print("Current value:", i)

print("\n=== Demonstration of 'continue' statement ===")


for i in range(1, 6):
if i == 3:
print("Continue encountered at i =", i)
continue # skips the rest of the code for i == 3
print("Current value:", i)

print("\n=== Demonstration of 'pass' statement ===")


for i in range(1, 6):
if i == 2:
pass # does nothing, acts as a placeholder
print("Pass executed at i =", i)
print("Current value:", i)

=== Demonstration of 'break' statement ===


Current value: 1
Current value: 2
Current value: 3
Break encountered at i = 4

=== Demonstration of 'continue' statement ===


Current value: 1
Current value: 2
Continue encountered at i = 3
Current value: 4
Current value: 5

=== Demonstration of 'pass' statement ===


Current value: 1
Pass executed at i = 2
Current value: 2
Current value: 3
Current value: 4
Current value: 5

In [ ]:

Common questions

Powered by AI

To store and retrieve student details efficiently in Python, use a dictionary with roll numbers as keys and another dictionary as values to contain details like name, course, and marks. This structure supports efficient retrieval with operations to input data for each student and a loop to search by roll number .

Input validation in Python scripts is crucial for ensuring that only expected input types are processed, which prevents errors and allows for robust handling of user interaction. This can involve type checking, value range checks, and exception handling for invalid input formats .

Python can perform arithmetic operations on two user-input numbers by first reading the numbers using input() and converting them to float. The operations include addition, subtraction, multiplication, division, modulus, exponentiation, and floor division. The results are then printed. For example, if both numbers are 2.5, performing these operations results in addition: 5.0, subtraction: 0.0, multiplication: 6.25, division: 1.0, modulus: 0.0, exponent: 9.882117688026186, and floor division: 1.0 .

To determine if a number is even or odd in Python, one can use the modulus operator (%) to check the remainder of the number divided by 2. If the remainder is 0, the number is even; otherwise, it is odd .

In Python, dynamic handling of user input within loops can involve an interactive loop where user inputs are checked against conditions to perform actions like storing data or executing specific functions. This involves continuous input checks with mechanisms such as dictionaries for data storage and retrieval, as demonstrated in the student detail program .

The Fibonacci sequence is generated using a for loop in Python by initializing the first two numbers as 0 and 1, then iterating through a range to update these numbers to the sum of the preceding two numbers for n terms. The first 10 numbers of the sequence starting from 0 are 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34 .

'break' immediately exits the loop when a specified condition is met, 'continue' skips the rest of the code inside the loop for the current iteration, and 'pass' acts as a placeholder, doing nothing when executed. Each is used to control loop execution in different scenarios .

To count vowels and consonants in a string using Python, initialize counters for vowels and consonants, define a string of vowel characters, and loop through each character in the input string. If the character is alphabetic and in the vowel list, increase the vowel counter; otherwise, increase the consonant counter .

In Python, the modulus operation available through '%' is essential for determining properties like evenness or oddness of a number, which can influence program flow through conditional statements. It helps simplify logic controls, particularly in loops or decision-making structures .

To handle large numerical operations in Python, select data types like float or use libraries designed for numerical computations to maintain accuracy. Structure operations efficiently, and handle exceptions like division by zero with appropriate error handling strategies .

You might also like