+ 1
how do I test if a variable has text instead of numbers?
I want to make an error-proof calculator and I want it to see if some one decided to use text instead of numbers in a variable to stop the error and make them type the value of the variable again.
10 ответов
+ 2
Try isdigit() function it checks if a string is containing only digits and if so it return true. so just convert it to int if its true other wise give a message that the input should be numbers
+ 1
if type(my_var) == str:
# Do stuff here
You can also use assert to check if a variable is a certain type. it will throw an AssertionError instead though if it doesn't evaluate to true:
def my_func(foo):
assert(type(foo) == str)
# Do stuff here
+ 1
print('3'.isdigit()) this will return true 👍🏼
0
I tried what my brother, Star Fusion said and this is my code. It's like it skips the "wrongNumber = True" part. Please help!
wrongNumber1 = False
wrongNumber2 = False
num1 = 0
num2 = 0
#Shows the phone what to do to gather numbers
while wrongNumber1 == True:
num1 = input("Enter your first number: ")
if num1.isdigit():
num1 = int(num1)
wrongNumber1 = False
wrongNumber2 = True
else:
print("ERR_UNKNOWN_VALUE")
wrongNumber1 = True
while wrongNumber2 == True:
wrongNumber2 = False
num2 = input("Enter your second number: ")
if num2.isdigit():
num2 = int(num2)
else:
print("ERR_UNKNOWN_VALUE")
wrongNumber2 = True
#END setup number gathering, START user input
while prgrmRun == True:
print("Options:\nQuit\nAdd\nSubtract\nMultiply\nDivide\nPut in the symbol please. To quit just type in Quit.")
answerType = input("> ")
if answerType == "+":
wrongNumber1 = True:
print(f"The answer is {num1 + num2}")
elif answerType == "-":
wrongNumber1 = True
print(f"The answer is {n
0
(The text is too long and that indent isn't supposed to be there)
0
You need to rearrange the program in the correct order or to use functions,
see it will go through the program line by line so you need to take the inputs and change the value of the wrongNumber1 to true before the while otherwise it won't go inside the loop because its intialized in the first line to false
0
Try breaking the program to functions and call them I think this is the idea of what your doing
0
so do I cut and paste the while wrongNumber loops underneath the while prgrmRun loop?
I'm not doing functions BTW, too lazy. LOL
And I want it to print the options first and take the answerType input before you have to input your numbers.
0
1.You can see the data type of the variable declared in the main().
2.you can use isdigit() function or isalpha() to check whether it is a number or alphabet respectively.
3.You can just use cout<<variable;