Python Forum
how to make sure an input is from the wanted type
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to make sure an input is from the wanted type
#1
hey guys,
so as a continuation of the previous thread - and taking my own code (as it is easier for me to comprehend) , how do you make sure an input is from the desired type ? (in this case - integer),
suppose the type is a different kind - how is it being accompanied with a message (suppose - "please enter an integer kind of number") and re-asking for an input...

base code:

import random

RNumber = random.randint(1,10)

user_input = int(input("please guess a number between 0 and 10: \n"))

while user_input != RNumber:
    if user_input > RNumber:
        user_input = int(input("choose a lower number: \n"))
    elif user_input < RNumber:
        user_input = int(input("choose a higher number: \n"))

print("the number you chose is correct (", RNumber, ")")
Reply
#2
>>> "2.2".isnumeric()
False
>>> "22".isnumeric()
True
>>> "022".isnumeric()
True
>>> int('000022')
22
Also you can just try/except the user input:
try:
    user_input = int(input("please guess a number between 0 and 10: \n"))
except ValueError:
    print('Not an integer! Please try again!')
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Catch the exception thrown by int? From memory, might be a ValueError but that's easily checked.
Reply
#4
You could use a try block.

import random

RNumber = random.randint(1, 10)

while True:
    try:
        user_input = int(input('Guess a number\n>> '))
    except ValueError:
        print('Please use only whole numbers')
        continue
    else:
        if user_input > RNumber:
            print('Number is to high')
        elif user_input < RNumber:
            print('Number is too low')
        else:
            print(f'Congradulation! You guessed the number {RNumber}')
            RNumber = random.randint(1,10)
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#5
input() returns a str. The return type is str, always. Some strings can be converted to numbers, but they are still type str. This is not a "type" issue, it is a content issue. Does your string have the correct characters organized in the correct way to be interpreted as a number.

You can test the string to see if it can be converted to a number, but those tests are difficult to write. str.isnumeric() is not adequate. Pretty close, but fails for valid numbers.
print(float("1.54e5"), "1.54e5".isnumeric())
Output:
154000.0 False
It is far easier to perform the conversion and clean up the mess.
def string_to_number(number_string):
    """Return numeric equivalent of number_string"""
    try:
        return int(number_string, 0)
    except ValueError:
        pass  # Is it a float?

    try:
        return float(number_string)
    except ValueError:
        raise ValueError(f'"{number_string}" is not a numeric string')

for number_string in ("123", "0x7b", "0o173", "0b1111011", "123.0", "one two three"):
    number = string_to_number(number_string)
    print(number, type(number), number_string.isnumeric())
Output:
123 <class 'int'> True 123 <class 'int'> False 123 <class 'int'> False 123 <class 'int'> False 123.0 <class 'float'> False Traceback (most recent call last): File "...", line 9, in string_to_number return float(number_string) ValueError: could not convert string to float: 'one two three' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "...", line 14, in <module> number = string_to_number(number_string) File "...", line 11, in string_to_number raise ValueError(f'"{number_string}" is not a numeric string') ValueError: "one two three" is not a numeric string
This practice of trying to do something you expect to work, but catching exceptions raised if it doesn't, is very common in Python. Far more common that doing exhaustive testing in an attempt to prevent errors.
Reply
#6
I tend to use a custom function when checking any (and all) user input.

As a simple example:

def check_input(n):
    """check the user input for a valid number.
    if valid, return the number, otherwise return 'None'"""
    for number in n:
        if number.isnumeric():
            pass
        else:
            return None
    return n


user_input = check_input(input("Pick a number: "))
if user_input:
    print(f"You picked {user_input}")
else:
    print("Not valid.\nNumbers need to be whole (no decimal point)")

That function can be coded to return anything you choose (such as an error message) and do whatever checks you want, such as checking that a number is within a certain range.

Clearly, as is, the number being printed is a string object, but again, the function could return a int, or a float, or the object type can be changed after it has been returned; it's a matter of choice.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#7
Thank you everybody !
Reply
#8
i tried this:

import random

RNumber = random.randint(1,10)

try:
    user_input = int(input("please guess a number between 0 and 10: \n"))
except ValueError:
    print("you have typed an invalid input")

count = 1

while user_input != RNumber:
    try:
        if user_input > RNumber:
            user_input = int(input("choose a lower number: \n"))
        elif user_input < RNumber:
            user_input = int(input("choose a higher number: \n"))
    except ValueError:
        print("you have typed an invalid input")
    count += 1

print(f"the number you chose is correct {RNumber}\n")

print(f"you have guessed the right number in {count} times")
it works when in the first time i am asked to enter a number, and then after i choose some number - i type some string, it works okay,
but if right on the first time i'm prompted i enter a string - it gives the right output - but then also an error...
the output is this:
Output:
/home/tal/PycharmProjects/pythonProject1/venv/bin/python /home/tal/code/pycharm-community-2020.2.3/plugins/python-ce/helpers/pydev/pydevd.py --multiprocess --qt-support=auto --client 127.0.0.1 --port 42581 --file /home/tal/PycharmProjects/pythonProject2/experiment.py please guess a number between 0 and 10: you have typed an invalid input Traceback (most recent call last): File "/home/tal/code/pycharm-community-2020.2.3/plugins/python-ce/helpers/pydev/pydevd.py", line 1496, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "/home/tal/code/pycharm-community-2020.2.3/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/home/tal/PycharmProjects/pythonProject2/experiment.py", line 12, in <module> while user_input != RNumber: NameError: name 'user_input' is not defined Process finished with exit code 1
how come this is so ? is there a way to correct it ?
Reply
#9
Your loop depends on the user entering a number string, but your code does not force the user to enter a number string. If I enter "a" for the input, user_input is not defined.

I would change the layout and moved the initial guess inside the loop. Normally I would do this with a while loop, but since you are keeping track of guesses, I'm going to use a for loop.
import random
 
number = random.randint(1, 10)
prompt = "Enter a number from 1 to 10: "
for i in range(1, 100):
    try:
        # Verify the input
        guess = int(input(prompt))
        if not 1 <= guess <= 10:
            raise ValueError

        # To get here we know the user entered a number from 1 to 10
        if guess > number:
            prompt = "Choose a lower number: "
        elif guess < number:
            prompt = "Choose a higher number: "
        else:
            # To get here we know the user entered the correct number
            print(f"You guessed the correct number in {i} tries")
            break
    except ValueError:
        prompt = "Enter a number from 1 to 10: "
Reply
#10
okay thank you Dean,

i have a question for you, - i noticed that on lines 14 and 16 you used prompt = "Choose a lower number: " (and "higher" in line 16 accordingly) - how can one just put a variable and have its value printed out ? don't you have to use the print() method for that ?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to make input come after input if certain line inserted and if not runs OtherCode Adrian_L 6 3,356 Apr-04-2021, 06:10 PM
Last Post: Adrian_L
  Make the answer of input int and str enderfran2006 2 2,016 Oct-12-2020, 09:44 AM
Last Post: DeaD_EyE
  How to make input goto a different line mxl671 2 2,472 Feb-04-2020, 07:12 PM
Last Post: Marbelous
  Type hinting - return type based on parameter micseydel 2 2,513 Jan-14-2020, 01:20 AM
Last Post: micseydel
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 2,768 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  catch input type error mcmxl22 5 3,075 Aug-11-2019, 07:33 AM
Last Post: wavic
  Getting type from input() function in Python 3.0 leodavinci1990 7 3,781 Jul-29-2019, 08:28 PM
Last Post: avorane
  how i can check the input type? Firdaos 3 2,870 Dec-13-2018, 11:39 PM
Last Post: wavic
  How to make an input trigger the output once no matter how long input is high cam2363 3 3,266 Feb-05-2018, 01:19 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020