I have a python programming spelling game for children, and I need to make it loop/restart if the player clicks yes once they have finished the game, and exit the program if they click no.
This is the top of my programming.
#Declare Constants and Variables
Score = 0
PlayerAnswer = 0
playOn = 0
while playOn != "Yes":
and this is the end, where I want the player to be able to repeat the game if they click yes on the easygui buttonbox.
playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
if playOn == "Yes":
Score = 0 #resets score count, if player wants to play again
elif playOn == "No":
easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")
whenever I test it and click yes, the program closes anyway.
while playOn != "Yes":
playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
if playOn == "Yes":
Score = 0 #resets score count, if player wants to play again
elif playOn == "No":
easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")
In Python, the code body needs to be indented for it to be interpreted as inside a code block.
In other languages such as C# as long as the codes are inside method{ //code inside here} then the codes will run inside the method.
while (playOnBool):
playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
if playOn == "Yes": playOnBool = True
else: playOnBool = False
You need to wrap your code with a while loop.
The code at the end is not in the 'while' loop at the top.
Since Python goes by indentation, the program will end after the playOn variable is set at the end.
I assume there must be code in the middle, at least a 'pass', otherwise Python will give an indented block error.
Related
What is wrong with my coding. It is a simple conditional statement where you say yes or no to taking the quiz. If you type yes, you begin answering questions and if you type no, it just exits out of the function.
play=input("\v Do you want to take the quiz or not? Yes or No? ").lower
if play == "no":
print("That's too bad")
quit(main())
question_num=0
green_point=0
mean_point=0
if play=="yes":
print("Great! Let us Begin!")
for questions,answers in QUESTIONS:
playeranswer=input("{} " .format(questions))
But the program just ends once you type in an answer for play. I thought it was pretty clear what is supposed to happen. Why is it not doing anything?
1- the indention is wrong with your coding
2- you forgot the () after .lower
your code should be like this :
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower()
if play == "no":
print("That's too bad")
quit(main())
question_num = 0
green_point = 0
mean_point = 0
elif play == "yes":
print("Great! Let us Begin!")
for questions, answers in QUESTIONS:
playeranswer = input("{} " .format(questions))
Actually it's not just the indentation. When you do this:
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower
It actually sets play to be the function lower, not the lowercase string that results from calling lower(). You need to add parentheses:
play = input("\v Do you want to take the quiz or not? Yes or No? ").lower()
if play == "no":
print("That's too bad")
quit(main())
question_num = 0
green_point = 0
mean_point = 0
elif play == "yes":
print("Great! Let us Begin!")
for questions, answers in QUESTIONS:
playeranswer = input("{} " .format(questions))
So i have this simple problem and I am not so sure what to do even after trying it for quite sometime.
combinations = ["rock","papers","scissors"]
ask = str(input("Do you want to play rock papers scissors?"))
while ask:
if ask.lower() == "yes":
print("ok")
break
elif ask.lower() == "no":
print("okay :(")
break
else:
ask = input("So is it a yes or no ?!")
break
my issue is that I am not so sure what to type such that my input user has to type either yes or no instead of typing something else. Additionally, when I tried to run the program, when I typed yes/no it jumped straight to the else statement instead of the if statement.. someone pls help :( (am just a noob programmer)
I would remove the break in the else statement so that your program keeps looping until the user inputs yes or no.
combinations = ["rock","papers","scissors"]
ask = str(input("Do you want to play rock papers scissors?"))
while ask:
if ask.lower() == "yes":
print("ok")
break
elif ask.lower() == "no":
print("okay :(")
break
else:
ask = input("So is it a yes or no ?!")
Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break
I'm trying to make a game where you go through a maze and try to escape from a voice, but everytime the player says the wrong answer to one of the questions it says "Game Over" but then carries on where it kept off, I've tried a lot of things and researched, but I can't seem to figure it out, I'm only a beginner
`
import time
import os
print ("Your adventure starts as a young boy, running away from home becuase you're a rebel")
time.sleep(2)
print ("You find the famous labyrinth, do you go in?")
time.sleep(2)
answer = input("Make your choice, Yes OR No")
time.sleep(2)
print ("The answer",answer ,"got you stuck in a hole")
time.sleep(2)
print ("But you find a secret passage")
answer = input("Do you go through the door, Yes or No?")
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
answer = input("What do you say to the Voice, Hello or Who are you?")
if answer == "Hello":
print ("Hello")
elif answer == "Who are you?":
print ("Im your worst nightmare")
time.sleep(2)
print("You try and escape the labyrinth and turn a large gate with a gnome on the over end")
answer = input("Do you open the gate, Yes Or No?")
if answer == "Yes":
time.sleep(3)
print ("Game Over, you get brutally killed by a gnome, good job")
os._exit(0)
elif answer == "No":
time.sleep(3)
print ("You go the other way and see a light at the end of the tunnel")
answer = input("You see your family outside crying and waiting for you, do you go with them?")
if answer == "Yes":
print("You have a nice ending and you're sorry you ran away")
print("You have been graded: ")
elif answer == "No":
print("God smites you for being stupid.")
os._exit(0)`
take this block, for example
print ("But you find a secret passage")
answer = input("Do you go through the door, Yes or No?")
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
# continuation
if the user enters "No" it will print "Game Over" - which I assume is correct. However, control flow in the program continues past the if/else block. What you need to do is exit the program using something like sys.exit() or make sure your control flow only has paths forward if it should i.e. wrapping what happens next in the truthy part of the if/else block
if answer == "No":
time.sleep(2)
print ("Game Over.")
elif answer == "Yes":
time.sleep(2)
print("You hear a strange voice")
time.sleep(2)
# put continuation here
I'm working on a code with python, where we've been asked to create a game of Rock, Paper, Scissors using an external file of options (rock, paper, scissors) as opposed to having the code use any user input. However, for some reason, my code doesn't work. When someone inputs "yes", it prints "Let us play now," but that's it. Nothing else happens.
Why isn't the game completing when a user provides "yes" as input?
from random import randrange
def sample():
computer_input = randrange(1,3)
return computer_input
def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()
tied = 0 #games tied
user_won = 0 #games won by user
comp_won = 0 #games won by computer
user_input = ""
computer_input = ""
print("Rules of the game...")
print("Would you like to turn up with a game of rock, paper, or scissors? ;) Yes or no? -->")
answer = input()
if (answer == "yes"):
play = True
print("Let us now play.")
## elif(answer == "no" or "No"):
## play = False
## print("Sorry. Maybe we can play next time ;)")
## else:
## play = False
## print("Please try again!")
## main()
while True:
if(computer_input == "1"):
if(user_input == a[0]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[1]):
user_won = user_won + 1
print("You won! Paper covers Rock")
elif(user_input == a[2]):
comp_won = comp_won + 1
print("You lost! Rocks knocks out scissors")
## else:
## print("Try again!")
elif (computer_input == "2"):
if (user_input == a[0]):
comp_won = comp_won + 1
print("You lost! Paper covers Rock")
elif(user_input == a[1]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[2]):
user_won = user_won + 1
print("You won! Scissors cuts Paper")
## else:
## print("Try again!")
else :
if(user_input == a[0]):
user_won = user_won + 1
print("You won! Rock knocks out scissors")
elif(user_input == a[1]):
comp_won = comp_won + 1
print("You lost! Scissors cuts Paper")
elif(user_input == a[2]):
tied = tied + 1
print("Game is tied!")
## else:
## print("Try again!")
##
##print("Game over")
##print("Statistics")
##print("Games tied -->", tied)
##print("Game won by comp -->", comp_won)
##print("Game won by user -->", user_won)
##
main()
Notice that on line 5 below, you set computer_input to the result of sample():
def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()
But then a few lines later, you set it to "":
user_input = ""
computer_input = ""
Your while loop is checking against the value of computer_input, but it assumes it will be a number. It has no case to handle the empty string. I would recommend removing that line.
Also note that your while loop is checking the value of user_input, but you never seem to actually read input into that variable.
There are many, many problems with this code.
Every time you define or use a variable, you should have a clear idea of
why it is defined this way or exactly what this use of the variable is
going to accomplish.
You have a loop, which seems to indicate that you meant for more than
one round of the game to be played when you run the code once.
But there is only one place where the computer's choice is set
to a number 1, 2, or 3, and it occurs only once.
(Besides, as has already been pointed out, then you change the
computer's choice to "" without even reading the number once.)
You have no apparent way to get out of the loop within the logic of the code.
It is unclear what you think you are supposed to be reading from the
user's input file. You put the contents of the file in the array a line
by line, but then you only ever look at a[0], a[1], and a[2].
What were the first three lines of the file supposed to contain?
Why only three lines? What does it mean to ask whether
user_input == a[0]?
(I have a hunch that you were supposed to set the user input on each
round to a member of a, not compare user_input to a member of a.)
(Also notice that you set user_input = "" earlier, so unless you read
empty strings into the entries of a, expressions like
user_input == a[0] will always be false.)
What is the point of setting play = True? (Or even setting
play = False as in the commented-out code?) You never do anything that
would read the value of play.
What is the point of keeping count in the variables tied,
user_won, and computer_won? You never read those variables either,
except when you're setting new values of them.
It might help if you write some smaller functions with very clear
purpose, input and output. The sample() function is promising, but
everything else is in main().
For example, figuring out who won, given the computer's choice and
the player's choice, could be a function.
By writing such a function you would remove dozens of lines of code from
the loop in main(), replacing them with perhaps one line of code.
It's much, much easier to write well-designed loops when
the block of code inside the loop is short.