How to check every input for isdigit - python

I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")

I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")

If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html

The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')

# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.

In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")

You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)

Related

How to make a "while" loop using input from user?

Currently using 3.8.1.
I was wondering how I could make a while True: loop like in the example below, but using a number that the user inputted instead of a word (for example any number equal to or lower then 100 would print something different. I've looked on this website, but I couldn't understand the answers for questions similar to mine.
while True:
question = input("Would you like to save?")
if question.lower() in ('yes'):
print("Saved!")
print("Select another option to continue.")
break
if question.lower() in ('no'):
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
How about including less than / great than clauses in your if statements?
while True:
# get user input:
user_input = input("Would you like to save? ")
# convert to int:
number = int(user_input)
if number <= 100:
print("Saved!")
print("Select another option to continue.")
break
elif number > 100:
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
you need to extract the number from the input and then run your conditional evaluation of the inputed value.
while True:
input_val = input("Enter a #?")
try:
num=int(input_val)
except ValueError:
print("You have entered an invalid number. please try again")
continue
if num == 1:
print("bla bla")
elif num ==2:
print("bla bla 2")
else:
...
input takes the user's input and outputs a string. To do something with numbers, check if the string is numeric, cast it to an int and do whatever you want
while True:
answer = input("How many dogs do you have?")
if answer.isnumeric():
num_dogs = int(answer)
else:
print("Please input a valid number")
I think you maybe want a list instead of a tuple.
Could this work:
while True:
number = input("Enter a number?")
if int(number) in list(n for n in range(100)):
print("lower!")
elif int(number) in [100]:
print ("exact")
else:
print("higher")

How do you use an if statment to only except integers and give an invalid entry message?

I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.
I have tried to use just 'int' in an if statement to address all integers, but that is not working.
I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
This is the error that I'm getting. There may be some other mistakes in my code as well.
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
I always use this method to check if something is not an integer:
Python 3
if not round(guess) == guess: print("Do Stuff")
Python 2
if not round(guess) == guess: print "Do Stuff"
You need to do something like this:
play = True
while play:
guess = input("Guess a number between 1 and 5: ")
try:
number = int(guess)
except ValueError:
print("You need to input an integer.")
continue
if number < 1 or number > 5:
print("You need to input an integer between 1 and 5.")
continue
# ...
print("Your number was: " + guess)
play = False
When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.
>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'
To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.
The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.
Parse the user input as string to avoid ValueError.
guess = input("Guess a number between 1 and 5: ")
while not guess.isdigit() or int(guess) > 5 or int(guess) < 1:
guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")
guess = int(guess)
Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.
Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:
a = 2
isinstance(a, int)
Output:
>>> True

can we make this script shorter ?even odd checking

hi there i'm learning python
i like to know if this script can be better or shorter
import sys
g = 1
def trying():
q = input('enter (y or yes) to retry')
if not q == 'y' or q == 'yes':
return 0
while g == True:
try:
t = int(input('please enter an integer:'))
r = t % 2
if r == 0:
print('your number is even')
if trying() == 0:
g = 0
else:
print('your number is odd')
if trying() == 0:
g = 0
except ValueError:
print('sorry you need to enter numbers only')
If you want in shorter, here is my version..
while True:
try:
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
if input('Enter (y or yes) to retry: ') not in ['y', 'yes']: break
except ValueError:
print('Sorry you need to enter numbers only')
What you want here is a do-while loop. You can easily implement it by adding a break statement to a infinite while-loop. More on this topic can be found here.
Next thing, you have to add a try-except statement as there is a string to integer conversion is happening.
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
This statement will return "Your number is even" if the input is even else it will return "Your number is odd". This method is called python ternary operator.
Then you can wrap it with a print-function to print the returned string. Look here.
input('Enter (y or yes) to retry: ') not in ['y', 'yes']
This check whether the user input is not there in the given list. So if user input is neither "y" or "yes", while-loop will break.
Here is an example of how the code can be made simpler. Remember that code should rarely be repeated. In most cases, if you have repeating lines of code it can be simplified.
while True:
try:
t = int(input('please enter an integer:'))
if t % 2 == 0: print('your number is even')
else: print('your number is odd')
q = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'): break
except ValueError:
print('sorry you need to enter numbers only')
def trying():
question = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'):
return 1
return 0
while True:
try:
num1 = int(input('please enter an integer:'))
num2 = t % 2
if not num2:
print('your number is even')
else:
print('your number is odd')
if trying():
break
except ValueError:
print('sorry you need to enter numbers only')
You don't have to import sys in your program as you didn't used it and you don't have to. You don't have to store anything in a variable for a while loop. Just assigning True and breaking out will do. If you're looking for anything that is True (this includes an unempty list, string, and dictionaries; and numbers not equal to 0). You should make if var:. If the variable evaluates to True. The conditional block will be executed. This is a clearer syntax so it is recommended. Name your variables with words, not with letters. This will not make your code longer and it will make your code better.
This is all I can do with your code. If there is more, please state them.

Python: Continue if variable is an 'int' and has length >= 5

I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "

Python: How to check if a signed number is positive or negative or none?

Simply, I am entering a value, I want to determine whether the value is alpha or not. If it is not alpha, I want to check if it is a number or not. If it is a number I want to check if it is positive or negative.
I read a lot about checking a signed number like -50. There are two ways, we can use something like this:
try:
val = int(x)
except ValueError:
print("That's not an int!")
Which I think I do not need it here and I do not know where to put it in my code.
The other way is to use .lstrip("-+"), but it is not working.
amount = 0
while True:
amount = input("Enter your amount ===> ")
if amount.isalpha() or amount.isspace() or amount == "":
print("Please enter only a number without spaces")
elif amount.lstrip("-+").isdigit():
if int(amount) < 0:
print("You entered a negative number")
elif int(amount) > 6:
print("You entered a very large number")
else:
print(" Why I am always being printed ?? ")
else:
print("Do not enter alnum data")
What am I doing wrong ?
This is how you would integrate a try/except block:
amount = 0
while True:
amount = input("Hit me with your best num!")
try:
amount = int(amount)
if amount < 0:
print("That number is too tiny!")
elif amount > 6:
print("That number is yuge!")
else:
print("what a boring number, but I'll take it")
break # How you exit this loop
except ValueError:
print("Wow dude, that's like not even a number")
It does all the heavy lifting for you, as int() can process numbers with +/- automatically.
>>> amount = '-6'
>>> '-' in amount
True
>>> amount = amount.strip('-')
>>> amount.isdigit()
True
Check if the number is less than 0 or greater than 0 with < >

Categories

Resources