how to assign user input to a variable python

Published on Aug. 22, 2023, 12:16 p.m.

To assign user input to a variable in Python, you can use the input() function. Here’s an example:

# Ask the user for their name
name = input("What is your name? ")

# Print a message using the user's name
print("Hello, " + name + "!")

When this code is run, the input() function will display the prompt “What is your name? ” and wait for the user to enter their name. The value that the user enters will be assigned to the variable name. Then, the program will print a message that includes the user’s name using string concatenation.

You can also format strings using f-strings to include user input:

# Ask the user for their name and age
name = input("What is your name? ")
age = input("What is your age? ")

# Print a message using the user's name and age
print(f"{name} is {age} years old.")

This will output a message like “Alice is 30 years old.” with the values that the user entered.

Tags:

related content