-
1. Introduction to Python
-
2. Python Basics
-
3. Working with Data Structures
-
4. Functions and Modules
-
5. Object-Oriented Programming (OOP)
-
6. File Handling
-
7. Error and Exception Handling
-
8. Python for Data Analysis
-
9. Advanced Topics in Python
-
10. Working with APIs
-
11. Python for Automation
-
12. Capstone Projects
- 13. Final Assessment and Quizzes
2.2.1 Accepting user input using input()
In Python, the input() function is used to accept user input from the keyboard during program execution. This is an essential part of making interactive programs where you need to gather information from the user.
Basic Syntax of input()
variable = input(prompt)
- prompt: The optional string displayed to the user before they enter their input. It helps guide the user on what information is expected.
- variable: The variable in which the user's input will be stored.
- input(): This function waits for the user to type something and press Enter. Once Enter is pressed, it returns the value entered as a string.
1. Basic Example of input()
name = input("Enter your name: ") print("Hello, " + name + "!")
- The program displays the prompt: "Enter your name: ".
- The user types their name and presses Enter.
- The input is stored in the variable name.
- The program then prints a greeting, for example, "Hello, Alice!".
Note: The value entered by the user is always returned as a string, even if the user types a number or any other type of data.
2. Accepting Numbers with input()
Although input() returns a string, you can accept numbers by converting the input to the appropriate data type, such as int or float.
Example of Accepting an Integer
age = input("Enter your age: ") age = int(age) # Convert the input to an integer print("Your age is", age)
- The input() function reads the input as a string.
- int(age) converts the string to an integer.
- If the user enters a valid integer, the program will print their age.
If the user enters something that cannot be converted to an integer, Python will raise an error (ValueError), so it’s a good idea to handle such cases.
Example of Accepting a Float
weight = input("Enter your weight in kg: ") weight = float(weight) # Convert the input to a float print("Your weight is", weight, "kg")
- The input() function reads the input as a string.
- float(weight) converts the string to a floating-point number, which is useful for decimal numbers.
3. Using input() to Get Multiple Inputs
You can use input() multiple times in the same program to accept multiple inputs from the user.
Example of Multiple Inputs:
name = input("Enter your name: ") age = input("Enter your age: ") age = int(age) # Convert age to an integer print(f"Hello, {name}! You are {age} years old.")
Here:
- The program asks for the name and age separately.
- The age is converted to an integer after being input.
Alternatively, you can split a single input to get multiple values at once.
Example: Splitting Input into Multiple Values
name, age = input("Enter your name and age: ").split() age = int(age) print(f"Hello, {name}! You are {age} years old.")
In this case:
- The user is asked to input both their name and age in a single line, separated by spaces.
- .split() splits the input string at spaces, assigning the first part to name and the second part to age.
- The age is then converted to an integer.
4. Input with Validation
Since input() returns a string, you often need to validate that the input is in the correct format (e.g., a number when expecting an integer). You can do this with try-except blocks.
Example with Validation:
age = input("Enter your age: ") try: age = int(age) print(f"Your age is {age}.") except ValueError: print("Please enter a valid number.")
- If the user enters something that is not a valid integer, the program catches the ValueError and prints an error message.
5. Using input() for Passwords
When asking for sensitive information, like passwords, it’s common to hide the input on the screen. Python's standard input() function does not hide input by default. However, you can use the getpass module to securely accept a password.
Example with Password Input:
import getpass password = getpass.getpass("Enter your password: ") print("Password accepted.")
- The getpass.getpass() function hides the user's input as they type, ensuring privacy.
Summary:
- input() allows you to accept user input during program execution.
- The input is always returned as a string.
- You can convert the input to other types (e.g., int, float) to handle different data types.
- You can validate user input with try-except blocks to handle errors like invalid conversions.
- For sensitive information (e.g., passwords), use the getpass module to hide input.
Commenting is not enabled on this course.