I'm new to the whole coding thing...so here goes. Just trying to write a simple number guess game, but also do input validation. So that only integers are accepted as input. I've figured out how to weed out alphabetic characters, so I can convert the numbers into an integer. I'm having trouble when I put in a float number. I can't get it to convert the float number over to an integer. Any help is appreciated. As I said I'm on about day 3 of this coding thing so try to be understanding of my little knowledge. Thanks in advance.
Here's the function from my main program.
def validateInput():
while True:
global userGuess
userGuess = input("Please enter a number from 1 to 100. ")
if userGuess.isalpha() == False:
userGuess = int(userGuess)
print(type(userGuess), "at 'isalpha() == False'")
break
elif userGuess.isalpha() == True:
print("Please enter whole numbers only, no words.")
print(type(userGuess), "at 'isalpha() == True'")
return userGuess
Here's the error I'm getting if I use 4.3 (or any float) as input.
Traceback (most recent call last):
File "C:\\*******.py\line 58, in <module>
validateInput()
File "C:\\*******.py\line 28, in validateInput
userGuess = int(userGuess)
ValueError: invalid literal for int() with base 10: '4.3'
if spam == False:
, justif not spam:
. In anelif
, you don't need to recheck the opposite of theif
test—you already knowisalpha
is true, because you know it isn't false. So, just useelse:
. If you're returninguserGuess
from this function, you almost certainly don't need it to beglobal
. And finally, you don't need tobreak
just to hit thereturn
; you can justreturn userGuess
right there in theif
block. – Faiyum