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

Python

The document outlines a Python program for a list operation app that allows users to append, remove, and display elements from a list. It includes a menu-driven interface for user interaction and demonstrates various Python functionalities, including type conversion and arithmetic operations. The program also provides error handling for invalid inputs and empty lists.

Uploaded by

wave06741
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 views3 pages

Python

The document outlines a Python program for a list operation app that allows users to append, remove, and display elements from a list. It includes a menu-driven interface for user interaction and demonstrates various Python functionalities, including type conversion and arithmetic operations. The program also provides error handling for invalid inputs and empty lists.

Uploaded by

wave06741
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

write a python program to perform operation print(f"{index}.

{item}")
on list app and remove display
elif choice == '4':
# Initialize an empty list to act as our app's # Exit the application
storage print("Exiting the application. Goodbye!")
items_list = [] break

while True: else:


# Display the menu options to the user print("Invalid choice! Please select a valid
print("\n=== LIST OPERATION APP ===") number from 1 to 4.")
print("1. Append (Add an element)") To print numbers from 1 to 10 in Python, the
print("2. Remove (Delete an element)") most efficient method is using a for loop
print("3. Display (Show all elements)") combined with the range() function.
print("4. Exit")
# Loop from 1 to 10
choice = input("Enter your choice (1-4): for i in range(1, 11):
").strip() print(i)

if choice == '1': # Initialize the counter


# Operation: Append an element to the i=1
end of the list
new_item = input("Enter the element to # Loop until i is greater than 10
add: ") while i <= 10:
items_list.append(new_item) print(i)
print(f"Success: '{new_item}' has been i += 1 # Increment the counter
added.")
To perform arithmetic operations on two
elif choice == '2': numbers in Python, you can utilize built-in
# Operation: Remove an element from the Python Arithmetic Operators such as +, -, *, /,
list //, %, and **
if not items_list:
print("The list is empty. Nothing to # Program to perform arithmetic operations
remove.") on two numbers
else: num1 = float(input("Enter first number: "))
remove_item = input("Enter the element num2 = float(input("Enter second number: "))
to remove: ")
if remove_item in items_list: print("\n--- Results ---")
items_list.remove(remove_item) print(f"Add (+): {num1 + num2}")
print(f"Success: '{remove_item}' has print(f"Sub (-): {num1 - num2}")
been removed.") print(f"Mul (*): {num1 * num2}")
else: if num2 != 0:
print(f"Error: '{remove_item}' was not print(f"Div (/): {num1 / num2}")
found in the list.") print(f"Floor (//): {num1 // num2}")
print(f"Mod (%): {num1 % num2}")
elif choice == '3': else:
# Operation: Display the list elements print("Div/Floor/Mod: Error! Division by
if not items_list: zero.")
print("The list is currently empty.") print(f"Exp (**): {num1 ** num2}")
else:
print("\nCurrent List Elements:") Here is a comprehensive Python program that
for index, item in enumerate(items_list, demonstrates implicit type conversion
start=1): (handled automatically by Python) and
explicit type conversion (also known as original_float = 9.99
typecasting, where you manually change truncated_int = int(original_float)
types using built-in functions) print(f"Float {original_float} converted to
Integer: {truncated_int}, Type:
# {type(truncated_int)}")
====================================
====== # D. Number to String
# DEMONSTRATION OF TYPE CONVERSION number_val = 500
IN PYTHON converted_string = str(number_val)
# print(f"Number {number_val} converted to
==================================== String: '{converted_string}', Type:
====== {type(converted_string)}")

print("--- 1. IMPLICIT TYPE CONVERSION ---") # E. Conversion to Boolean


# Python automatically converts lower data print(f"Empty string '' to Boolean: {bool('')}")
types to higher data types to avoid data loss # False
integer_num = 10 print(f"Filled string 'Hi' to Boolean:
float_num = 5.5 {bool('Hi')}") # True
print(f"Zero 0 to Boolean: {bool(0)}") #
# Adding int and float results in a float False
implicit_result = integer_num + float_num print(f"Non-zero 5 to Boolean: {bool(5)}")
# True
print(f"Integer Value: {integer_num}, Type: print()
{type(integer_num)}")
print(f"Float Value: {float_num}, Type:
{type(float_num)}") print("--- 3. ADVANCED COLLECTION
print(f"Result of Addition: {implicit_result}, CONVERSIONS ---")
Type: {type(implicit_result)}") # Converting between iterables/collections
print()
sample_list = [1, 2, 2, 3, 4]
print(f"Original List: {sample_list}")
print("--- 2. EXPLICIT TYPE CONVERSION
(TYPECASTING) ---") # List to Tuple
# Manually converting types using predefined converted_tuple = tuple(sample_list)
constructor functions print(f"Converted to Tuple:
{converted_tuple}")
# A. String to Integer
string_integer = "123" # List to Set (Removes duplicate values)
converted_int = int(string_integer) converted_set = set(sample_list)
print(f"String '{string_integer}' converted to print(f"Converted to Set: {converted_set}")
Integer: {converted_int}, Type: print()
{type(converted_int)}")

# B. String to Float print("--- 4. HANDLING CONVERSION


string_float = "45.67" ERRORS ---")
converted_float = float(string_float) # Attempting to convert an invalid value
print(f"String '{string_float}' converted to causes a ValueError
Float: {converted_float}, Type: invalid_string = "Python123"
{type(converted_float)}")
try:
# C. Float to Integer (Truncates the decimal print("Attempting to convert 'Python123' to
part) an integer...")
failed_conversion = int(invalid_string)
except ValueError as error:
print(f"Error caught successfully! | {error}")

To find the largest of three numbers in Python,


use an if-elif-else conditional ladder
combined with the logical and operator.
# Prompt the user to input three numbers
# Using float() allows the program to handle
both integers and decimals
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

# Check if num1 is greater than or equal to


both num2 and num3
if (num1 >= num2) and (num1 >= num3):
largest = num1

# Check if num2 is greater than or equal to


both num1 and num3
elif (num2 >= num1) and (num2 >= num3):
largest = num2

# If neither num1 nor num2 is the largest, then


num3 must be the largest
else:
largest = num3

# Display the final result


print(f"The largest number is: {largest}")

You might also like