Python list index is out of range error - python

I've been tasked with making a Quiz app for a school project. It's meant to ask the user how many questions they want, and they then enter all of the Q&A's. Once finished, someone will then take the test.
The problem is, I'm getting an IndexError from the results function. This function is supposed to compare the test answers with the user's answers and print out a score.
def results(testAnswers, userAnswers):
score = 0
for i in range(0, len(answers)):
if testAnswers[i].lower().strip() == userAnswers[i].lower().strip():
score += 1
print("\nResults: You got " + str(score) + " out of " + str(len(answers)) + "!")
Does anyone know how I can fix this problem?

Your problem is here:
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
if user_answers[n] != answer_list[n]:
n += 1
Lets say times is 10, and n is 9, it executes, and n+=1 makes it 10. Most likely, you have 10 elements in the array (note 10 is an example), and now user_answers[10 raises an exception, as the valid varles are 0..9
To fix this issue, use elif:
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
elif user_answers[n] != answer_list[n]:
n += 1
Alternate approach is to get rid of the else clause altogether,
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
Note that there are quite a few places you could optimize the code, but I am just going to leave the answer here, and let you figure other things out yourself.

Perhaps copying your code into this site went wrong, but regardless the code is not correctly formatted here which makes it very difficult to read.
regardless, its clear that you are indexing into a list to a point that doesn't exist. to help track down this error, add this line after you start your while loop:
print 'n %s, times %s, user_answers %s, answer_list %s' % (n, times, user_answers, answer_list)
then run the program and paste the output of the program into your question (but first please correct the indenting)

Due to an unknown reason, the testAnswers and userAnswers weren't in equal length. The lesson here is to always make sure they are the same length.
A simple if-statment can prevent the entire error.
if len(answers) != len(userAnswers):
return

Related

Why is infinite inputting of a variable happening in Python?

num = int(input())
evenCounter = 0
while num != 0:
if num % 2 == 0:
evenCounter += 1
print(evenCounter)
Maybe this is sort of silly question, but I really can't figure out why does inifite input of the variable happen here. The console just keep asking me to write in a number for some reason.
I guess you get it wrong, it asks user input just once, and then it's stuck in a while loop, and you think that it's asking user anther input. To check it just add some text in input('add some text here: ' ) and you'll see that input is called just once.

Python progroam, Exclude Groups

kicked = 0
def calculate():
room = 0
global kicked
N = input("Write the number of groups\n")
M = input("Write the size of the groups, separated with space:\n").split()
for elem in M:
if room+int(elem)<int(N)+1:
room += int(elem)
else:
kicked += 1
while True:
try:
calculate()
print(kicked, "groups did not fit")
break
except:
print("An exception occurred, try again:\n")
Mainly I need help to explain my for loop.
secondly I can't use a splitter input on my first input, why?
Transforming the previous comment into an answer, and adding some optimization hints that would not fit in a comment:
Asking for help "to explain my for loop" is a bit unusual - it's your loop, you should know what it does :D Anyhow it basically checks if the sum of all elements in M insofar is still less than or equal to N; if not it "kicks" every remaining elements. Not the most efficient way to do that, but it works. For the second question: you surely can use split() on your first input, but you will get a list, not a single value - so you will need to do something like int(N[0]) to get the number.
Optimizations:
casting a string to an int is not particularly slow, but there is no need to repeat the same operation many times. So let's convert N to int once and for all:
N = int(input("Write the number of groups\n"))
for the same reason, let's convert each elem to int once, not twice, and while we're here let's test for less or equal instead of adding 1 and testing for less than (this last point will only give a very slight improvement but improves readability):
for elem in M:
e = int(elem)
if room + e <= int(N):
room += e
finally once we kick a group there's no need to continue looping - we are kicking everything else. So let's compute how many groups we are kicking and exit the loop:
for i,elem in enumerate(M):
e = int(elem)
if room + e <= int(N):
room += e
else:
kicked = len(M) - i
break

Creating a game where the computer guesses a value through inputs of <,> or =

I am trying to create a game where i think of a number in my head. And then the computer guesses the number through me telling it if its guess is too low or high.
This is what I've come up with but i am pretty lost tbh.
maxguess = 100
minguess = 1
count = 0
print("Think of a number between {} and {}".format(minguess,maxguess))
def midpoint(maxguess, minguess) :
z = ((maxguess + minguess)/2)
def guessing(x) :
print("Is you number greater (>) , equal (=) ,or less (<) than" ,z,)
print("please answer <,=, or >! >")
x = input()
if x == (">") :
minpoint = z
count += 1
continue
elif x == ("<") :
maxpoint = z
count += 1
continue
elif x == ("=") :
print ("I have guessed it!")
count += 1
break
print("I needed {} steps!".format(count))
Purposely not a complete solution, but some hints for you:
I'd recommend avoiding the global variables like count, maxguess, and minguess. Instead, make a function that holds all these variables.
Change your midpoint function to return z instead, then call it inside your guessing function.
Your continue and break functions would need to be inside a for or while loop. Since you aren't sure how many iterations you need to guess the number, I think a while loop would make sense here
Your functions are never run. On a style point, bring all your 'main' statements down to the bottom so they're together. After the prompt to think of a number, you need to call the guessing() function. When you call it, you should pass the minguess and maxguess values to it.
I can see what you're trying to do with the if...elif statements, but they need to be in a while True: block. So should the three statements preceding them so the script repeatedly asks for new advice from you.
Either bring the content of the midpoint() function into guessing() or make it return the value of z.
You also offer the user a choice of '>1' but don't handle it - and you don't need it as far as I can tell.
You never use minpoint or maxpoint - and you dont need them. Call the midpoint function instead and pass it the appropriate values, e.g., if '>', z = midpoint(z, maxguess).
Also, you're going to spend forever trying to get it to guess as you are using floats. Make sure everything is an integer.
Finally, you should add some code to manage input that isn't expected, i.e., not '<', '>' or '='.
Good luck!
minguess=1
maxguess=100
z=50
count=0
print("Think of a number between 1 and 100")
condition = True
while condition:
z=((maxguess + minguess)//2)
print("Is your number greater (>) , equal (=) ,or less (<) than" ,z,)
print("Please answer <,=, or >! >")
x = input()
if x == (">"):
minguess=z
count += 1
elif x == ("<") :
maxguess=z
count += 1
elif x == ("=") :
print ("I have guessed it!")
count += 1
condition=False

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0

Ending a while loop with a specific input

I have attempted to search for similar problems, but have come up short. I'm attempting to get a while loop to stop upon the input 'done'. No matter what I do or how I format it, it either won't stop the loop, or it prints the value I have assigned to 'done'. If I run it without an assignment it throws a 'NameError: name 'done' is not defined'. If I assign a value to it, it won't end the loop. I am not asking for code optimization or help with anything else, but I would truly appreciate it if someone could explain why this is happening.
Counter1 = 0
Counter2 = 0
Counter3 = 0
Counter4 = 0
n = 0
while True: #Begins a loop that runs until manually ended.
n = input("Enter desired scores, and type done when complete: ")
if n == "done": #Closes the loop if given this input.
break
else:
n = int(n) #changes input to an integer
if n >= 0 and n <= 25: #increments the counters depending on the input
Counter1 = Counter1 + 1
elif n > 25 and n <= 50:
Counter2 = Counter2 + 1
elif n > 50 and n <= 75:
Counter3 = Counter3 + 1
else:
Counter4 = Counter4 + 1
You're using Python 2. input immediately tries to convert your input into a Python type, which is dangerous and causes problems like the one you are experiencing. Use raw_input instead.
In other words, when you type "done", input tries to eval* it, comes up with a non-existent variable named "done", and bails out complaining. If you use raw_input instead, it will give you a string, which you can properly cast into a different type as desired, or as in your case, leave it alone since a string is what you want.
* This is about JavaScript but eval appears in many programming languages.

Categories