Introduction
Programs become much more useful when they can receive information from users. Python provides the input() function to read data entered from the keyboard.
The input() Function
The input() function displays a message and waits for the user to type something.
name = input("Enter your name: ")
print("Hello", name)
User Input is Always a String
Regardless of what the user types, input() returns a string.
age = input("Enter your age: ")
print(type(age))
The output will be:
<class 'str'>
Converting Input to Numbers
To perform calculations, convert the input to an integer or float.
age = int(input("Enter your age: "))
print(age + 1)
price = float(input("Enter the price: "))
print(price * 2)
Reading Multiple Values
first = input("First name: ")
last = input("Last name: ")
print(first, last)
Practical Example
name = input("Your name: ")
age = int(input("Your age: "))
print("Hello", name)
print("Next year you will be", age + 1)
Handling Invalid Input
If the user enters text where a number is expected, Python raises a ValueError.
age = int(input("Age: "))
If the user types abc, the conversion fails.
Best Practices
- Write clear prompts.
- Convert input to the correct data type.
- Validate user input when possible.
- Use meaningful variable names.
Summary
The input() function allows Python programs to interact with users. Since all input is returned as text, converting values to integers or floats is often necessary before performing calculations.
Examples
The following examples help reinforce the concepts explained in this lesson.
<!DOCTYPE html>
<html>
<head>
<title>My First Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
💡 Pro Tip
Practice every concept immediately after reading it. Learning by doing is the fastest way to master HTML.
⚠ Common Mistake
Do not simply copy code examples. Type them yourself and experiment with small changes.
Best Practices
- Write clean and readable HTML.
- Indent your code consistently.
- Use semantic HTML elements.
- Validate your HTML regularly.
- Test your pages in multiple browsers.
Frequently Asked Questions
Why should I learn HTML first?
HTML is the foundation of every website. Once you understand HTML, learning CSS and JavaScript becomes much easier.
Is HTML difficult?
No. HTML is considered one of the easiest web technologies to learn, making it an excellent starting point for beginners.