Python Forum
while + if + elif + else combination
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while + if + elif + else combination
#1
What is wrong with this code?? If I input a number it says I get 'That is not a number'. Why?

while True:
    text = input('Number (or \'Quit\' to exit): ')
    if text == 'Quit':
        print('...exiting program')
        break
    elif text.isnumeric == True :
            print(int(text) + 2)
    else:
            print('That is not a number', end = '\n')
Thanks

Haha, I figured it out. It's meant to be is.numeric()
Reply
#2
Your elif line has a couple of problems. First of all, you are comparing the method isnumeric itself to true, not the result of isnumeric. You would want to call isnumeric (text.isnumeric()). Second, isnumeric is going to be True for a lot of things that int is not going to be able to handle. The isdigit method works better with in, but only for positive numbers. Negative numbers that int can handle come back False from isdigit. Finally, you should not compare to True, the conditional already checks if it's True. So better would be:

elif text.isdigit():
Even better would be a try/except block:

try:
    print(int(text) * 2)
except ValueError:
    print('That is not a number') # '\n' is the default for end, you don't need to add it explicitly.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Group List Elements according to the Input with the order of binary combination quest_ 19 6,235 Jan-28-2021, 03:36 AM
Last Post: bowlofred
  Checking if the combination of two keys is in a dictionary? mrsenorchuck 6 3,773 Dec-04-2019, 10:35 AM
Last Post: mrsenorchuck
  Whats the right way to refactor this Big if/elif/elif ? pitosalas 1 2,214 Jul-28-2019, 05:52 PM
Last Post: ichabod801
  how to get all the possible permutation and combination of a sentence in python sodmzs 1 4,120 Jun-13-2019, 07:02 AM
Last Post: perfringo
  Is there a datepicker which can be used in combination with the python library urwid? AFoeee 5 5,480 Nov-18-2018, 08:54 PM
Last Post: AFoeee
  A combination of Python and MySql xgrzeniu 2 3,926 Mar-28-2018, 06:50 AM
Last Post: xgrzeniu

Forum Jump:

User Panel Messages

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