Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need some help here
#4
To be sure you get it:
  • while True means go forever. A while loop goes until the condition is False. If the condition is a literal True, it goes on forever.
  • text.strip() takes out whitespace that would confuse isdigit. isdigit() makes sure the remaining characters are all digits (0-9).
  • num = int(text) converts text to an integer and stores it in num. We can do this because it's only digits and whitespace. Otherwise we might get an error.
  • break gets out of the loop, because we have what we want.
As you note, it's not perfect, as it misses negative integers. I'm not usually interested in them either. You could solve that with a more complicated expression, or a try/except block.

while True:
    text = input('Enter a number, please: ')
    try:
        num = int(text)
        break
    except ValueError:
        print('Integers only, please.')
The try/except synatx tries the indented block of code. If any errors pop up, it goes to the except and sees if they match. ValueError is what you would get if you tried int('two') or int('2.718').
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
Need some help here - by Framble - Sep-16-2017, 08:48 PM
RE: Need some help here - by ichabod801 - Sep-16-2017, 09:26 PM
RE: Need some help here - by Framble - Sep-16-2017, 10:27 PM
RE: Need some help here - by ichabod801 - Sep-16-2017, 11:30 PM

Forum Jump:

User Panel Messages

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