0% found this document useful (0 votes)
4 views15 pages

Python Programs for Beginners

The document provides a series of Python programming examples, each demonstrating different functionalities such as displaying personal details, performing arithmetic operations, calculating BMI, and implementing a menu-driven calculator. Each example includes the aim, source code, result, and output of the program. The examples cover various topics including string manipulation, list and tuple functions, random number generation, and pattern matching.
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)
4 views15 pages

Python Programs for Beginners

The document provides a series of Python programming examples, each demonstrating different functionalities such as displaying personal details, performing arithmetic operations, calculating BMI, and implementing a menu-driven calculator. Each example includes the aim, source code, result, and output of the program. The examples cover various topics including string manipulation, list and tuple functions, random number generation, and pattern matching.
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

Ex: no: 1

AIM:

To display your personal details using print statement

Source code:

print(“MY PERSONAL DETAILS”)

print(“*”*10)

print(“Vinothini.S”)

print(“Im 32 years old”)

print(“Im staying in Trichy”)

print(“My hobby is to hearing music”)

Result:

Thus we successfully completed Python program.

OUTPUT:

Vinothini.S

Im 32 years old

Im staying in Trichy

My hobby is to hearing music

Ex: no: 2

AIM:

To add 3 numbers using a Python program

Source code:

a,b,c=10,20,30

print(“Addition of three numbers = “,a+b+c)

Result:

Thus we successfully completed a Python program for adding 3 numbers.

OUTPUT:

Addition of three numbers = 60

Ex: no: 3

AIM:

To calculate area of circle using user defined input

Source code:

r=int(input(“Enter the radius”))

ar=3.14*r*r

print(“Area of a circle =”,ar)


Result:

Thus we successfully completed a Python program

OUTPUT:

Enter the radius5

Area of a circle= 78.5

Ex: no: 4

AIM:

To calculate area of circle using user defined input

Source code:

# Program to calculate BMI

weight = float(input("Enter weight in kg: "))

height = float(input("Enter height in meters: "))

bmi = weight / (height * height)

print("Your BMI is:", round(bmi, 2))

if bmi < 18.5:

print("Category: Underweight")

elif bmi < 25:

print("Category: Normal weight")

elif bmi < 30:

print("Category: Overweight")

else:

print("Category: Obese")

Result:

Thus we successfully completed a Python program on BMI Calculator

OUTPUT:

Enter weight in kg: 75

Enter height in meters: 1.6

Your BMI is: 29.3

Category: Overweight

Ex: no: 5

AIM:

To write a Python program on math module

Source code:

# Program demonstrating functions of math module


import math

num = int(input("Enter a number "))

print("Number:", num)

# Square root

print("Square root:", [Link](num))

# Power

print("Power (5^2):", [Link](5, 2))

x = float(input("Enter a signed float value "))

# Absolute value

print("Absolute value:", [Link](x))

y = float(input("Enter a float value "))

# Ceiling and Floor

print("Ceiling value:", [Link](y))

print("Floor value:", [Link](y))

# Factorial

print("Factorial of 5:", [Link](5))

# Trigonometric functions (convert degree to radian)

angle = float(input("Enter a angle value "))

radian = [Link](angle)

print("Sin 30°:", [Link](radian))

print("Cos 30°:", [Link](radian))

print("Tan 30°:", [Link](radian))

# Constants

print("Value of pi:", [Link])

print("Value of e:", math.e)

Result:

Thus we successfully completed a Python program on Math module

OUTPUT:

Enter a number 7

Number: 7

Square root: 2.6457513110645907

Power (5^2): 25.0

Enter a signed float value -8


Absolute value: 8.0

Enter a float value 5.6

Ceiling value: 6

Floor value: 5

Factorial of 5: 120

Enter a angle value 85

Sin 30°: 0.9961946980917455

Cos 30°: 0.08715574274765814

Tan 30°: 11.430052302761348

Value of pi: 3.141592653589793

Value of e: 2.718281828459045

Ex: no: 6

AIM:

To write a Python program on random module.

Source code:

# Program demonstrating random module functions

import random

# random() → generates a float between 0 and 1

print("Random float:", [Link]())

# randint(a, b) → random integer between a and b

print("Random integer (1 to 10):", [Link](1, 10))

# randrange(start, stop, step)

print("Random number from range(1, 20, 2): ", [Link](1, 20, 2))

# choice() → random element from a list

colors = ["Red", "Green", "Blue", "Yellow"]

print("Random color:", [Link](colors))

# shuffle() → shuffle list elements

numbers = [1, 2, 3,4, 4, 5]

[Link](numbers)

print("Shuffled list:", numbers)

# uniform(a, b) → random float between a and b

print("Random float between 5 and 10:", [Link](5, 10))

Result:

Thus we successfully completed a Python program on random module


OUTPUT:

Random float: 0.5247072697695836

Random integer (1 to 10): 4

Random number from range(1, 20, 2): 15

Random color: Blue

Shuffled list: [5, 4, 4, 1, 2, 3]

Random sample of 3 numbers: [5, 3, 4]

Random float between 5 and 10: 7.196154101754099

Ex: no: 7

AIM:

To write a Python program on statistics module

Source code:

import statistics

data = eval(input("Enter your data in form of list "))

print("Data:", data)

print("Mean:", [Link](data))

print("Median:", [Link](data))

print("Mode:", [Link](data))

Result:

Thus we successfully completed a Python program on statistics module

OUTPUT:

Enter your data in form of list [10,20,30,40,10,20,50,60,70,40,50,20]

Data: [10, 20, 30, 40, 10, 20, 50, 60, 70, 40, 50, 20]

Mean: 35

Median: 35.0

Mode: 20

Ex: no: 8

AIM:

To write a Number Guessing Game using for loop in Python

Source code:

import random

number = [Link](1, 10)

for i in range(1, 6): # 5 attempts

guess = int(input("Attempt " + str(i) + ": Guess a number between 1 and 10: "))
if guess == number:

print("Congratulations! You guessed the correct number.")

break

elif guess < number:

print("Too low!")

else:

print("Too high!")

else:

print("Sorry! You have used all attempts.")

print("The correct number was:", number)

Result:

Thus we completed a Number Guessing Game using a for loop in Python

OUTPUT:

Attempt 1: Guess a number between 1 and 10: 5

Too high!

Attempt 2: Guess a number between 1 and 10: 3

Too high!

Attempt 3: Guess a number between 1 and 10: 2

Congratulations! You guessed the correct number.

Ex: no: 9

AIM:

To develop a Python program that calculates the total bill for multiple food items selected from the Study
Break café menu using loops and conditional statements.

Source code:

print("Welcome to STUDY BREAK ☕🍔")

print("------ MENU ------")

print("1. Veg Burger - Rs.80")

print("2. French Fries - Rs.60")

print("3. Pizza Slice - Rs.120")

print("4. Cold Coffee - Rs.70")

print("5. Exit")

total = 0

while True:

choice = int(input("Enter your choice (1-5): "))


if choice == 5:

break

quantity = int(input("Enter quantity: "))

if choice == 1:

item = "Veg Burger"

price = 80

elif choice == 2:

item = "French Fries"

price = 60

elif choice == 3:

item = "Pizza Slice"

price = 120

elif choice == 4:

item = "Cold Coffee"

price = 70

else:

print("Invalid choice")

continue

cost = price * quantity

total += cost

print(item, "added | Cost = Rs.", cost)

print("------ STUDY BREAK BILL ------")

print("Total Amount to Pay: Rs.", total)

print("Thank you! Best of luck for your studies 📘✨")

Result:

Thus we completed a Number Guessing Game using a for loop in Python

OUTPUT:

The program successfully displays the Study Break café menu, calculates the total bill accurately, and prints
the final payable amount.

Ex: no: 10

AIM:

To develop a Python program for pattern matching.

Source code:
rows = int(input("Enter number of rows: "))

print("\inverted Triangle:")

for i in range(rows, 0, -1):

for j in range(i):

print("*", end=" ")

print() # New line

# String Pattern – Pyramid

rows = int(input("Enter number of rows: "))

for i in range(1, rows + 1):

for j in range(rows - i):

print(" ", end="") # spaces

for k in range(1, i + 1):

print(chr(64 + k), end=" ") # letters

print()

Result:

Thus we completed a pattern matching program using nested for loop

OUTPUT:

Enter number of rows: 5

Inverted Triangle:

*****

****

***

**

Enter number of rows: 4


Ex: no: 11

AIM:

To create a menu-driven calculator in Python using a loop to perform basic arithmetic operations.

Source code:

while True:

print("\n===== Simple Calculator =====")

print("1. Addition")

print("2. Subtraction")

print("3. Multiplication")

print("4. Division")

print("5. Exit")

choice = int(input("Enter your choice (1-5): "))

if choice == 5:

print("Thank you! Calculator closed.")

break

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

if choice == 1:

print("Result =", num1 + num2)

elif choice == 2:

print("Result =", num1 - num2)

elif choice == 3:

print("Result =", num1 * num2)

elif choice == 4:

if num2 != 0:

print("Result =", num1 / num2)

else:

print("Error: Division by zero not allowed")

else:

print("Invalid choice! Please select 1 to 5.")

Result:

Thus we completed a Python calculator successfully

OUTPUT:
===== Simple Calculator =====

1. Addition

2. Subtraction

3. Multiplication

4. Division

5. Exit

Enter your choice (1-5): 1

Enter first number: 26

Enter second number: 32

Result = 58.0

===== Simple Calculator =====

1. Addition

2. Subtraction

3. Multiplication

4. Division

5. Exit

Enter your choice (1-5): 5

Thank you! Calculator closed.

Ex: no: 12

AIM:

To write a Python program to perform various string manipulation operations using built-in string functions.

Source code:

s = input("Enter a string: ")

print("\nOriginal String:", s)

print("Length of string:", len(s))

print("Uppercase:", [Link]())

print("Lowercase:", [Link]())

print("Title Case:", [Link]())

print("Capitalized:", [Link]())

print("Find position of 'a':", [Link]('a'))

try:

print("Index position of 'a':", [Link]('a')) # Error if not found


except ValueError:

print("Index position of 'a': Not found")

print("Partition using space:", [Link](" "))

print("Count of 'a':", [Link]('a'))

print("Replace space with hyphen:", [Link](" ", "-"))

print("Starts with 'A'?", [Link]('A'))

print("Ends with 'z'?", [Link]('z'))

print("Is alphanumeric?", [Link]())

print("First 5 characters:", s[:5])

print("Last 5 characters:", s[-5:])

print("Split into words:", [Link]())

Result:

Thus we successfully completed to perform various string manipulation .


OUTPUT:

Enter a string: Class XI Practical File

Original String: Class XI Practical File

Length of string: 23

Uppercase: CLASS XI PRACTICAL FILE

Lowercase: class xi practical file

Title Case: Class Xi Practical File

Capitalized: Class xi practical file

Find position of 'a': 2

Index position of 'a': 2

Partition using space: ('Class', ' ', 'XI Practical File')

Count of 'a': 3

Replace space with hyphen: Class-XI-Practical-File

Starts with 'A'? False

Ends with 'z'? False

Is alphanumeric? False

First 5 characters: Class

Last 5 characters: File

Split into words: ['Class', 'XI', 'Practical', 'File']


Ex: no: 13

AIM:

To write a Python program to perform various list functions.

Source code:

lst = eval(input("Enter elements : "))

print("\nOriginal List:", lst)

[Link](10)

print("After append:", lst)

[Link](1, 5)

[Link](10)

print("After inserting and removing the element:", lst)

print("After pop:", [Link]())

print("Length of list:", len(lst))

[Link]()

print("Sorted list:", lst)

[Link]()

print("Reversed list:", lst)

print("Maximum value:", max(lst))

print("Minimum value:", min(lst))

print("Sum of elements:", sum(lst))

Result:

Thus, we completed to perform various list manipulations.


OUTPUT:

Enter elements : [45,65,32,14,74,85,94,20,25,27,63]

Original List: [45, 65, 32, 14, 74, 85, 94, 20, 25, 27, 63]

After append: [45, 65, 32, 14, 74, 85, 94, 20, 25, 27, 63, 10]

After inserting and removing the element: [45, 5, 65, 32, 14, 74, 85, 94, 20, 25, 27, 63]

After pop: 63

Length of list: 11

Sorted list: [5, 14, 20, 25, 27, 32, 45, 65, 74, 85, 94]

Reversed list: [94, 85, 74, 65, 45, 32, 27, 25, 20, 14, 5]

Maximum value: 94

Minimum value: 5

Sum of elements: 486


Ex: no: 14

AIM:

To write a Python program to perform various Tuple functions.

SOURCE CODE:

t = tuple(input("Enter elements separated by space: ").split())

print("\nOriginal Tuple:", t)

print("Length of tuple:", len(t))

print("First element:", t[0])

print("Last element:", t[-1])

print("Sliced tuple (1 to 3):", t[1:4])

print("Count of an ",t[0]," is ", [Link](t[0]))

print("Index of \"kiwi\" element:", [Link]('kiwi'))

print("Maximum element:", max(t))

print("Minimum element:", min(t))

print("Reversed tuple:", t[::-1])

t2 = ("Python", "AI")

print("Concatenated tuple:", t + t2)

Result:

Thus, we completed to perform various tuple manipulations.


OUTPUT:

Enter elements separated by space: apple mango kiwi 12345

Original Tuple: ('apple', 'mango', 'kiwi', '12345')

Length of tuple: 4

First element: apple

Last element: 12345

Sliced tuple (1 to 3): ('mango', 'kiwi', '12345')

Count of an apple is 1

Index of "kiwi" element: 2

Maximum element: mango

Minimum element: 12345

Reversed tuple: ('12345', 'kiwi', 'mango', 'apple')

Concatenated tuple: ('apple', 'mango', 'kiwi', '12345', 'Python', 'AI')


Ex: no: 15

AIM:

To write a Python program to perform various Dictionary functions.

SOURCE CODE:

marks = {}

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

for i in range(n):

name = input("Enter student name: ")

score = int(input("Enter marks: "))

marks[name] = score

print("\nOriginal Dictionary:", marks)

[Link]("Anita", 90)

print("After setdefault:", marks)

print("Keys:", [Link]())

print("Values:", [Link]())

print("Items:", [Link]())

print("Sorted keys:", sorted(marks))

print("Maximum marks:", max([Link]()))

print("Minimum marks:", min([Link]()))

print("Sum of marks:", sum([Link]()))

[Link]("Anita")

print("After pop('Anita'):", marks)

removed_item = [Link]()

print("After popitem:", marks)

print("Removed item:", removed_item)

if len(marks) > 0:

key_to_delete = list([Link]())[0]

del marks[key_to_delete]

print("After del:", marks)

[Link]()

print("After clear:", marks)

Result:

Thus, we completed to perform various dictionary manipulations.


OUTPUT:
Enter number of students: 4

Enter student name: tamil

Enter marks: 98

Enter student name: kanishka

Enter marks: 56

Enter student name: santhosh

Enter marks: 78

Enter student name: nandha kumar

Enter marks: 95

Original Dictionary: {'tamil': 98, 'kanishka': 56, 'santhosh': 78, 'nandha kumar': 95}

After setdefault: {'tamil': 98, 'kanishka': 56, 'santhosh': 78, 'nandha kumar': 95, 'Anita': 90}

Keys: dict_keys(['tamil', 'kanishka', 'santhosh', 'nandha kumar', 'Anita'])

Values: dict_values([98, 56, 78, 95, 90])

Items: dict_items([('tamil', 98), ('kanishka', 56), ('santhosh', 78), ('nandha kumar', 95), ('Anita', 90)])

Sorted keys: ['Anita', 'kanishka', 'nandha kumar', 'santhosh', 'tamil']

Maximum marks: 98

Minimum marks: 56

Sum of marks: 417

After pop('Anita'): {'tamil': 98, 'kanishka': 56, 'santhosh': 78, 'nandha kumar': 95}

After popitem: {'tamil': 98, 'kanishka': 56, 'santhosh': 78}

Removed item: ('nandha kumar', 95)

After del: {'kanishka': 56, 'santhosh': 78}

After clear: {}

You might also like