Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
Issue converting to string to integer.
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="alex23, post: 5096905"] When you were presented the 'Start' prompt, you hit Enter, which causes `input` to return an empty string. As it's passed directly into `int`, which requires a valid string-representing-a-number, you get the ValueError traceback, which shows you the failing input it received: '' This doesn't happen in your original code, because your condition `if start:` will fail on an empty string, and not try to turn it into an int. You don't want to wrap your `input` with an `int`. You want to test the return result from `input` to ensure it can be coerced: start = input("\nStart: ")) if start and start.isdigit(): start=int(start) ... else: start='' # set start to empty string so the while loop repeats Here we check that all of the characters in the string `start` are actually numbers before coercing. This is known as the "Look Before You Leap" (LBYL) approach. Another approach is to catch the ValueError exception: start = input("\nStart: ")) try: start = int(start) except ValueError: start = '' if start: .... This is known as "Easier to for Ask Forgiveness than Permission" (EAFP). They both have their advantages. try/excepts tends to be quicker if few exceptions are called, while an if/else will test every time, although at this point it's not something you need to overly concern yourself with. Go with whichever is easiest for you to understand & extend. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
Issue converting to string to integer.
Top