Learning Sections show
In Python, user input can be captured using the built-in
input()
function. This function reads a line from input, converts it to a string (removing the trailing newline), and returns that string. The basic usage of input()
is straightforward, but it can be extended to handle various types of inputs and multiple inputs efficiently.Here's a simple example to get started:
name = input("Enter your name: ")
print(f"Hello, {name}!")
When this script is run, it will prompt the user to enter their name and then greet them with the provided name.
Example with Multiple Inputs
Sometimes, you might need to capture multiple pieces of information from the user. You can do this by using input()
multiple times or by splitting a single input into multiple values. Here's an example:
# Using multiple input() calls
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
print(f"Hello, {first_name} {last_name}!")
# Using split() to handle multiple inputs in a single line
data = input("Enter your age and height (separated by a space): ")
age, height = data.split()
age = int(age)
height = float(height)
print(f"You are {age} years old and {height} meters tall.")