Member-only story
Python Mastery: Essential String Skills for Every Developer
String is a cornerstone of every app. Sometimes you will be positioned in situations where you can't affect which kind of data you get. It's important to know how to handle these situations as a programmer. And this is what this article is about.
Getting data from the input
age = input("Please enter your age: ")
# Please enter your age: 20
if age > 18: # TypeError: '>' not supported between instances of 'str' and 'int'
print("Older than 18)
else:
print("Too young")
Oops, it won't work because the result from the input is string. This is common mistake. We need to convert the string to int.
We can also check the type — yep it's a string.
print(type(age)) # <class 'str'>
What can we do? We also need to protect ourselves from situations where the user may input something other than a number.
while True:
try:
age = input("Please enter your age: ")
if int(age) > 18: # for float you can use float instead of int
print("Older than 18")
else:
print("Too young")
break
except ValueError:
print("Please enter a valid number for age.")
The process of converting a…