Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether the user input is a number [duplicate]

Tags:

python

I'm trying to compare a input that the user receives that checks if the input is actually a number. Here's what I have so far:

numstring = input("Choose a number between 1 and 10")

and then to compare I have it in a method like this:

def check(a):
   if int(a) == int:
       print("It's a number!")
   else:
       print("It's not a number!")

It always prints out that it's not a number, even though it is.

Goal of this program: I'm making a guessing game:

import random

numstring = input("Choose a number between 1 and 10")

def check(a):
    if int(a) == int:
        print("It's a number!")
    else:
        print("It's not a number!")

    if abs(int(a)) < 1:
        print("You chose a number less than one!")
    elif abs(int(a)) > 10:
        print("You chose a number more than ten!")
    else:
        randomnum = random.randint(1, 10)
        randomnumstring = str(abs(randomnum))
        if randomnum == abs(int(a)):
            print("You won! You chose " + a + "and the computer chose " + randomnumstring)
        else:
            print("You lost! You chose " + a + " and the computer chose " + randomnumstring)


check(numstring)

Thanks for any help! The actual code works, but it just fails at checking it.

like image 371
Some Guy Avatar asked Feb 07 '26 04:02

Some Guy


1 Answers

You can just use str.isdigit() method:

def check(a):
    if a.isdigit(): 
        print("It's a number!")
    else:
        print("It's not a number!")

The above approach would fail for negative number input. '-5'.isdigit() gives False. So, an alternative solution is to use try-except:

try:
    val = int(a)
    print("It's a number!")
except ValueError:
    print("It's not a number!")
like image 120
Rohit Jain Avatar answered Feb 09 '26 17:02

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!