Eleuin
Eleuin

Reputation: 21

Python - Simple While loop with IF statements

I am trying to make a script to check if an argument was entered. If an argument was entered it uses that number for the timer, if no argument was entered, then by default, the timer should equal 3.

This while loop will count down from the given number & print each value as it counts down. When it gets to the end it will output 'blast off!'

#!/usr/bin/env python3

import sys

timer = int(sys.argv[1])

while timer != 0:
    if len(sys.argv[1]) == 0:
        timer = 3

    elif len(sys.argv[1]) == int(sys.argv[1]):
        timer = int(sys.argv[1])

    print (timer)
    timer = timer - 1

print ('blast off!')

My homework checking script gives me an error of IndexError: list index out of range - related to the first timer = int(sys.argv[1])

I am not sure how exactly I am supposed to "convert an empty string into an integer"

Thank you

Upvotes: 2

Views: 580

Answers (3)

shrewmouse
shrewmouse

Reputation: 6050

I'm guessing that your script is called without an argument which will fail because len(sys.argv) == 0.

If the user doesn't specify a value then set timer to whatever.

import sys

##################
if len(sys.argv) > 1:
    timer = int(sys.argv[1])
else:
    timer = 0
##################


while timer != 0:
    if len(sys.argv[1]) == 0:
        timer = 3

    elif len(sys.argv[1]) == int(sys.argv[1]):
        timer = int(sys.argv[1])

    print (timer)
    timer = timer - 1

print ('blast off!')

Or even better:

try:
    timer = int(sys.argv[1])
except:
    timer = 0

Upvotes: 0

townie
townie

Reputation: 322

You are attempting to index into a position in the list that does not exist and getting an IndexError: list index out of range.

Lets call your file countdown.py.

When you run python3 countdown.py then sys.argv == ['countdown.py'].

If you ran python3 countdown.py 5 then sys.argv == ['countdown.py', 5]

Would recommend looking into the argparse library as this is the pythonic way to parse arguments from the command line.

For example your code would look like this: #!/usr/bin/env python3

import argparse 


def countdown(timer):
    [print(tick) for tick in reversed(range(1, timer+1))]
    print('blast off!')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Countdown to blast off!')
    parser.add_argument('timer', type=int, nargs='?', default=3)

    args = parser.parse_args()

    countdown(args.timer)

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994599

Check that you actually have an argument:

timer = int(sys.argv[1]) if len(sys.argv) >= 2 else 3

Upvotes: 1

Related Questions