To allow for interactive input of variables into a Python program, you can use the input() function to gather information from users. Below is an example where you can request multiple variables from the user, process them, and output results based on the entered data.
Example: Interactive Input of Variables
Here’s a sample program that prompts the user to enter their name, age, and favorite color, and then prints a personalized greeting:
def get_user_info():
# Prompt for user name
name = input("Enter your name: ")
# Prompt for user age with validation
while True:
age_input = input("Enter your age: ")
try:
age = int(age_input) # Convert input to an integer
if age < 0:
print("Age cannot be negative. Please try again.")
continue
break # Exit loop if input is valid
except ValueError:
print("Invalid input. Please enter a valid age.")
# Prompt for user's favorite color
favorite_color = input("Enter your favorite color: ")
return name, age, favorite_color
def main():
name, age, favorite_color = get_user_info()
print(f"\nHello, {name}! You are {age} years old and your favorite color is {favorite_color}.")
if __name__ == "__main__":
main()
Explanation:
- Function Definition:
get_user_info is defined to encapsulate user input logic.
- User Prompts:
- The user is first prompted to enter their name.
- Next, they are prompted to input their age. The program checks if the input is a valid integer and not negative, using a loop to handle incorrect inputs.
- Finally, the user is prompted to enter their favorite color.
- Returning Values: The function returns the collected information for further processing.
- Main Functionality: In the
main function, user inputs are collected and printed in a formatted output greeting.
- Running the Program: The program starts when the script is executed.
Example Interaction:
Enter your name: Alice
Enter your age: twenty
Invalid input. Please enter a valid age.
Enter your age: 25
Enter your favorite color: Blue
Hello, Alice! You are 25 years old and your favorite color is Blue.
Customization
You can modify the program to collect different types of data according to the needs of your application. Here are a few ideas for customization:
- Collect multiple inputs in a loop, as demonstrated in the previous answer about collecting multiple numbers.
- Validate different types of data (e.g., email addresses, phone numbers, etc.).
- Store inputs in a dictionary for easier management of related input data.
- Implement additional logic based on user input (e.g., conditional statements).
This interactive input approach allows you to create dynamic and user-friendly command-line applications in Python.