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

Python Record

The document outlines various Python programming experiments, including looping statements, conditional statements, list functions, tuple functions, dictionary functions, mean and variance calculations, prime number checking, key searching in dictionaries, sum of natural numbers, and string operations. Each experiment includes an aim, algorithm, code, output, and a result indicating successful execution. The programs demonstrate fundamental programming concepts and operations in Python.

Uploaded by

rithuponnusaami
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)
2 views16 pages

Python Record

The document outlines various Python programming experiments, including looping statements, conditional statements, list functions, tuple functions, dictionary functions, mean and variance calculations, prime number checking, key searching in dictionaries, sum of natural numbers, and string operations. Each experiment includes an aim, algorithm, code, output, and a result indicating successful execution. The programs demonstrate fundamental programming concepts and operations in Python.

Uploaded by

rithuponnusaami
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

[Link] 1.

LOOPING STATEMENTS
AIM:
To write a python program to implement looping statements.
ALGORITHM:
Step 1: Declare a variable ‘n’ and assign a value to it.
Step 2: Declare a variable ‘sum’ and initialize it to 0.
Step 3: Declare a variable ‘i’ and initialize it to 1.
Step 4: Using ‘while’ loop, when i<=n, then sum=sum+i. Go to step 5. Else go
to step 6.
Step 5: Increase i=i+1
Step 6: Display the sum.
Step 7: Stop
CODE:
# Program to illustrate a loop with the condition at the top
# Try different numbers
n = 10
# Uncomment to get user input
#n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is",sum)
OUTPUT:
LOOPING STATEMENTS
The sum is 5
RESULT:
Thus the above program has been executed successfully.
[Link] 2. CONDITIONAL STATEMENTS
AIM:
To write a python program to implement conditional statements.
ALGORITHM:
Step 1: Declare a variable “age” and get input for it from the user.
Step 2: Declare a variable “citizenship” and ask if they are, or not.
Step 3: Using “if” condition, if age>=18 and citizenship=“yes”, got to step 5,
else go to step 4.
Step 4: Display “Not eligible to vote”
Step 5: Display “Eligible to vote”.
Step 6: Stop.
CODE:
# Check if a person is eligible to vote
age = int(input("Enter your age: "))
citizenship = input("Are you a citizen? (yes/no): ").lower()
if age >= 18 and citizenship == "yes":
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
OUTPUT:
CONDITIONAL STATEMENTS
Enter your age: 22
Are you a citizen? (yes/no): yes
You are eligible to vote.
RESULT:
Thus the above program has been executed successfully.
[Link] 3. LIST FUNCTIONS
AIM:
To write a python program to demonstrate list functions.
ALGORITHM:
Step 1: Start
Step 2: Define a function “add_number”, with variables “a” and “b”. Assign
values to them.
Step 3: Declare a variable “sum” and assign the sum value of “a” and “b”.
Step 4: Change the values of “a” and “b”.
Step 5: Display the sums for different values of “a” and “b”
Step 6: Stop
CODE:
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers()
OUTPUT:
LIST FUNCTIONS
Sum: 5
Sum: 10
Sum: 15
RESULT:
Thus the above program has been executed successfully.
[Link] 4. TUPLE FUNCTIONS
AIM:
To write a python program to demonstrate tuple functions.
ALGORITHM:
Step 1: Start
Step 2: Declare a variable “fruits” and assign values to it.
Step 3: Declare variables “first_fruit” and “second_fruit” and assign values
from “fruits”.
Step 4: Display the values of “first_fruit” and “second_fruit”.
Step 5: Stop.
CODE:
# Creating a tuple
fruits = ('apple', 'banana', 'orange', 'grape')
# Accessing elements using indexing
first_fruit = fruits[0]
second_fruit = fruits[1]
print("First fruit:", first_fruit)
print("Second fruit:", second_fruit)
OUTPUT:
TUPLE FUNCTIONS
First fruit: apple
Second fruit: banana
RESULT:
Thus the above program has been executed successfully.
[Link] 5. DICTIONARY FUNCTIONS
AIM:
To write a python program to demonstrate Dictionary Functions.
ALGORITHM:
Step 1: Start
Step 2: Create a dictionary
Step 3: Do the following operations: displaying elements, calculating total,
finding maximum value.
Step 4: Display the results of step 3.
Step 5: Stop.
CODE:
# Creating a dictionary
fruit_prices = {'apple': 1.0, 'banana': 0.75, 'orange': 1.25}
# Displaying dictionary elements
for fruit, price in fruit_prices.items():
print(f"{[Link]()}: ${price:.2f}")
# User's shopping list
shopping_list = {'apple': 3, 'banana': 2, 'orange': 1}
# Calculating total cost
total_cost = sum(item_prices[item] * quantity for item, quantity in
shopping_list.items())
print("Total cost: ${:.2f}".format(total_cost))
#Finding Maximum Value in a Dictionary
sales = {'January': 1200, 'February': 1500, 'March': 1100, 'April': 1800}
# Finding the month with the maximum sales
max_month = max(sales, key=[Link])
max_sales = sales[max_month]
print("Maximum sales in {}: ${}".format(max_month, max_sales))
OUTPUT:
DICTIONARY FUNCTIONS
Apple: $1.00
Banana: $0.75
Orange: $1.25
Total cost: $6.25
Maximum sales in April: $1800
RESULT:
Thus the above program has been executed successfully.
[Link] 6. MEAN AND VARIANCE
AIM:
To write a python program to find the mean and variance from a list of numbers.
ALGORITHM:
Step 1: Start the program.
Step 2: import the numpy library as np.
Step 3: Define a print statement indicating that we're going to calculate the
mean and variance of numbers.
Step 4: Create an array using numpy's arange() function, generating numbers
from 0 to 9.
Step 5: Print the original array.
Step 6: Calculate the mean of the array using [Link]() function and store the
result in variable r1.
Step 7: Print the mean.
Step 8: Calculate the standard deviation of the array using [Link]() function and
store the result in variable r2.
Step 9: Print the standard deviation.
Step 10: Calculate the variance of the array using [Link]() function and store the
result in variable r3.
Step 11: Print the variance.
Step 12: End the program
CODE:
import numpy as np
# Original array
print("Mean and Variance of Numbers")
array = [Link](10)
print(array)
r1 = [Link](array)
print("\nMean: ", r1)
r2 = [Link](array)
print("\nstd: ", r2)
r3 = [Link](array)
print("\nvariance: ", r3)
OUTPUT:
MEAN AND VARIANCE OF NUMBERS 2
[0 1 2 3 4 5 6 7 8 9]
Mean: 4.5
std: 2.8722813232690143
variance: 8.25
RESULT:
Thus the above program has been executed successfully.
[Link] 7. CHECKING PRIME NUMBER
AIM:
To write a python program to check if a number is prime or not.
ALGORITHM:
Step 1: Start the program.
Step 2: Define a function named 'check_prime' that takes a single argument
'num':
a. If 'num' is less than or equal to 1, return False (since numbers less than or
equal to 1 are not prime).
b. Iterate over 'i' in the range from 2 to the square root of 'num' (inclusive):
i. If 'num' is divisible evenly by 'i', return False (since 'num' is not prime).
c. If no divisors are found in the loop, return True (indicating 'num' is prime).
Step 3: Prompt the user to enter a number and store the input in the variable
'number'.
Step 4: Check if the entered number is prime using the 'check_prime' function:
a. If the function returns True, print that the number is a prime number.
b. If the function returns False, print that the number is not a prime number.
Step 5: End the program.
CODE:
def check_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
number = int(input("Enter a number: "))
if check_prime(number):
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")
OUTPUT:
CHECKING PRIME NUMBER
Enter a number: 5
5 is a prime number.
CHECKING PRIME NUMBER
Enter a number: 10
10 is not a prime number.
RESULT:
Thus the above program has been executed successfully.
[Link] 8. SEARCHING KEY IN DICTIONARY
AIM:
To write a python program to search for a key in the dictionary.
ALGORITHM:
Step 1: Start the program.
Step 2: Check if Key Exists in Dictionary
Step 3: Initialize a dictionary named 'ages' with key-value pairs representing
names and ages.
Step 4: Define a variable 'some_key' and assign it a value 'Matt', which is one of
the keys in the 'ages' dictionary.
Step 5: Check if 'some_key' exists in the 'ages' dictionary:
a. If 'some_key' exists in the dictionary, print "Key exists".
b. If 'some_key' does not exist in the dictionary, print "Key doesn't exist".
Step 6: End the program
CODE:
ages = {'Matt': 30, 'Katie': 29, 'Nick': 31, 'Jack': 43, 'Alison': 32, 'Kevin': 38}
some_key = 'Matt'
if some_key in ages:
print(“Key exists”)
else:
print(“Key doesn't exist”)
# Returns: Key exists
OUTPUT:
SEARCH FOR A KEY IN THE DICTIONARY
Key exists
RESULT:
Thus the above program has been executed successfully.
[Link] 9. SUM OF NATURAL NUMBERS
AIM:
To write a python program using function to find the sum of first ‘n’ natural
numbers.
ALGORITHM:
Step 1: Start the program.
Step 2: Read input from the user, prompting them to enter a natural number, and
store it in variable 'N'.
Step 3: Initialize a boolean variable 'validation' to True, assuming that the input
is valid initially.
Step 4: Check if the input 'N' is numeric:
a. If 'N' is not numeric, set 'validation' to False.
b. If 'N' is numeric, proceed to the next step.
Step 5: If 'N' is numeric, convert it to an integer and store it back in variable 'N'.
Step 6: Check if 'N' is less than 1:
a. If 'N' is less than 1, set 'validation' to False, as it is not a natural number.
b. If 'N' is greater than or equal to 1, continue to the next step.
Step 7: If 'validation' is True after the above checks, calculate the sum of natural
numbers up to 'N':
a. Use the formula for the sum of the first 'N' natural numbers: (N * (N + 1)) / 2.
b. Convert the result to an integer using the int() function and store it in variable
'answer'.
Step 8: Print the value of 'answer', which represents the sum of natural numbers
up to 'N'.
Step 9: If 'validation' is False after the checks, print a message indicating that
the input is not a natural number.
Step 10: End the program.
CODE:
# Read the input
N = input("Enter a natural number: ")
# Assume everything is fine
validation = True
# If N is not numeric, validation fails
if not([Link]()):
validation = False
else:
N = int(N)
#if n is less than 1, it is not a natural number
if (N<1):
validation = False
if validation:
answer = (N*(N+1))/2
answer = int(answer)
print(answer)
else:
print('Input is not a natural number. Try again.')
OUTPUT:
SUM OF NATURAL NUMBERS
Enter a natural number: 5
15
RESULT:
Thus the above program has been executed successfully.
[Link] 10. STRING OPERATIONS
AIM:
To write a python program to perform string operations.
ALGORITHM:
Step 1: Start the program
Step 2: Print a message indicating the start of string functions and operations.
Step 3: Prompt the user to enter two strings: 'String1' (stored in variable 'a') and
'String2' (stored in variable 'b').
Step 4: Concatenate 'String1' and 'String2' with a space in between, store the
result in variable 'c'.
Step 5: Print the concatenated string.
Step 6: Calculate and print the length of each input string using the len()
function.
Step 7: Split 'String1' based on periods ('.') using the split('.') function and print
the result.
Step 8: Convert both strings to uppercase using the upper() function and print
the results.
Step 9: Convert both strings to lowercase using the lower() function and print
the results.
Step 10: Print the memory address (id) of 'String1' using the id() function.
Step 11: Extract a substring from 'String1' from index 2 to index 8 (exclusive)
and print it.
Step 12: Remove leading and trailing whitespaces from both strings using the
strip() function and print the results.
Step 13: Replace occurrences of character 'D' with character 'K' in 'String1'
using the replace() function and print the modified string.
Step 14: End of the program.
CODE:
print("String Functions and Operations")
a=input("Enter the String1:")
b=input("Enter the String2: ")
c=a+" "+b
print("Concatenation of Two Strings: ",c)
print("The length of the String is : ",len(a),len(b))
print("Spliting the String: ",[Link]('.'))
print("Converting String into Upper case:",[Link](),[Link]())
print("Converting String into Lower case:",[Link](),[Link]())
print("The id of String:",id(a))
print("String Slice: ",a[2:9])
print("Modified String: ",[Link](),[Link]())
print("Replace String:",[Link]("D","K"))
OUTPUT:
STRING FUNCTIONS AND OPERATIONS
Enter the String1:Python
Enter the String2: Programming
Concatenation of Two Strings: Python Programming
The length of the String is : 6 11
Spliting the String: ['Python']
Converting String into Upper case: PYTHON PROGRAMMING
Converting String into Lower case: python programming
The id of String: 135247958090224
String Slice: thon
Modified String: Python Programming
Replace String: Python
RESULT:
Thus the above program has been executed successfully.

You might also like