Hi
I want to check the input of a variable before going further in the program. I can do it in C# like this:
int= pr=0;
do
Console.Write("Price: ");
while (float.TryParse(Console.ReadLine(), out pr) == false);
As long as the input is not ok, the loop will still run. Never an error is shown.
But how to do that with python? I tried this, but i get always an error when the unput is bad.
while True:
pr=int(input("Price: "))
if type(pr) == int:
break
else:
print("No int")
Thanks.
V.

Vishal JoshiRank #377 · 6.7K reputationPosted Mar 24, 2023, 2:38 AM EDT
Hello Valerie,
You can use the code below to get only integer numbers in python.
# input a number while True: try: num = int(input("Enter an integer number: ")) break except ValueError: print("Please input integer only...") continue print("num:", num)Or else you can use isdecimal() to check if the input is decimal. it's similar to TryParse as c#
num = int(num) if num.isdecimal() else NoneThanks
Valerie MeunierRank #1,526 · 1K reputationPosted Mar 23, 2023, 9:27 AM EDT
I tried with try / except and it works, but i wonder whether it exists a specific function like TryParse...
Valerie MeunierRank #1,526 · 1K reputationPosted Mar 24, 2023, 6:35 AM EDT
Thanks