Code Examples
Example 1
This example shows how to convert a string input to an integer using the int() function. Once converted, you can perform mathematical operations like addition. If the user enters "25", the program will convert it to the integer 25, add 1 to it, and display "Next year you will be: 26". Note that this will cause an error if the user enters something that can't be converted to an integer (like "twenty-five" or "25.5").
# Converting string input to an integer
user_age_str = input("How old are you? ")
user_age = int(user_age_str) # Convert the string to an integer
next_year_age = user_age + 1
print("Next year you will be:", next_year_age)
Example 2
This example demonstrates converting input to a float (decimal number) using the float() function. This is necessary when you need to work with decimal values. After converting the input to a float, the program calculates the height in feet and displays it with two decimal places using the :.2f format specifier in the f-string. If the user enters "1.75", the program will convert it to the float 1.75, multiply by 3.28084, and display "Your height in feet is: 5.74".
# Converting string input to a floating-point number
height_str = input("Enter your height in meters: ")
height = float(height_str) # Convert the string to a float
# Calculate height in feet (1 meter = 3.28084 feet)
height_in_feet = height * 3.28084
print(f"Your height in feet is: {height_in_feet:.2f}")
Example 3
This example shows a practical use of string-to-integer conversion. The program asks for an item name (kept as a string) and a quantity (converted to an integer). After conversion, it can use the quantity in mathematical comparisons like quantity > 1. This example demonstrates how you often need to convert only certain inputs while leaving others as strings, depending on how you plan to use them.
# Working with mixed string and number input
item_name = input("Enter the name of the item: ")
quantity_str = input("How many do you want? ")
quantity = int(quantity_str)
# Display information using the converted values
print(f"You ordered {quantity} {item_name}(s)")
if quantity > 1:
print(f"That's a lot of {item_name}s!")
else:
print(f"Just one {item_name}, got it!")