List index out of range int(sys.argv[1]) | Sololearn: Learn to code for FREE!

0

List index out of range int(sys.argv[1])

Hi! I try to run this simple code but have an error in this line: int(sys.argv[1]) Error: List index out of range How can i fix that? Anyone can help me? import sys import random stake = int(sys.argv[1]) goal = int(sys.argv[2]) trials = int(sys.argv[3]) bets = 0 wins = 0 for t in range(trials): # Run one experiment. cash = stake while cash > 0 and cash < goal: # Simulate one bet. bets += 1 if random.randrange(0, 2) == 0: cash += 1 else: cash -= 1 if cash == goal: wins += 1 Print(str(100 * wins//trials) + '% wins') Print('Avg # bets: ' + str(bets//trials))

4/10/2021 5:57:26 AM

AmirHossein RahmanParvar

5 Answers

New Answer

+3

Try to check length of `sys.argv` before proceeding with <stake>, <goal>, and <trials>. It would be better if you also verify whether those values were convertible to `int` after checking for their availabilty..

0

How should I do that? (Im beginner)

0

`len( sys.argv )` should return number of elements in `sys.argv`

0

It still has problem Can you write corrected line of those parts? I really confused

0

stake, goal, trials = 0, 0, 0 if len(sys.argv) > 2: if sys.argv[1].isdigit(): stake = int(sys.argv[1]) if sys.argv[2].isdigit(): goal = int(sys.argv[2]) if sys.argv[3].isdigit(): trials = int(sys.argv[3]) # perform additional validation for <stake>, <goal>, <trials> # as necessary