Python Forum
Beginner question: help ensuring input is a number - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Beginner question: help ensuring input is a number (/thread-7152.html)



Beginner question: help ensuring input is a number - ycrad - Dec-23-2017

Hello, I am very new to programming - so please excuse the incredibly beginner question.

I have been trying to a write a couple of lines of code and am struggling to make sure that the input is a number (either int or float).

I have looked online, and have struggled to execute the suggestions of using try/except, while and .isdigit(). I am sure that it is probably a grossly easy question, but I can't seem to figure it out. Wall

I am using Python 3.6.3.

Amongst others, I have written the below:

odds_text = ("The number is ")

odds_input = input("Enter a number: ")
strip_input = odds_input.strip()

while str(strip_input): # Trying to ensure that the input was not a string.
    print("Sorry, please enter a valid number")
    break
else:
    print(odds_text.format(odds=strip_input))
Thanks for any help! Smile


RE: Beginner question: help ensuring input is a number - ezdev - Dec-23-2017

ck = ""
while type(ck) == str:
    odds_text = ("The number is ")
    odds_input = input("Enter a number: ")
    strip_input = odds_input.strip()
    try:
        ck = float(strip_input)
    except:
        print("Sorry, please enter a valid number") ; ck = ""



RE: Beginner question: help ensuring input is a number - snippsat - Dec-23-2017

Doing unnecessary stuff there ezdev.
No need to check type,and is same code use try/except(should not be bare).

Catch the error(ValueError) if input need a integer,and give a message to try again.
If use function can use return,the no need to break out.
Function will only return a number, int(input(' ')) or float(input(' '))
def foo():
    while True:
        try:
            odds_input = int(input('Enter a number: '))
            return odds_input
        except ValueError:
            print('Sorry please enter a valid number,try again')

print(foo())