How can you convert user input from a string to an integer in Python?
a) Using the str() function
b) Using the int() function
c) Using the input() function
d) Using the convert() function
Answer:
b) Using the int() function
Explanation:
To convert user input from a string to an integer in Python, you can use the int()
function. Since the input()
function returns data as a string, you often need to convert it to an integer if you want to perform numerical operations.
age = input("Enter your age: ")
age = int(age) # Converts the input string to an integer
print(f"Next year, you will be {age + 1} years old.")
Using the int()
function is crucial when working with numerical input from users, as it ensures that you can perform calculations and comparisons on the data.
Correctly handling user input and converting data types are important steps in creating robust and user-friendly applications.