Posts: 230
Threads: 39
Joined: Mar 2020
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, ")")
Posts: 2,953
Threads: 48
Joined: Sep 2016
Oct-26-2022, 06:31 PM
(This post was last modified: Oct-26-2022, 06:34 PM by wavic.)
>>> "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!')
Posts: 1,838
Threads: 2
Joined: Apr 2017
Catch the exception thrown by int ? From memory, might be a ValueError but that's easily checked.
Posts: 1,145
Threads: 114
Joined: Sep 2019
Oct-26-2022, 06:49 PM
(This post was last modified: Oct-26-2022, 06:49 PM by menator01.)
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)
Posts: 6,806
Threads: 20
Joined: Feb 2020
Oct-26-2022, 07:35 PM
(This post was last modified: Oct-26-2022, 08:36 PM by deanhystad.)
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.
Posts: 453
Threads: 16
Joined: Jun 2022
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
Posts: 230
Threads: 39
Joined: Mar 2020
Posts: 230
Threads: 39
Joined: Mar 2020
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 ?
Posts: 6,806
Threads: 20
Joined: Feb 2020
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: "
Posts: 230
Threads: 39
Joined: Mar 2020
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 ?
|