-2

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")
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 6
    Welcome to Stack Overflow! Please convert the screenshot of code to formatted code in your question. – Logan Bertram Jan 29 '19 at 16:16
  • 3
    on which line does code crash – Talha Israr Jan 29 '19 at 16:17
  • 1
    The pythonic way to do that would be to simply try it and catch any exception, instead of double checking before attempting it. I.e. `try: a = int(a) except ValueError: # ask user again`. – deceze Jan 29 '19 at 16:20
  • @TalhaIsrar it returns " Traceback (most recent call last): File "zl.py", line 14, in a = int(input("podaj liczbę:")) ValueError: invalid literal for int() with base 10: 'g' " when i type g – Kamil Kołodziej Jan 29 '19 at 16:21
  • Its a simple error as you are trying to convert "g" which is a string to an integer which gives a value error – Talha Israr Jan 29 '19 at 16:22
  • @TalhaIsrar i know, thats why i'm trying implement isdigit. if it will detect its not a digit it'll just tell that you have to input digit – Kamil Kołodziej Jan 29 '19 at 16:23
  • Well, that error message you mention in the comment relates to code which is different from that in your post. Please check again which version of the code you are actually using. – mkrieger1 Jan 29 '19 at 16:23
  • @deceze sorry, but im newbie, could you be more specific where i should put this code? also, if i put in where i have a = int(a) it still gives me same error – Kamil Kołodziej Jan 29 '19 at 16:24
  • @KamilKołodziej the way you are running your code is wrong. If you are using isdigit then why are you converting to int a = int(input("podaj liczbę:"))? – Talha Israr Jan 29 '19 at 16:25
  • @TalhaIsrar `cause it dont want to compare input if it's not a int as the generated number is. so i thought that is i convert it it will solve a problem – Kamil Kołodziej Jan 29 '19 at 16:29
  • 1
    Of course it wont solve the problem instead it will create a new problem. if input is not an integer code will crash – Talha Israr Jan 29 '19 at 16:30

6 Answers6

2

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")
0

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

Nexaspx
  • 371
  • 4
  • 20
0

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')
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Well, that sounds interesting. I'm a newbie so, could you explain to me what do you mean by ValueError? i'm opening a code in powershell so shall i just copy there a error that occurs? – Kamil Kołodziej Jan 29 '19 at 16:44
  • You'll want to learn about handling exceptions: https://docs.python.org/3/tutorial/errors.html – deceze Jan 29 '19 at 16:46
0
# 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.
0

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")
ABHAY KOTAL
  • 153
  • 3
  • 13
-1

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)
blues
  • 4,547
  • 3
  • 23
  • 39