My program keeps looping and I cannot figure out why - python-3.x

My program is continually looping and I would like to figure out why before I progress any further into the project it self. The programs purpose is to create a key from the alphabet that is used to decode/encode a message.
import random
def main():
userselection = "0"
print("This program allows you to create keys, econde plaintext, and decode ciphertext.")
while userselection != "4":
print("What would you like to do?")
userselection = input("1.create a key 2.encode a message 3.decode a message 4.quit > ")
if userselection == "1":
#selection 1 stuffs goes here
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = ""
letter = random.choice(alphabet)
elif userselection == "2":
#selection 2 stuffs
plaintext = plaintext.lower()
ciphertext = ""
for i in range(len(plaintext)):
alphabetposition = alphabet.find(plaintext[i])
if alphabetposition >= 0:
ciphertext = ciphertext + key[alphabetposition]
else:
ciphertext = cipertext + plaintext[i]
elif userselection == "3":
#selection 3 stuffs
print()
elif userselection != "4":
print("invalid selection")
if __name__ == "__main__":
main()

I think you need to take user input inside the while loop. Try this :-
import random
def main():
userselection = "0"
print("This program allows you to create keys, econde plaintext, and decode ciphertext.")
while userselection != "4":
print("What would you like to do?")
userselection = input("1.create a key 2.encode a message 3.decode a message 4.quit > ")
if userselection == "1":
#selection 1 stuffs goes here
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = ""
letter = random.choice(alphabet)
elif userselection == "2":
#selection 2 stuffs
plaintext = plaintext.lower()
ciphertext = ""
for i in range(len(plaintext)):
alphabetposition = alphabet.find(plaintext[i])
if alphabetposition >= 0:
ciphertext = ciphertext + key[alphabetposition]
else:
ciphertext = cipertext + plaintext[i]
elif userselection == "3":
#selection 3 stuffs
print()
elif userselection != "4":
print("invalid selection")
if __name__ == "__main__":
main()

While loop at wrong position. It looping as you set userselection = "0" after that before user input you checking the
while userselection != "4":
print("What would you like to do?")
I will suggest you should comments this lines and take rerun.

Related

Cannot get it to accept input

when input is asked, I type Rock it loops back as though i did not type the right input.
I've tried retyping the error checking but nothing is working. The only input it will accept is 'q'. Here is the code:
import random
user_wins = 0 #setting default score
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint(0, 2) #rock: 0 , paper: 1, scissors: 2
computer_pick = options[random_number] #using computer's pick from a random from the list to be stored.
print('Computer picked:', computer_pick + ".") #printing the result of computer's pick
if user_input == "rock" and computer_pick == "scissors": #setting win or lose conditions
print('Rock Crushes Scissors...You Win!')
user_wins += 1
elif user_input == "paper" and computer_pick == "rock":
print('Paper Covers Rock...You Win!')
user_wins += 1
elif user_input == "scissors" and computer_pick == "paper":
print('Scissors Cuts Paper...You Win!')
user_wins += 1
else:
print("You Lose")
computer_wins += 1
print("You won ", user_wins, "times.")
print("Computer won ", computer_wins, "times.")
print('Goodbye')
It's because you need to break the loop when input is in options, so the loop could be
while True:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
if user_input not in options:
continue
else:
break
Anyways, a better implementation could be creating the empty option and assign it if matches, so
answer = ''
while not answer:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
elif user_input in options:
answer = user_input
In you case try this code. You will need to have two while loops: one is for checking the input, the other is for continuing the game.
exit = False #this helps you to exit from the main while loop.
while not exit:
options = ['rock', 'scissors', 'paper']
user_input = ""
while True:
user_input = input('pls write paper, rock, scissors, or
q(quit) ').lower()
if user_input in options:
break
elif user_input == 'q':
exit = True
break
#do some calculations
# do some summary calculations and print them
I hope you will find it helpful)

Variable says it is False when run in the function, but then it reverts back to True

I am currently creating a tic-tac-toe game for a course. It has been going great, however, I have hit a roadblock. I am having trouble with the part when I want to check if a player has won or not, it is a function (called "game_over"). When I run the game, and if the "if" statement is met, it says "game_on = False". However, once the player while loop begins, it reverts back to True. Thus the game never stops.
game_on = True
player_ready = False
game_finish = False
turn = "Player1"
# THE BOARD
line1 = ["|", "___" , "|", "___", "|","___","|"]
line2 = ["|", "___" , "|", "___", "|","___","|"]
line3 = ["|", "___" , "|", "___", "|","___","|"]
list1 = ''.join(line1)
list2 = ''.join(line2)
list3 = ''.join(line3)
print(list1)
print(list2)
print(list3)
# FUNCTIONS AND THE GAME
Player1_character = "x"
def game_over(player,character):
if line1[1] == (f"_{character}_") and line1[3] == (f"_{character}_") and line1[5] == (f"_{character}_"):
game_on = False
print(f"Game Over, {player} won!game_on = {game_on}")
return
def print_character(numbers,char):
if numbers == 1:
line1[1] = (f"_{char}_")
if numbers == 2:
line1[3] = (f"_{char}_")
if numbers == 3:
line1[5] = (f"_{char}_")
if numbers == 4:
line2[1] = (f"_{char}_")
if numbers == 5:
line2[3] = (f"_{char}_")
if numbers == 6:
line2[5] = (f"_{char}_")
if numbers == 7:
line3[1] = (f"_{char}_")
if numbers == 8:
line3[3] = (f"_{char}_")
if numbers == 9:
line3[5] = (f"_{char}_")
list1 = ''.join(line1)
list2 = ''.join(line2)
list3 = ''.join(line3)
print(list1)
print(list2)
print(list3)
section = 0
# Tutorial Goes Here
while game_on == True:
# Selecting Players
while player_ready == False:
Player1_character = ""
Player1_character = input("Player1 choose your character 'x' or 'o': ")
Player2_character = "|"
if Player1_character == "x":
Player2_character = "o"
elif Player1_character == "o":
Player2_character = "x"
print(f"Player1 = {Player1_character} ||| Player2 = {Player2_character}")
print("LETS BEGIN!!!\n")
player_ready = True
#Starting game:
while turn == "Player1":
section = int(input(f"Player1's Turn: \nSelect where you want to put your '{Player1_character}'(1-9){game_on}: "))
print_character(section, Player1_character)
if game_on == False:
break
turn = "Player2"
while turn == "Player2":
section = int(input(f"Player2's Turn: \nSelect where you want to put your '{Player2_character}'(1-9){game_on}: "))
print_character(section, Player2_character)
game_over("Player2",Player2_character)
if game_on == False:
break
turn = "Player1"
See the Python Programming FAQ on the rules for using global variables in functions.
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

it shows"line 42, in <module> if input_ !='no': NameError: name 'input_' is not defined" when i giv no in first line.How can i correct it?

Its showing"line 42, in
if input_ !='no':
NameError: name 'input_' is not defined" error when i input 'no'
The code is :
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
input_=input(y+z+"?")
if input_ == "no":
return
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
How can i rectify it? (this is just a small part of the entire program but i think this should do...)
Variable input_ is initialised inside function rock_paper_scissors() which means outside of it (function scope) is undefined. So we need to put it inside function or make input_ global.
def rock_paper_scissors():
comp_score = your_score = 0
y, z = "This is a rock paper scissors game. ", "Do you wish to play"
x= ["rock", "paper", "scissors"]
input_=input(y + z + "?")
if input_ == "no":
return
else: # no need for: if input_ != "no"
a = input("Do you wanna play again?")
rock_paper_scissors()
Hope this helps.
Here is my take on it, still needs some work, it functional...
# Tested via Python 3.7.4 - 64bit, Windows 10
# Author: Dean Van Greunen
# License: I dont care, do what you want
####################################
# Some Defines
####################################
# imports
import random
# global vars
comp_score = 0
your_score = 0
input_ = ''
ai_input = ''
# strings
string_1 = 'This is a rockpaper scissors game.'
question_1 = 'Do you wish to play? '
question_2 = 'Enter your move: '
question_3 = 'Do you wanna play again? '
string_4 = 'Valid Moves: '
string_5 = 'Thank you for playing!'
string_6 = 'Scores: Player {0} V.S. AI {1}'
yes = 'yes'
no = 'no'
# vaild moves
moves = ["rock","paper","scissors"]
####################################
# Code Setup
####################################
def displayWinner(player_move_str, ai_move_str):
# Vars
winner = ''
tie = False
# Winner Logic
if player_move_str == ai_move_str:
tie = True
elif player_move_str == 'paper' and ai_move_str == 'rock':
winner = 'Player'
elif player_move_str == 'scissor' and ai_move_str == 'rock':
winner = 'AI'
elif player_move_str == 'rock' and ai_move_str == 'paper':
winner = 'AI'
elif player_move_str == 'scissor' and ai_move_str == 'paper':
winner = 'Player'
elif player_move_str == 'rock' and ai_move_str == 'scissor':
winner = 'Player'
elif player_move_str == 'paper' and ai_move_str == 'scissor':
winner = 'AI'
# display Logic
if tie:
print('It Was A Tie!')
else:
global your_score
global comp_score
if winner == 'AI':
comp_score = comp_score + 1
elif winner == 'Player':
your_score = your_score + 1
print(winner + ' Won!')
def start():
global your_score
global comp_score
print(string_1)
print(string_6.format(your_score, comp_score))
input_ = input(question_1)
if input_ == yes:
print(string_4)
[print(x) for x in moves]# make sure input is valid.
input_ = input(question_2)
ai_input = random.choice(moves) # let AI pick move
print('AI Picked: ' + ai_input)
displayWinner(input_, ai_input)
input_ = input(question_3) # Play Again?
if input_ == yes:
start() # Restart Game (Recursive Call)
else:
print(string_5) # Thank you Message
####################################
# Game/Script Entry Point/Function
####################################
start()
Thanks yall. Fixed my program. Now it goes like:
import time
import random
input_ =""
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
global input_
input_=input(y+z+"?")
if input_ == "no":
return
max_score=("Enter max score : ")
while True:
input_=input("Enter your choice among rock, paper and scissors ('stop' to
quit):")
if input_ not in x and input_!='stop'and input_ != 'enough':
print("Invalid answer. Are you blind? Pick one from the 3.")
continue
n = random.randint(0,2)
k=x[n]
if n<2:
if input_==x[n+1]:
your_score+=1
elif input_==k:
pass
else:
comp_score+=1
else:
if input_=="paper":
comp_score+=1
elif input_=="rock":
your_score+=1
elif input_=="scissors":
pass
else:
pass
if input_!="stop" and input_ != "enough":
print(3)
time.sleep(1.5)
print(2)
time.sleep(1.5)
print(1)
time.sleep(1.5)
print("Your choice : "+input_ +"\nComputers move : "+k)
elif input_=="stop" and input_=="enough":
input_=input("Play again?")
if (your_score == max_score or comp_score==max_score) or (input_=="stop"
or input_=="enough"):
print("Your score is : ",your_score)
print("AI's score is : ",comp_score)
break
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
if a =="yes":
rock_paper_scissors()
print("k.bye! \n :(")

Displaying output after adding item to list

This is my code:
import time,sys,random
wpm = 125
userName = ""
global mirror
mirror = False
global knife
knife = False
inventory = []
vial = False
trollHit = 0
playerHit = 0
axe = False
choice2 = False
kitchenAlready = False
def death():
sys.exit()
userInput = ""
def cantPerformAction(userInput):
if userInput == "e" or userInput == "u" or userInput == "w" or userInput == "s" or "t" in userInput:
slow_type("You can't perform that action.")
def checkDirection(userInput):
if any(char in userInput for char in 'nsewudt') == False:
return False
elif any(char in userInput for char in 'nsewudt') == True:
return True
#credit to 'bill gross' for ideas on the slow type
def slow_type(y): #slow typing to make it seem like the computer is typing
for x in y:
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(random.random( )*10.0/wpm)
print (' ')
def clear(): #clear the line so that another line of text can appear below it
print ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
#CROSSROADS: All directions lead to death except right. Player cannot turn back.
def crossroads():
slow_type("\n\nCrossroads")
slow_type("\n\nA crossroads is in front of you. There is a passage to the west, east, and north.")
global choice2
global choice
choice = None
choice2 = None
youBetterChoose = 0
while choice == None and choice2 == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput1 = userInput.lower().strip()
if userInput1 == "s":
clearingalready()
if userInput1 =="n":
slow_type("\n>You walk forward, determined... off a cliff. Tragic!")
death()
if userInput1 == "w":
slow_type("\nYou encounter a giant spider. Without a weapon, it easily tears you to shreds.")
death()
if userInput1 == "e":
fork()
if userInput1 == "d":
slow_type("You can't do down farther than the floor.")
if userInput1 == "u":
slow_type("You can't go that way.")
userInput = ""
def crossroadsalready():
slow_type("\n\nCrossroads")
global choice2
global choice
choice = None
choice2 = None
youBetterChoose = 0
while choice == None and choice2 == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput1 = userInput.lower().strip()
if userInput1 == "s":
clearingalready()
if userInput1 =="n":
slow_type("\n>You walk forward, determined... off a cliff. Tragic!")
death()
if userInput1 == "w":
slow_type("\nYou encounter a giant spider. Without a weapon, it easily tears you to shreds.")
death()
if userInput1 == "e":
fork()
if userInput1 == "d":
slow_type("You can't do down farther than the floor.")
if userInput1 == "u":
slow_type("You can't go that way.")
userInput = ""
def fork():
choice2 = False
slow_type("\nFork")
slow_type("\nThere are another two ways to go. One goes north into a cavern, another leads down deeper into the earth.\n\n")
deeperOrFarther = ""
while choice2 == False:
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input (">")
checkDirection(userInput)
deepLower = userInput.lower().strip()
if deepLower == "n":
slow_type("You walk forward, determined... off a cliff. Tragic!")
choice2 = True
death()
if deepLower == "d":
slow_type("You descend down into the darker regions of the cave.")
choice2 = True
if deepLower == "w":
crossroadsalready()
cantPerformAction(deepLower)
houseChoice()
wpm = 60
slow_type("Welcome to Zotan! \nn = north \ns = south \nw = west \ne = east \nu = up \nd = down \nt = take")
clear()
wpm = 120
def clearing():
slow_type("Clearing\n")
slow_type("You wake up in the middle of a clearing. There is a passage to the north.")
slow_type("\n\n")
clearingalready = True
choice = None
while choice == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower()
if userInput.strip() == "n":
choice = False
else:
slow_type("You can't go that way.")
userInput = ""
crossroads() #1
def clearingalready():
slow_type("Clearing\n")
slow_type("There is a passage to the north.")
slow_type("\n\n")
choice = None
while choice == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower()
if userInput.strip() == "n":
choice = False
else:
slow_type("You can't go that way.")
userInput = ""
crossroads() #1
def houseChoice():
slow_type("\n\n\n\nHouse Doorway\n\n")
choice = None
while choice == None:
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input(">")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "d" or userInput == "u" or userInput == "w" or userInput == "e":
slow_type("You can't go that way.")
if userInput == "n":
choice = False
if userInput == "s":
choice = False
if userInput == "s":
fork()
elif userInput == "n":
entryway()
def entryway():
slow_type("\nEntryway")
slow_type("\n\nThere is a kitchen to the west and a dark staircase. A back door hangs open in the north, revealing the entry into another dark corridor.")
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "w":
kitchen()
if userInput == "u":
attic()
if userInput == "n":
chasm()#4
if userInput == "s":
houseChoice()
def entrywayalready():
slow_type("\nEntryway")
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "w":
if kitchenAlready == False:
kitchen()
elif kitchenAlready == True:
kitchenalready()
if userInput == "u":
attic()
if userInput == "n":
chasm()#4
def kitchen():
kitchenAlready = True
slow_type("\n\nKitchen")
slow_type("It seems that the kitchen has been used recently. There is a wicked looking steak knife on the counter, and a mirror on the table.")
userInput = input("\n>")
userInput = userInput.lower().strip()
if userInput == "t knife":
if "knife" not in inventory:
slow_type("Taken.")
inventory.append("knife")
elif "knife" in inventory:
slow_type("You can't take that item.")
elif userInput == "t mirror":
if "mirror" not in inventory:
inventory.append("mirror")
elif "mirror" in inventory:
slow_type("You can't take that item.")
slow_type("You can't perform that action.")
elif userInput == "e":
entrywayalready()
def kitchenalready():
slow_type("\n\nKitchen")
userInput = input("\n>")
userInput = userInput.lower().strip()
if "knife" not in inventory:
inventory.append("knife")
elif "knife" in inventory:
slow_type("You can't take that item.")
if userInput == "t mirror":
if "mirror" not in inventory:
inventory.append("mirror")
elif "mirror" in inventory:
slow_type("You can't take that item.")
if userInput == "e":
entrywayalready()
def attic():
slow_type("\n\nAttic")
choice = None
while choice == None:
userInput = input(">")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input(">")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "n" or userInput == "s" or userInput == "e" or userInput == "w" or userInput == "u":
slow_type("You can't go that way")
if userInput == "t vial":
if "vial" not in inventory:
slow_type("Taken.")
inventory.append("vial")
elif "vial" in inventory:
slow_type("You can't take that item.")
if userInput == "d":
choice = False
entryway()#6
def chasm():
slow_type("\n\nChasm")
slow_type("\nThere is a chasm in front of you, with a rickety wooden bridge crossing the wide and endlessly deep ravine to the north, and a small passage to the west.")
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input (">")
checkDirection(userInput)
chasmChoice = userInput.lower().strip()
if chasmChoice == "n":
slow_type("You cross the wooden bridge and it crumbles behind you. There is no turning back.")
cavern()
if chasmChoice == "w":
smallPassage()
if chasmChoice == "s":
entryway()#7
def smallPassage():
slow_type("\n\nSmall Passage")
slow_type("\nThere is a room to the west.")
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input (">")
checkDirection(userInput)
userInputLower = userInput.lower().strip()
if userInputLower == "w":
trollRoom()
if userInputLower == "e":
chasm()
if userInputLower == "s" or userInputLower == "n" or userInputLower == "u" or userInputLower == "d" or userInputLower == "t":
slow_type("You can't perform that action.")#8
def trollRoom():
slow_type("\n\nTroll Room")
slow_type("\nThere is a troll in the room with a large blood stained axe.")
lowerr = "l"
while lowerr != "e":
userInput = input(">")
lowerr = userInput.lower().strip()
if lowerr == "attack troll":
if "knife" in inventory:
xRan = random.randint(0,3)
if xRan == "3":
slow_type("The troll parries your attack.")
if xRan == "2":
slow_type("You get a clear hit on the troll. It groans loudly, displaying a look of deep hatred on it's deformed face.")
trollHit = trollHit + 1
if trollHit == 2:
slow_type("The troll falls to the floor, dead. Its axe lays on the floor.")
axe = True
if userInput != "t axe" or userInput != "e":
slow_type("You can't perform that action.")
if xRan == 3:
if playerHit == 0:
slow_type("The troll knocks you back.")
if playerHit == 1:
slow_type("The troll lands a clean graze on your shoulder. You cry out in pain.")
if lowerr == "t axe":
if axe == True:
slow_type("Taken.")
inventory.append("axe")
elif axe != True:
slow_type("There is no axe there.")
if lowerr == "n" or lowerr == "s" or lowerr == "d" or lowerr == "u" or lowerr == "t" or lowerr == "w":
slow_type("You cannot perform that action.")#9
clearingAlready = False #Determines whether or not the player has already been to the crossroads.
clearing()
crossroads()
fork()
When I execute this particular part of the code It seems like there is no ouput from the computer, no Taken. or You can't perform that action. I can't seem to pinpoint the exact cause of the error or why it is misbehaving.
Console output:
House Doorway
>n
Entryway
>w
Kitchen
>t knife
output: nothing

Counter for this, I still don't understand

I had previously asked about why my counter wasn't working. So, whilst working a different project, I realised I needed a counter but couldn't find or place one that fitted my needs. (I am also well aware that this could be shortened but ignore that). The counter needs to allow only 10 questions to be asked, but I just couldn't figure out how to adapt the others that I saw.
from random import randint
import random
import math
count = 0
print("This game is a quiz to see how good you are at maths. No paper allowed!")
def Start():
print("No paper allowed nor a calculator!")
ans1 = input("Do you wish to start? \n")
if ans1 == "Yes" or ans1 == "yes" or ans1 == "Y" or ans1 == "y":
Begin(count)
if ans1 == "no" or ans1 == "No" or ans1 == "n" or ans1 == "N":
exit()
def Begin(count):
opers = ['+','-','*',"/"]
operation = random.choice(opers)
num1 = random.randint(2,21)
num2 = random.randint(2,num1)
num3 = int(eval(str(num1) + operation + str(num2)))
ans2 = int(input("What is "+str(num1) + operation + str(num2)+"? \n"))
if ans2 == num3:
print("Well done! You must be good at maths!")
Begin(count)
if ans2 != num3:
print("You are terrible at maths. Go sit in that corner. (The answer was "+str(num3)+").")
Begin(count)
def Replay():
ans3 = input("Would you like to play again? \n")
if ans3 == "Yes" or ans3 == "yes" or ans3 == "Y" or ans3 == "y":
Start()
if ans3 == "no" or ans3 == "No" or ans3 == "n" or ans3 == "N":
exit()
Start()
in Begin function add :
global counter
counter+=1
if counter == 10:
print("something...")
EDIT:
this works!
from random import randint
import random
import math
count = 0
print("This game is a quiz to see how good you are at maths. No paper allowed!")
def Start():
print("No paper allowed nor a calculator!")
ans1 = input("Do you wish to start? \n")
if ans1 == "Yes" or ans1 == "yes" or ans1 == "Y" or ans1 == "y":
Begin()
if ans1 == "no" or ans1 == "No" or ans1 == "n" or ans1 == "N":
exit()
def Begin():
global count
count+=1
if count==10:
print("finished")
exit()
opers = ['+', '-', '*', "/"]
operation = random.choice(opers)
num1 = random.randint(2
, 21)
num2 = random.randint(2, num1)
num3 = int(eval(str(num1) + operation + str(num2)))
ans2 = int(input("What is " + str(num1) + operation + str(num2) + "? \n"))
if ans2 == num3:
print("Well done! You must be good at maths!")
Begin()
if ans2 != num3:
print("You are terrible at maths. Go sit in that corner. (The answer was " + str(num3) + ").")
Begin()
def Replay():
ans3 = input("Would you like to play again? \n")
if ans3 == "Yes" or ans3 == "yes" or ans3 == "Y" or ans3 == "y":
Start()
if ans3 == "no" or ans3 == "No" or ans3 == "n" or ans3 == "N":
exit()
Start()

Resources