srakaproducts.blogg.se

Float to convert string to number python
Float to convert string to number python




float to convert string to number python

You may also want some other checks even inside the try part. Or, if you want to truncate floats, change that int(userGuess) to int(float(userGuess)). If you want to handle check whether it's a float so you can give a different error, do the same thing- try to call float(userGuess)-inside the except clause. If you want to handle actual words differently from other kinds of failure, e.g., so you can print a more specific error message, then you can check isalpha inside the except clause. Print(type(userGuess), "after int failed") Print(type(userGuess), "after int succeeeded") If you want to know if a string is a valid integer, just call int on it, and use a try/ except to handle the case where it isn't: def validateInput(): That means you're still going to treat, say, "Hello!" as a number, because it has at least one non-letter. userGuess.isalpha() only tells you that the guess is made entirely of letters. Second, the way you're approaching this is wrong. ValueError: invalid literal for int() with base 10: '4.3'įirst, why do you want to convert the float string to an integer? Do you want to treat 4.7 as meaning the user has guessed 4? Or 5? Or a legal but automatically-invalid guess? Or as actually the value 4.7 (in which case you don't want integers at all)? Or…? Traceback (most recent call last):įile "C:\\*******.py\line 28, in validateInput Here's the error I'm getting if I use 4.3 (or any float) as input. Print(type(userGuess), "at 'isalpha() = True'") Print("Please enter whole numbers only, no words.") Print(type(userGuess), "at 'isalpha() = False'") UserGuess = input("Please enter a number from 1 to 100.

float to convert string to number python

Here's the function from my main program. As I said I'm on about day 3 of this coding thing so try to be understanding of my little knowledge. I can't get it to convert the float number over to an integer. I'm having trouble when I put in a float number.

#FLOAT TO CONVERT STRING TO NUMBER PYTHON HOW TO#

I've figured out how to weed out alphabetic characters, so I can convert the numbers into an integer. So that only integers are accepted as input. Just trying to write a simple number guess game, but also do input validation.

float to convert string to number python

I'm new to the whole coding thing.so here goes.






Float to convert string to number python