'Simplifying user-input foolproofing, Python
I have the following code to make sure that a user enters a float in python:
while True:
try:
some_variable = int(input("Input Prompt: "))
break
except ValueError:
print("Please enter a whole number (in digits)")
The code works fine, but I have a program that needs many of these, and I was wondering if there is a way to simplify it.
ie I wouldn't have to use:
while True:
try:
some_variable = int(input("Input Prompt: "))
break
except ValueError:
print("Please enter a whole number (in digits)")
For every user input. I'd really appreciate any help I can get.
Solution 1:[1]
Ok, I did some research on Thierry Lathuille's suggestion. I used functions to simplify the code. Below is the simplified code for everyone's use:
def int_input(prompt):
while True:
try:
variable_name = int(input(prompt))
return variable_name
except ValueError:
print("Please enter a whole number (in digits)")
def float_input(prompt):
while True:
try:
variable_name = float(input(prompt))
return variable_name
except ValueError:
print("Please enter a number (in digits)")
def yes_input(prompt):
while True:
variable_name = input(prompt).lower()
if variable_name in ["y", "yes"]:
return "yes"
elif variable_name in ["n", "no"]:
return "no"
else:
print("""Please enter either "yes" or "no": """)
while True:
print("Volume of a right circular cone")
print("Insert the radius and height of the cone below:")
one_third = 1 / 3
radius = float_input("Radius: ")
height = float_input("Perpendicular Height: ")
pi_confirm = yes_input("""The value of ? is 22/7, "yes" or "no": """)
if pi_confirm == "yes":
pi = 22/7
if pi_confirm == "no":
pi = float_input("Type the value of pi, for eg ? 3.141592653589: ")
volume = one_third * pi * radius ** 2 * height
accuracy = int_input("How many decimal places do you want your answer to?: ")
print(f"""{volume:.{accuracy}f}""")
new_question = yes_input("""New question? "yes" or "no": """)
if new_question == "no":
break
Again thanks for your help. Also if anyone has any more suggestions for the code I'd really appreciate it if you leave a comment.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
