Lesson 4: Input, Output, and Type Casting

🎯 Lesson Objective

To understand how to take user input, display output, and convert data types in Python programs.


🧠 1. Input in Python

The input() function allows users to enter data from the keyboard.
By default, it returns data as a string.

Example:

name = input("Enter your name: ")
print("Hello,", name)

πŸ”Ή Example 2: Taking numeric input

num = input("Enter a number: ")
print(num + 10)  # ❌ Error (string + int not allowed)

To fix this, convert input to an integer:

num = int(input("Enter a number: "))
print(num + 10)  # βœ… Works correctly

πŸ’¬ 2. Output in Python

Use the print() function to display information.

Example:

name = "Ali"
age = 25
print("My name is", name, "and I am", age, "years old.")

πŸ”Ή Formatting Output
You can format text neatly using f-strings:

name = "Sara"
age = 21
print(f"My name is {name} and I am {age} years old.")

Another method: format()

print("My name is {} and I am {} years old.".format(name, age))

πŸ”„ 3. Type Casting

Type casting means converting one data type to another.

Common conversion functions:

FunctionDescriptionExampleOutput
int()Converts to integerint("10")10
float()Converts to floatfloat("3.14")3.14
str()Converts to stringstr(25)“25”
bool()Converts to booleanbool(0)False

Example:

x = "100"
print(int(x) + 50)   # 150

πŸ” 4. Combining Input, Output & Type Casting

Example Program:

name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Welcome {name}! Next year you will be {age + 1} years old.")

Output:

Enter your name: Ahmed
Enter your age: 20
Welcome Ahmed! Next year you will be 21 years old.

🧩 5. Real-Life Example

Suppose you are building a billing program:

item = input("Enter item name: ")
price = float(input("Enter item price: "))
quantity = int(input("Enter quantity: "))
total = price * quantity
print(f"Total cost for {item} = β‚Ή{total}")

🧠 6. Practice Ideas

Take age as input and display how old the person will be after 10 years.

Write a program to input two numbers and display their sum, difference, and product.

Create a greeting program that asks for the user’s name and city, then prints a personalized message.

Convert a string "123.45" to a float and print its type.

more examples


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *