My code for now works as desired where the user can input a level 1-3 depending on how hard they would like it to be (1-3 being the amount of digits the numbers will have in the math equation), and then must solve math equations. Those math equations will output EEE if the answer is incorrect and everything works as planned if you correctly answer the question as it exits the function and adds one total_correct_answers variable at the bottom, then will prompt you with another equation. However, if you input an incorrect answer and then a correct answer, you will just be prompted with the same question over and over again without the try loop being truly broken out of and total_correct_answers not being incremented positively by 1. The incrementation block of code is at lines 61-65, and the equation code is lines 30-49.
import random
def main():
ten_questions()
def get_level():
while True:
try:
level_input = int(input("Level: "))
if level_input in [1,2,3]:
return level_input
except:
pass
def integer_generator(level):
if level == 1:
x = random.randint(0,9)
y = random.randint(0,9)
elif level == 2:
x = random.randint(10, 99)
y = random.randint(10, 99)
else:
x = random.randint(100, 999)
y = random.randint(100, 999)
return x, y
def question_generator(x, y):
real_answer = x + y
wrong_counter = 0
while True:
try:
answer_given = input(str(x) + " + " + str(y) + " = ")
if int(answer_given) == real_answer:
if wrong_counter == 0:
return True
elif int(answer_given) == real_answer and wrong_counter != 0:
break
else:
while wrong_counter < 2:
print("EEE")
wrong_counter +=1
break
else:
print(str(x) + " + " + str(y) + " = " + str(real_answer))
print("False, that was last attempt")
break
except:
print("EEE")
pass
def ten_questions():
num_of_questions = 0
total_correct_answers = 1
my_level = get_level()
correct_answers = question_generator(*integer_generator(my_level))
while num_of_questions <= 8:
question_generator(*integer_generator(my_level))
num_of_questions +=1
if correct_answers == True:
total_correct_answers +=1
print("Score: " + str(total_correct_answers))
if __name__ == "__main__":
main()
Because of your line 36:
if int(answer_given) == real_answer: happens when someone answers correctly, wether they are right or wrong. So it enters the if, and then faces if wrong_counter == 0: which discards wrong answers. So just replace those two lines with if int(answer_given) == real_answer and wrong_counter == 0: and you are good to go.
I'm taking CS50 Introduction to Programming with Python. I have problem with PSet4 (Little Professor). I don't have any problem while running, but when check50 running it keeps giving this error: "Little Professor accepts valid level timed out while waiting for program to exit." While I’m manually running the program, it accepts any level value lower than 4. But the check50 says otherwise. Here is my code:
import random
def main():
try:
level = input("Level: ")
first, second = get_level(level)
game_on(first, second, 0, 2, 0, level)
except WrongInputError:
main()
def get_level(x):
try:
x = int(x)
if 0 < x < 4:
first = generate_integer(x)
second = generate_integer(x)
return first, second
else:
raise WrongInputError
except ValueError:
raise WrongInputError
class WrongInputError(Exception):
"""You entered something wrong, try again """
def generate_integer(level):
if level == 1:
integer = random.randrange(10)
return integer
elif level == 2:
x = str(random.randrange(1, 10))
y = str(random.randrange(10))
integer = int(x + y)
return integer
elif level == 3:
x = str(random.randrange(1, 10))
y = str(random.randrange(10))
z = str(random.randrange(10))
integer = int(x + y + z)
return integer
def game_on(x , y, count, lives, score, level):
game_set = [x, y]
try:
if count < 10:
calculation = int(input(f"{x} + {y} = "))
count += 1
if calculation == sum(game_set):
score +=1
first, second = get_level(level)
game_on(first, second, count, 3, score, level)
elif calculation == sum(game_set):
print("EEE")
if lives > 0:
lives -= 1
count -= 1
game_on(x, y, count, lives, score, level)
elif lives == 0:
print(f"{x} + {y} = {sum(game_set)}")
first, second = get_level(level)
game_on(first, second, count, 2, score, level)
else:
print(f"Score: {score}")
except ValueError:
print("EEE")
if lives > 0:
lives -= 1
game_on(x, y, count, lives, score, level)
elif lives == 0:
print(f"{x} + {y} = {sum(game_set)}")
first, second = get_level(level)
game_on(first, second, count, 2, score, level)
if __name__ == "__main__":
main()
main()
import sys
import random
def main():
num = get_level()
errors = 1
score = 0
for i in range(10):
x = generate_integer(num)
for j in range(1):
y = generate_integer(num)
answer = x + y
equation = input(f"{x} + {y} = ")
if int(equation) == answer:
score += 1
while int(equation) != answer:
errors += 1
print("EEE")
equation = input(f"{x} + {y} = ")
if errors >= 3:
print(answer)
sys.exit("Score: " + str(score))
print("Score: " + str(score))
# prompt for level and reprompt if needed
def get_level():
levelChoice = input("Level: ")
if levelChoice.isalpha() or int(levelChoice) <= 0 or int(levelChoice) > 3:
input("Level: ")
else:
levelChoice = int(levelChoice)
for i in [1,2,3]:
if levelChoice == i:
return levelChoice
# generate int from level choice
def generate_integer(level):
try:
if level == 1:
return random.randint(0, 9)
elif level == 2:
return random.randint(10, 99)
elif level == 3:
return random.randint(100, 999)
except:
raise ValueError
if __name__ == "__main__":
main()
I am trying to increase the correct answer count by 1 every time the users answer is correct. However, when parsed into the display_result() function, the correct function displays "0 correct"
I haven't been able to get this working no matter how I try to wiggle around it, so any help is really appreciated.
code removed for academic integrity
If the user has answered 1 of 3 questions correctly, I expect the answer to be "You have answer 1 questions out of 3 correctly."
Currently, it would display you have answered 0 questions out of 3 correctly"
In menu_option() you never modify count, so it stays at 0. Two simple fixes. Change to:
count = check_solution(user_solution, real_solution, count)
return count
Or just
return check_solution(user_solution, real_solution, count)
One other thing I noticed: in get_user_input() you need to return the result of the recursive calls:
else:
print("Invalid input, please try again")
return get_user_input()
There are a number of problems:
you are doing correct = menu_option(option, correct) when instead you should be accumulating the correct scores like correct +=
in the menu_option you are never assigning to count, I presume it should be count = check_solution(...)
you shouldn't do return option for index == 5 because that will add to the correct.
Finally the code run as I expected(python3.6+ is required):
#!/usr/bin/env python3
import random
def get_user_input():
while True:
try:
index = int(input("Enter your choice: "))
if 0 < index < 6:
return index
except ValueError:
print("Invalid input, should be Integer.\n")
else:
print("Invalid input, please try again")
def get_user_solution(problem):
while True:
print("Enter your answer")
user_solution = input(f"{problem} = ")
try:
return float(user_solution)
except ValueError:
print("Invalid input, should be float\n")
def check_solution(user_solution, solution, count):
if user_solution == solution:
print("Correct.")
return count + 1
else:
print("Incorrect.")
return count
def menu_option(index, count):
first_num = random.randrange(1, 21)
second_num = random.randrange(1, 21)
if index == 1:
problem = f"{first_num} + {second_num}"
real_solution = first_num + second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 2:
problem = f"{first_num} - {second_num}"
real_solution = first_num - second_num
print(real_solution)
user_solution = get_user_solution(problem)
return check_solution(user_solution, real_solution, count)
if index == 3:
# blah blah blah, repeated code but removed for neatness
pass
if index == 5:
option = 5
return option
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct")
print("Your score is 0.0%")
else:
percentage = round(correct / total * 100, 2)
print(
f'You answered {total} questions with {correct} correct.\n'
f'Your score is {percentage}%'
)
def display_intro():
pass
def display_menu():
pass
def display_separator():
print('-'*20)
def main():
display_intro()
display_menu()
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
if __name__ == "__main__":
main()
print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
IndexError: tuple index out of range
is the error that I am getting. I am currently writing a python program for tictactoe. moves is equal to ['','','','','','','','','']. Would you like any other info?
I have so far, changed 789 in the row to 678 because indexes begin at 0. Nothing happening.
Next, I tried various other small changes, each of which either changed the error or just gave me the same error.
I also attempted to change formats and things, which did not go so well. I am running python 2.7(?), if that matters.
def draw(moves):
print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[3],"|",moves[4],"|",moves[5]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[0],"|",moves[1],"|",moves[2], "\n"
import time
import random
moves = ['','','','','','','','','']
player = ''
ai = ''
restart = ''
first = 19
whosfirst = 1
# Ok, so this is to decide the symbol for each person ---------------------------------------------------
def XorO(man, machine):
print 'Please select a symbol to represent you'
player = raw_input( "Please select \"X\" or \"O\"")
while player not in ('x','X','o','O'):
print "I'm sorry, I don't think I got that. Please try again"
time.sleep(1)
player = raw_input("Select \"X\" or \"O\"")
if player == 'x' or player == 'X':
print "X"
time.sleep(1)
print "Ok, then I'll be \"O\""
ai = 'o'
else:
print "O"
time.sleep(1)
print "Ok, then I'll be \"X\""
ai = 'x'
return player.upper(), ai.upper()
# This is for who is going first -----------------------------------------------------------------------
def first():
number = "a"
while number not in ('n','y',"no",'yes'):
number = raw_input("Do you want to go first? - ").lower()
if number == 'y' or number == 'yes':
return 1
elif number == 'n' or number == 'no':
return 0
else:
print "I'm sorry, I dont think that I understood you."
time.sleep(1)
print "Please select y, yes, n, or no"
#Here Comes the hard part -- drawing the board
def draw(moves):
print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[3],"|",moves[4],"|",moves[5]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[0],"|",moves[1],"|",moves[2], "\n"
def playerwon():
print "You won! Yay! Now try again"
def aiwon():
print "I won! Won't you try again?"
def playerfirst(player, ai, moves):
while win(player, ai, moves) is None:
moves = playermove(player, moves - 1)
moves[int(moves)] = player
draw(moves)
if win(player, ai, moves) != None:
break
else:
pass
Dmove = machine_move(player, ai, moves)
print "Nice moves! I'll try ",Dmove
moves[int(Dmove)] = ai
draw(moves)
q = win(player, ai, moves)
if q == 1:
playerwon()
elif q == 0:
aiwon()
else:
print "We tied =-("
time.sleep(2)
print "Let's have another go!"
def aifirst(player, ai, moves):
while not win(player, ai, moves):
Dmove = machine_move(man, machine, moves)
print "I'll take..." , Dmove
moves[Dmove] = machine
draw(moves)
if win(player, ai, moves) != None:
break
else:
pass
moves = playermove(player, moves)
moves[int(moves)] = player
draw(moves)
variable = win(player, ai, moves)
if q == 1:
playerwon()
elif q == 0:
aiwon()
else:
print "We tied =-("
time.sleep(2)
print "Let's have another go!"
def win(player, ai, moves):
ways = ((7,8,9),(4,5,6),(1,2,3),(7,4,1)(8,5,2),(9,6,3),(7,5,3),(9,5,1))
for i in ways:
if ways[i[0]] == ways[i[1]] == ways[i[2]] != empty:
winner = new[i[0]]
if winner == player:
return 1
elif winner == ai:
return 0
if empty not in new:
return 'TIE'
if empty not in new:
return 'TIE'
return None
def playermove(player, moves):
moves = raw_input("Where would you like to place your symbol?")
while True:
if moves not in ('0','1','2','3','4','5','6','7','8'):
print "Sorry, I don't think that's a valid spot... Try again"
moves = raw_input("Where would you like to place your symbol ")
elif moves[int(moves)] != empty:
print "Sorry, I think there's somehing already there..."
moves = raw_input("Where would you like to place your symbol?")
else:
return int(moves)
def aimove(player, ai, moves):
bestmoves = [5, 7, 9, 1, 3]
blank = []
for i in range(0,9):
if moves[i] == empty:
blank.append(i)
for num in blank:
moves[i] = ai
if win(man, ai, moves) is 0:
return i
moves[i] = empty
for num in blank:
moves[i] = man
if win(man, ai, moves) is 1:
return num
moves[i] = empty
return int(blank[random.randrange(len(blank))])
def display_instruction():
print "Welcome to PMARINA's TicTacToe v 1.1.1 ..."
print "In order to place your symbol, just press the corresponding key on your numpad."
print "If you do not have a numpad, then please note down the following arrangement"
print "7 | 8 | 9"
print "-----------"
print "4 | 5 | 6"
print "-----------"
print "1 | 2 | 3"
print "Good Luck, and don't forget to do the most important thing:"
time.sleep(2)
print "HAVING FUN!!"
time.sleep(2)
def letsgo(player, ai, moves):
display_instruction()
print "so lets begin.."
moves = XorO(player, ai)
player = moves[0]
ai = moves[1]
whosfirst = first()
if whosfirst == 1:
print "Ok, you are first!"
print "Lets go!"
draw(moves)
playerfirst(player, ai, moves)
else:
print "Ok, I'll be the first!"
print "So, lets start.."
draw(moves)
aifirst(player, ai, moves)
letsgo(player, ai, moves)
raw_input("Press enter to exit")
Line 14:
moves = ['','','','','','','','','']
Line 192:
moves = XorO(player, ai)
...
draw(moves)
You overwrote your initial declaration of moves, so ('X', 'O') is being passed to draw.
If moves is ['','','','','','','','',''] and the error message you're getting is:
IndexError: tuple index out of range
Then the error is not occurring on the line you say it is. moves is a list, not a tuple. And it does have indices up to 8. moves[9] would generate this error instead:
IndexError: list index out of range
The only tuple I see in the code is ways. Also you don't seem to initialize new before you use it in the function 'win'.
FYI, tuples are made using parentheses tup = (1, 2, 3, 4) while lists use brackets list = [1,2,3,4]. Tuples are also immutable, so you can't modify them later.