0% found this document useful (0 votes)
3 views62 pages

Python Programs Collection

The document is a collection of Python programs demonstrating various programming concepts such as variables, conditionals, loops, lists, tuples, and dictionaries. Each program serves a specific purpose, including calculating areas, checking even/odd numbers, managing student marks, and implementing a simple shopping mall system. The collection provides practical examples for beginners to understand and apply Python programming fundamentals.

Uploaded by

pl0029549
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)
3 views62 pages

Python Programs Collection

The document is a collection of Python programs demonstrating various programming concepts such as variables, conditionals, loops, lists, tuples, and dictionaries. Each program serves a specific purpose, including calculating areas, checking even/odd numbers, managing student marks, and implementing a simple shopping mall system. The collection provides practical examples for beginners to understand and apply Python programming fundamentals.

Uploaded by

pl0029549
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

Python Programs Collection

[Link]
# Example of variables
name = "bhanu"
age = 25
height=5.4
print("Name:", name)
print("Age:", age)
print("height", height)
[Link]
# Calculate area using constants and variables
radius = float(input("Enter the radius: "))
PI = 3.14159
area = PI * radius * radius
print("Area of the circle:", area)
[Link]
# Check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:# 1==1
print(num, "is even")
else:
print(num, "is odd")
[Link]
# Check if a number is positive, negative, or zero
num = int(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
[Link]
# Find the largest among three numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a > b and a > c:
print(a, "is the largest")
elif b > c:
print(b, "is the largest")
else:
print(c, "is the largest")
[Link]
# Check grade based on marks
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
[Link]
# Check if a year is a leap year
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
[Link]
# Check username and password
username = input("Enter username: ")
password = input("Enter password: ")
if username == "admin" and password == "1234":
print("Login successful!")
else:
print("Invalid credentials")
[Link]
# Check if a character is a vowel or consonant
char = input("Enter a character: ").lower()
if char in 'aeiou':
print(char, "is a vowel")
else:
print(char, "is a consonant")
[Link]
# Check if a number is divisible by both 3 and 5
num = int(input("Enter a number: "))
if num % 3 == 0 and num % 5 == 0:
print(num, "is divisible by both 3 and 5")
else:
print(num, "is not divisible by both")
[Link]
# Calculate electricity bill based on usage
units = int(input("Enter electricity units consumed: "))
if units <= 100:
bill = units * 5
elif units <= 200:
bill = 100 * 5 + (units - 100) * 10
else:
bill = 100 * 5 + 100 * 10 + (units - 200) * 15
print("Electricity bill:", bill)
[Link]
# Example of constants (by convention, constants are written in uppercase)
PI = 3.14159
GRAVITY = 9.8
print("Value of PI:", PI)
print("Value of Gravity:", GRAVITY)
[Link]
# Calculator based on user choice
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print("Choose operation: +, -, *, /")
operation = input("Enter operation: ")
if operation == '+':
print("Result:", num1 + num2)
elif operation == '-':
print("Result:", num1 - num2)
elif operation == '*':
print("Result:", num1 * num2)
elif operation == '/':
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Division by zero error")
else:
print("Invalid operation")
[Link]
# Used when you know how many times you want to repeat
# something (iterate over a sequence like a list, tuple, string, or
# range).
for i in range(5):
print("Hello", i)
[Link]
# Used when you want to repeat something
# until a condition becomes false.
count = 1
while count <= 5:
print("Count =", count)
count += 1
[Link]
# break – Exits the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
[Link]
# Student Marks Manager

# Step 1
names = []
marks = []

while True:
# Display the menu
print("\n=== STUDENT MARKS MANAGER ===")
print("1. Add Student Marks")
print("2. View All Students")
print("3. Search Student")
print("4. Calculate Average Marks")
print("5. Exit")

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

# Option 1: Add a new student and their marks


if choice == "1":
name = input("Enter student name: ")
mark = float(input("Enter marks (out of 100): "))
[Link](name)
[Link](mark)
print("Student record added successfully.")

# Option 2: View all students with their marks


elif choice == "2":
if names:
print("\nList of Students:")
for i in range(len(names)):
print(f"{i+1}. {names[i]} - {marks[i]} marks")
else:
print("No student records found.")

# Option 3: Search a student by name


elif choice == "3":
search = input("Enter student name to search: ")
if search in names:
index = [Link](search)
print(f"{search} scored {marks[index]} marks.")
else:
print("Student not found.")

# Option 4: Calculate and display average marks


elif choice == "4":
if marks:
average = sum(marks) / len(marks)
print(f"Average Marks of Class: {average:.2f}")
else:
print("No marks available to calculate average.")

# Option 5: Exit the program


elif choice == "5":
print("Thank you for using Student Marks Manager.")
break

# Invalid choice
else:
print("Invalid choice. Please enter a number between 1 and 5.")
[Link]
# else with loops – Executes after the loop finishes normally
# (not by break).

for i in range(3):
print(i)
else:
print("Loop finished!")
[Link]
# A list in Python is a collection of items (elements) that can hold
# different data types — like numbers, strings, or even other lists.
# Ordered (items have a defined order)

# Mutable (you can change, add, or remove items)

# Allows duplicates

# Can contain different data types

numbers = [10, 20, 30, 40, 50]


print(numbers)
[Link]
# List of Strings
fruits = ["apple", "banana", "cherry"]
print(fruits)
[Link]
# Mixed Data Types
mixed = [25, "hello", 3.14, True]
print(mixed)
[Link]
# Arithmetic using variables
a = 10
b = 5
sum = a + b
sub =a -b
multi =a*b
div = a/b
mod= a%b
print("Sum:", sum)
print("Sub:", sub)
print("multi:",multi)
print("div:", div)
print("mod:", mod)
[Link]
# Use index numbers (starting from 0).
fruits = ["apple", "banana", "cherry"]

print(fruits[0]) # First element


print(fruits[1]) # Second element
print(fruits[-1]) # Last element

print(fruits[0:2]) # From index 0 to 1


print(fruits[:2]) # Same as above
print(fruits[1:]) # From index 1 to end

[Link]("mango")
[Link](1, "orange")
[Link](["grape", "melon"])
print(fruits)

[Link]("apple")
[Link](1)
print(fruits)

# Lists are mutable, so you can modify them directly.

fruits[0] = "kiwi"
print(fruits)
[Link]
# A tuple is a collection of items —
# just like a list — but it is immutable,
# meaning you cannot change, add, or
# remove elements after it is created.
# Tuples are often used to store data that
# should not be modified.

fruits = ("apple", "banana", "cherry")


print(fruits)
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[0:2]) # ('apple', 'banana')
print(len(fruits))
# Count Occurrences
print([Link]("banana"))
# Find Index
print([Link]("cherry"))

# check if item exists


print("apple" in fruits) # True
print("mango" in fruits) # False

# Concatenation (Joining Tuples)

more_fruits = ("mango", "grape")


new_tuple = fruits + more_fruits
print(new_tuple)

# repetition
print(fruits * 2)

# loops in tuple
for fruit in fruits:
print(fruit)
[Link]
# Simple Shopping Mall Program

# List of items and their prices


items = ["T-shirt", "Jeans", "Shoes", "Watch", "Perfume"]
prices = [500, 1200, 2000, 1500, 800]

# Empty shopping cart


cart = []

while True:
# Display menu options
print("\n=== SHOPPING MALL MENU ===")
print("1. View Items")
print("2. Add Item to Cart")
print("3. View Cart")
print("4. Checkout")
print("5. Exit")

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

# Option 1: View available items


if choice == "1":
print("\nAvailable Items:")
for i in range(len(items)):
print(f"{i+1}. {items[i]} - Rs.{prices[i]}")

# Option 2: Add item to cart


elif choice == "2":
num = int(input("Enter item number to add: ")) - 1 # Get index
if 0 <= num < len(items):
[Link](items[num]) # Add to cart
print(f" {items[num]} added to cart.")
else:
print(" Invalid item number!")

# Option 3: View items in cart


elif choice == "3":
if cart:
print("\n■ Your Cart Items:")
for c in cart:
print("-", c)
else:
print("■■ Your cart is empty!")

# Option 4: Checkout and show total bill


elif choice == "4":
if cart:
total = 0
print("\n===== BILL RECEIPT =====")
for c in cart:
price = prices[[Link](c)] # Get price by matching name
print(f"{c} - Rs.{price}")
total += price
print("------------------------")
print(" Total Amount: Rs.", total)
print("Thank you for shopping! ")
break
else:
print(" Your cart is empty. Add items first!")

# Option 5: Exit program


elif choice == "5":
print(" Thank you! Visit again.")
break

# If user enters wrong option


else:
print(" Invalid choice! Please enter 1-5.")
[Link]
# Student Marks Manager (Beginner Friendly)

# Step 1: Create empty lists to store names and marks


names = []
marks = []

while True:
# Display the menu
print("\n=== STUDENT MARKS MANAGER ===")
print("1. Add Student Marks")
print("2. View All Students")
print("3. Search Student")
print("4. Calculate Average Marks")
print("5. Exit")

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

# Option 1: Add a new student and their marks


if choice == "1":
name = input("Enter student name: ")
mark = float(input("Enter marks (out of 100): "))
[Link](name)
[Link](mark)
print("Student record added successfully.")

# Option 2: View all students with their marks


elif choice == "2":
if names:
print("\nList of Students:")
for i in range(len(names)):
print(f"{i+1}. {names[i]} - {marks[i]} marks")
else:
print("No student records found.")

# Option 3: Search a student by name


elif choice == "3":
search = input("Enter student name to search: ")
if search in names:

index = [Link](search)
print(f"{search} scored {marks[index]} marks.")
else:
print("Student not found.")

# Option 4: Calculate and display average marks


elif choice == "4":
if marks:
average = sum(marks) / len(marks)
print(f"Average Marks of Class: {average:.2f}")
else:
print("No marks available to calculate average.")

# Option 5: Exit the program


elif choice == "5":
print("Thank you for using Student Marks Manager.")
break

# Invalid choice
else:
print("Invalid choice. Please enter a number between 1 and 5.")
[Link]
# Weekday Finder using Tuple

# Step 1: Create a tuple of weekdays


weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")

# Step 2: Ask user to enter a number


num = int(input("Enter a number between 1 and 7: "))

# Step 3: Check if number is valid and display day


if 1 <= num <= 7:
print("Day is:", weekdays[num - 1]) # Access tuple element using index
else:
print("Invalid input! Please enter number from 1 to 7.")
34,[Link]
# Student Marks Manager

# Step 1
names = []
marks = []

while True:
# Display the menu
print("\n=== STUDENT MARKS MANAGER ===")
print("1. Add Student Marks")
print("2. View All Students")
print("3. Search Student")
print("4. Calculate Average Marks")
print("5. Exit")

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

# Option 1: Add a new student and their marks


if choice == "1":
name = input("Enter student name: ")
mark = float(input("Enter marks (out of 100): "))
[Link](name)
[Link](mark)
print("Student record added successfully.")

# Option 2: View all students with their marks


elif choice == "2":
if names:
print("\nList of Students:")
for i in range(len(names)):
print(f"{i+1}. {names[i]} - {marks[i]} marks")
else:
print("No student records found.")

# Option 3: Search a student by name


elif choice == "3":
search = input("Enter student name to search: ")
if search in names:
index = [Link](search)
print(f"{search} scored {marks[index]} marks.")
else:
print("Student not found.")

# Option 4: Calculate and display average marks


elif choice == "4":
if marks:
average = sum(marks) / len(marks)
print(f"Average Marks of Class: {average:.2f}")
else:
print("No marks available to calculate average.")

# Option 5: Exit the program


elif choice == "5":
print("Thank you for using Student Marks Manager.")
break

# Invalid choice
else:
print("Invalid choice. Please enter a number between 1 and 5.")
[Link]
# A dictionary is a collection of data in key–value pairs.
# It lets you store and access data by name (key) instead
# of by position (like in lists or tuples).

student = {"name": "Riya", "age": 20, "marks": 85}


print(student)

print(student["name"])
print(student["marks"])

student["city"] = "Delhi"
print(student)

# updating value
student["marks"] = 9
print(student)

# removing value
[Link]("age") # Removes key "age"
print(student)
[Link]
# Dictionary with Mixed Data
data = {
"name": "John",
"age": 25,
"skills": ["Python", "HTML", "CSS"],
"address": {"city": "Mumbai", "pin": 400001}
}
print(data["skills"])
print(data["address"]["city"])
[Link]
# Student Marks Record using Dictionary

# Step 1: Create an empty dictionary


students = {}

while True:
# Display menu options
print("\n=== STUDENT MARKS RECORD ===")
print("1. Add Student")
print("2. View All Students")
print("3. Search Student")
print("4. Update Marks")
print("5. Delete Student")
print("6. Exit")

choice = input("Enter your choice (1-6): ")

# Option 1: Add student record


if choice == "1":
name = input("Enter student name: ")
marks = float(input("Enter marks (out of 100): "))
students[name] = marks # Add to dictionary
print("Record added successfully.")

# Option 2: View all students


elif choice == "2":
if students:
print("\nAll Student Records:")
for name, marks in [Link]():
print(f"{name} - {marks} marks")
else:
print("No records found.")

# Option 3: Search student by name


elif choice == "3":
name = input("Enter name to search: ")
if name in students:
print(f"{name} scored {students[name]} marks.")
else:
print("Student not found.")

# Option 4: Update student marks


elif choice == "4":
name = input("Enter name to update marks: ")
if name in students:
new_marks = float(input("Enter new marks: "))
students[name] = new_marks
print("Marks updated successfully.")
else:
print("Student not found.")

# Option 5: Delete student record


elif choice == "5":
name = input("Enter name to delete: ")
if name in students:
[Link](name)
print("Record deleted successfully.")
else:
print("Student not found.")

# Option 6: Exit
elif choice == "6":
print("Thank you for using Student Marks Record.")
break

# Invalid choice
else:
print("Invalid choice. Please enter number 1–6.")
[Link]
# Phone Book Program using Dictionary

# Step 1: Create an empty dictionary to store contacts


phone_book = {}

while True:
# Step 2: Show menu options
print("\n=== PHONE BOOK MENU ===")
print("1. Add Contact")
print("2. View All Contacts")
print("3. Search Contact")
print("4. Update Contact Number")
print("5. Delete Contact")
print("6. Exit")

choice = input("Enter your choice (1-6): ")

# Option 1: Add new contact


if choice == "1":
name = input("Enter contact name: ")
number = input("Enter phone number: ")
phone_book[name] = number
print("Contact added successfully.")

# Option 2: View all contacts


elif choice == "2":
if phone_book:
print("\nAll Contacts:")
for name, number in phone_book.items():
print(f"{name} : {number}")
else:
print("No contacts found.")

# Option 3: Search for a contact


elif choice == "3":
name = input("Enter name to search: ")
if name in phone_book:
print(f"{name}'s Number: {phone_book[name]}")
else:
print("Contact not found.")

# Option 4: Update contact number


elif choice == "4":
name = input("Enter name to update: ")
if name in phone_book:
new_number = input("Enter new phone number: ")
phone_book[name] = new_number
print("Contact updated successfully.")
else:
print("Contact not found.")

# Option 5: Delete a contact


elif choice == "5":
name = input("Enter name to delete: ")
if name in phone_book:
phone_book.pop(name)
print("Contact deleted successfully.")
else:
print("Contact not found.")

# Option 6: Exit program


elif choice == "6":
print("Thank you for using the Phone Book.")
break

# Invalid input
else:
print("Invalid choice! Please enter a number from 1 to 6.")
[Link]
# NumPy stands for Numerical Python.
# It is a Python library used for fast mathematical operations
# on large amounts of data.
# Arrays (faster than lists)
# Mathematical functions (sum, mean, sqrt, etc.)
# Matrix operations,Support for scientific computing

# Create a NumPy Array

import numpy as np
arr = [Link]([10, 20, 30, 40])
print(arr)

# Array with Range of Numbers

import numpy as np
arr = [Link](1, 11) # 1 to 10
print(arr)

# Mathematical Operations on Arrays


import numpy as np
arr = [Link]([5, 10, 15])
print(arr + 5) # Add 5 to each element
print(arr * 2) # Multiply each element by 2

# Find Sum, Mean, Max, Min


import numpy as np
arr = [Link]([1, 2, 3, 4, 5])
print("Sum:", [Link](arr))
print("Mean:", [Link](arr))
print("Max:", [Link](arr))
print("Min:", [Link](arr))
[Link]
# Swap two variables
x = 10
y = 20
x, y = y, x
print("x:", x)
print("y:", y)
[Link]
# Student Marks Analysis

import numpy as np

# Marks of 5 students in 3 subjects


marks = [Link]([[78, 85, 90],
[88, 76, 92],
[90, 91, 85],
[76, 80, 79],
[89, 84, 88]])

print("Total marks of each student:", [Link](marks, axis=1))


print("Average marks of each student:", [Link](marks, axis=1))
print("Highest marks:", [Link](marks))
print("Lowest marks:", [Link](marks))
[Link]
# Temperature Data Analysis
import numpy as np

temps = [Link]([30.5, 32.0, 31.2, 33.1, 29.8, 28.9, 30.0])

print("Average Temperature:", [Link](temps))


print("Maximum Temperature:", [Link](temps))
print("Minimum Temperature:", [Link](temps))
print("Temperature Difference Each Day:", [Link](temps))
[Link]
# Sales Analysis for a Shop
import numpy as np

sales = [Link]([[100, 120, 130, 90, 110], # Product 1


[80, 85, 88, 92, 100], # Product 2
[150, 160, 155, 170, 180], # Product 3
[50, 60, 65, 55, 70]]) # Product 4

print("Total sales of each product:", [Link](sales, axis=1))


print("Average daily sales:", [Link](sales, axis=1))
print("Highest sale in all:", [Link](sales))
[Link]
# Sports Scores Comparison
import numpy as np

teamA = [Link]([45, 56, 67, 70, 65])


teamB = [Link]([40, 60, 65, 75, 68])

print("Team A average:", [Link](teamA))


print("Team B average:", [Link](teamB))
print("Matchwise winner (1 = A wins):", teamA > teamB)
[Link]
# Random Data Simulation (Exam Scores)

import numpy as np

# Generate random marks (50 students)


scores = [Link](40, 100, size=50)

print("All Scores:", scores)


print("Average Score:", [Link](scores))
print("Highest Score:", [Link](scores))
print("Lowest Score:", [Link](scores))
print("Students scoring above 80:", [Link](scores > 80))
[Link]
# ■ Pandas stands for Python Data Analysis Library.
# It is used for storing, cleaning, analyzing, and visualizing data — especially data in table (
# Create a Series
import pandas as pd
data = [10, 20, 30, 40]
s = [Link](data)
print(s)

# Create a DataFrame
import pandas as pd
data = {
'Name': ['Riya', 'Amit', 'John'],
'Age': [20, 22, 19],
'Marks': [85, 90, 88]
}

df = [Link](data)
print(df)

# Basic Data Analysis


print("Average Marks:", df['Marks'].mean())
print("Highest Marks:", df['Marks'].max())
print("Lowest Marks:", df['Marks'].min())
[Link]
# Student Report Analysis
import pandas as pd

data = {
'Name': ['Riya', 'Amit', 'John', 'Sara'],
'Maths': [85, 90, 78, 92],
'Science': [88, 85, 80, 95],
'English': [82, 87, 75, 90]
}

df = [Link](data)

print("Student Data:\n", df)


print("\nAverage Marks of Each Student:\n", df[['Maths','Science','English']].mean(axis=1))
print("\nHighest Marks in Each Subject:\n", df[['Maths','Science','English']].max())
[Link]
# Sales Data Analysis

import pandas as pd

data = {
'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
'Sales': [2000, 2500, 1800, 3000, 2800]
}

df = [Link](data)

print("Total Sales:", df['Sales'].sum())


print("Average Sales:", df['Sales'].mean())
print("Highest Sales Day:\n", [Link][df['Sales'].idxmax()])
[Link]
# Employee Salary Record
import pandas as pd

data = {
'Employee': ['Rohan', 'Neha', 'Vikas', 'Priya'],
'Department': ['HR', 'IT', 'Finance', 'IT'],
'Salary': [40000, 55000, 48000, 60000]
}

df = [Link](data)

print("\nAverage Salary:", df['Salary'].mean())


print("\nEmployees in IT Department:\n", df[df['Department'] == 'IT'])
[Link]
# Temperature Data Report
import pandas as pd

data = {
'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
'Temp': [30, 32, 31, 29, 28, 27, 30]
}

df = [Link](data)

print("Average Temperature:", df['Temp'].mean())


print("Coldest Day:\n", [Link][df['Temp'].idxmin()])
print("Hottest Day:\n", [Link][df['Temp'].idxmax()])
[Link]
# Get input from user
#
name = input("Enter your name: ")
age =int(input("enter your age "))
print("Hello", name)
print("age", age)
[Link]
# Library Book Record
import pandas as pd

data = {
'Book': ['Python Basics', 'Data Science 101', 'ML Intro', 'AI for All'],
'Total_Copies': [10, 8, 6, 5],
'Issued': [4, 3, 2, 5]
}

df = [Link](data)
df['Available'] = df['Total_Copies'] - df['Issued']

print(df)
print("\nBooks Fully Issued:\n", df[df['Available'] == 0])
[Link]
# Matplotlib is a Python library used for creating charts and
# graphs to visualize data.
# Line Chart

import [Link] as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]

[Link](x, y)
[Link]("Simple Line Chart")
[Link]("X Axis")
[Link]("Y Axis")
[Link]()
[Link]
# bar chart
import [Link] as plt

students = ['Riya', 'Amit', 'John', 'Sara']


marks = [85, 90, 78, 92]

[Link](students, marks, color='skyblue')


[Link]("Student Marks")
[Link]("Names")
[Link]("Marks")
[Link]()
[Link]
# pie chart
import [Link] as plt

subjects = ['Maths', 'Science', 'English', 'History']


marks = [80, 85, 75, 60]

[Link](marks, labels=subjects, autopct='%1.1f%%', startangle=90)


[Link]("Marks Distribution")
[Link]()
[Link]
# scatter plot

import [Link] as plt

x = [5, 7, 8, 9, 10]
y = [50, 54, 52, 58, 60]

[Link](x, y, color='green')
[Link]("Scatter Plot Example")
[Link]("Hours Studied")
[Link]("Marks Scored")
[Link]()
[Link]
# histogram
import [Link] as plt

ages = [18, 20, 22, 20, 25, 30, 35, 30, 28, 40]

[Link](ages, bins=5, color='orange', edgecolor='black')


[Link]("Age Distribution")
[Link]("Age")
[Link]("Count")
[Link]()
[Link]
# Simple calculator
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Sum:", num1 + num2)
print("hello","world",num1)
[Link]
# Concatenate two strings
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
print("Full Name:", first_name + " " + last_name)
[Link]
# Example of different data types
num = 10
text = "Python"
pi = 3.14
print(type(num))
print(type(text))
print(type(pi))
[Link]
# Convert string to integer
num_str = "100"
num = int(num_str)
print("Converted value:", num)
# ATM Program in Python using loop and [Link]
# ATM Program in Python using loop and if-else

# Predefined User ID and Password


user_id = "bhanu"
password = "1234" # detailed
balance = 10000 # initial balance

# Authentication
attempts = 3
while attempts > 0:
uid = input("Enter User ID: ")
pwd = input("Enter Password: ")

if uid == user_id and pwd == password:


print("\n■ Login Successful!\n")

# ATM Menu
while True:
print("------ ATM Menu ------")
print("1. Check Balance")
print("2. Withdraw Money")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == "1":
print("■ Your Balance is:", balance)

elif choice == "2":


amount = int(input("Enter withdrawal amount: "))
if amount > balance:
print("■ Insufficient Balance!")
elif amount <= 0:
print("■ Invalid Amount!")
else:
balance -= amount
print("■ Withdraw Successful! Remaining Balance:", balance)

elif choice == "3":


print("■ Thank you for using ATM!")
break

else:
print("■ Invalid choice, try again.\n")

break # exit login loop after successful login

else:
attempts -= 1
print("■ Invalid User ID or Password! Attempts left:", attempts)

if attempts == 0:
print("■ Account Blocked due to too many failed attempts!")

You might also like