Break command doesn't stop loop [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The Break Command Doesnt work and when i try to run it, it gets stuck like it cant compile because its stuck in a loop
My code isn't running at all, I have reviewed my code but it doesn't seem to work. Everything is fine for me.
import random
# print("Winning Rules of the Rock paper scissor game as follows: \n"
# + "Rock vs paper->paper wins \n"
# + "Rock vs scissor->Rock wins \n"
# + "paper vs scissor->scissor wins \n")
while True:
def main():
print("Enter choice \n 1. Rock \n 2. paper \n 3. scissor \n")
try :
choice_name = (input("User turn: "))
if choice_name == 1:
choice_name = 'Rock'
if choice_name == 2:
choice_name = 'paper'
if choice_name == 3:
choice_name = 'scissor'
else:
choice_name = None
input("Atleast Enter a Valid Number like BRUHHHHHHHHH: ")
except ValueError:
print ("Try again")
main()
print("user choice is: " + choice_name)
print("\nNow its computer turn.......")
Computer_Choice = random.randint(1, 3)
while Computer_Choice == choice_name:
Computer_Choice = random.randint(1, 3)
if Computer_Choice == 1:
Computer_Choice_name = 'Rock'
elif Computer_Choice == 2:
Computer_Choice_name = 'paper'
else:
Computer_Choice_name = 'scissor'
print("Computer choice is: " + Computer_Choice_name)
print(choice_name + " V/s " + Computer_Choice_name)
if((choice_name == 1 and Computer_Choice == 2) or
(choice_name == 2 and Computer_Choice == 1)):
print("paper wins => ", end="")
result = "paper"
elif((choice_name == 1 and Computer_Choice == 3) or
(choice_name == 3 and Computer_Choice == 1)):
print("Rock wins =>", end="")
result = "Rock"
else:
print("scissor wins =>", end="")
result = "scissor"
if result == choice_name:
print("<== User wins ==>")
else:
print("<== Computer wins ==>")
print("Do you want to play again? (Y/N)")
ans = input()
if ans == 'n' or ans == 'N':
break
print("\nThanks for playing")

You are defining a function inside of a while loop. Currently the loop always evaluates to False.
What you want is:
def main():
while True:
# ...
Then you need to actually call main. At the end of the file:
if __name__ == '__main__':
main()

Related

How to add rounds option to rock paper scissors game? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'd like some assistance on my rock paper scissors game code. I'd like to add a function where the player can choose a specific number of rounds, instead of having a preset number of rounds. I am quite stuck on how to do this and I've just started to pick up Python again, so i am a bit rusty. Thank you so much ! (Please ignore spelling ;D)
CODE:
import random #imports a random moduel for the computer.
game = ["ROCK", "PAPER", "SCISSORS"] #sets the game answers.
count = 0 #game count is set to zero.
score = 0 #player score is set to zero.
computerscore =0 #computers score is set to zero.
print ("Welcome")
while count == 0: #starts game if count is zero.
for i in range (3): #repeats the turns 3 times.
answer = input ("Pick rock, paper or scissors.") #users answer.
print (answer.upper()) # prints the users answer
computer= random.choice(game) #computer picks randomly
print ("Computer picks",computer) #prints the computers choice.
if answer.upper() == "ROCK" and computer == "ROCK": #This whole set of code sets the game that what beats what.
print ("Its a tie!") # prints after each response that who won.
count +=1 #the count variable is increased.
elif answer.upper() == "PAPER" and computer == "PAPER":
print ("Its a tie!")
count +=1
elif answer.upper() == "SCISSORS" and computer == "SCISSORS":
print ("Its a tie!")
count +=1
elif answer.upper() == "PAPER" and computer == "ROCK":
print ("You win!")
count +=1
score +=1 #user score is added.
elif answer.upper() == "PAPER" and computer == "SCISSORS":
print ("You lose!")
count +=1
computerscore +=1 #computers score is added.
elif answer.upper() == "ROCK" and computer == "PAPER":
print ("You lose!")
count +=1
computerscore +=1
elif answer.upper() == "ROCK" and computer == "SCISSORS":
print ("You win!")
count +=1
score +=1
elif answer.upper() == "SCISSORS" and computer == "ROCK":
print ("lose!")
count +=1
computerscore +=1
elif answer.upper() == "SCISSORS" and computer == "PAPER":
print ("You win!")
count +=1
score +=1
if score < computerscore: #prints out at the end who scored how much and who won.
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("Computer wins!.")
if score > computerscore:
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("You win!.")
if score == computerscore:
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("Its a tie!!.")
Change the while count == 0:
to while count < x:
where x is the number of games you want to play
also i suggest to split your code into more functions, it will be much cleaner
Create a rounds variable to store the user input:
rounds = 3
Add this just before the while-loop:
user_input = input('How many rounds do you want to play?')
try:
rounds = int(user_input)
except ValueError:
print('Not a number')
And change your loop's condition to for i in range(rounds):

how to use an if else statement in another while loop

I am new to coding. I want to try writing a simple rock paper scissors game. But I can't figure out how to end the game.
In the end of this program if the user input is wrong I want to go to the end variable again. I tried with the commented lines but its not working.
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
while True:
print(player1 + " What do you choose ? rock / paper / scissors : ")
a = input()
print(player2 + " What do you choose ? rock / paper / scissors : ")
b = input()
if a == "rock" and b == "scissors" :
print(player1, "won !!!")
elif a == "scissors" and b == "rock":
print(player2, "won !!!")
elif a == "paper" and b == "rock":
print(player1, "won !!!")
elif a == "rock" and b == "paper":
print(player2, "won !!!")
elif a == "scissors" and b == "paper":
print(player1, "won !!!")
elif a == "paper" and b == "scissors":
print(player2, "won !!!")
elif a == b:
print("Its a tie :-(")
elif a or b != "rock" or "paper" or "scissors":
print("Wrong input, Try again")
end = input("Do you want to play again ? yes/no ") == "yes"
if input == "yes":
continue
else:
print('''
GAME OVER''')
break
# elif input != "yes" or "no":
# print("Wrong input, Try again. yes or no ?")
I expect it to end game if the input is "no" and restart the game if input is "yes" if the input is not correct I want the prompt to appear again.
Your code has a few issues which need some addressing, and a few places where it can be streamlined. I have made a few changes to your program as well as added a few comments explaining the changes.
player1 = input("What is player 1's name ? ").title() #This uses chaining to streamline code
player2 = input("What is player 2's name ? ").title() #Same as above
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ") #no need to use a separate print statement
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
valid_entries = ["rock", "paper", "scissors"] #To check for valid inputs
if (a not in valid_entries) or (b not in valid_entries):
print("Wrong input, try again")
continue
a_number = valid_entries.index(a) #Converting it to numbers for easier comparison
b_number = valid_entries.index(b)
if(a_number == b_number):
print("Its a tie :-(")
else:
a_wins = ((a_number > b_number or (b_number == 2 and a_number == 0)) and not (a_number == 2 and b_number == 0)) #uses some number comparisons to see who wins instead of multiple if/elif checks
if(a_wins):
print(player1, "won !!!")
else:
print(player2, "won !!!")
end = input("Do you want to play again ? yes/no ")
while (end !="yes") and (end != "no"):
print("invalid input, try again")
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print("GAME OVER")
break
These changes also make the check by using another while loop to see if the input to restart the game was valid or not
*Note that I have not tested these changes and some edits may need to be be made
Just check the value of end
if end is True:
continue
else:
break
Since, you have set the value of end as a boolean by comparing the input() to "yes", it will say whether the user wants to end the game?
Also, you are not initializing the input variable, and the last elif condition will always be true as mentioned in the comment.
Well you can simplify your code using a list and then simplify your if tests. You can check the order of the options and based on it make a decision. You can also make the tests standard to minimize the number of if statements. This my suggestion to improve your code. I hope it helps:
# get playe names
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
# init vars
options = ["rock", "paper", "scissors"]
players = [player1, player2]
# start game
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check if inputs are correct
while (a not in options or b not in options):
print("Wrong input, Try again")
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check who won
if abs(options.index(a) - options.index(b)) == 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif abs(options.index(b) - options.index(a)) > 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif a == b:
print("Its a tie :-(")
# continue or drop game
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print('''
GAME OVER''')
break

Checking If a File Exists and Loading its Contents

In my programming class we are to make a Rock, Paper, Scissors Game that can load previous saves of the game, display the statistics of the game, and allow the user to continue playing if desired. I have a good chunk of the program created, I just need help with the loading of the file as I just get an endless loop of "What is your name?". My code is below and any help would be appreciated!
#Rock, Paper, Scissors Program
#A menu-based RPS program that keeps stats of wins, losses, and
ties
#12/2/18
import sys, os, random, pickle
#Functions
def print_menu():
print("\n1. Start New Game")
print("2. Load Game")
print("3. Quit")
def print_roundmenu():
print("What would you like to do?")
print("\n1. Play Again")
print("2. View Statistics")
print("3. Quit")
def start_game(username, playing):
print("Hello", username + ".", "let's play!")
playAgain = play_game()
if playAgain == True:
playing = True
elif playAgain == False:
playing = False
return playing
def play_game():
roundNo = 1
wins = 0
losses = 0
ties = 0
playing_round = True
while playing_round:
print("Round number", roundNo)
print("1. Rock")
print("2. Paper")
print("3. Scissors")
roundNo += 1
choices = ["Rock", "Paper", "Scissors"]
play = get_choice()
comp_idx = random.randrange(0,2)
comp_play = choices[comp_idx]
print("You chose", play, "the computer chose",
comp_play+".")
if (play == comp_play):
print("It's a tie!")
ties += 1
print_roundmenu()
gameFile.write(str(ties))
elif (play == "Rock" and comp_play == "Scissors" or play == "Paper" and comp_play == "Rock" or play == "Scissors" and comp_play == "Paper"):
print("You win!")
wins += 1
print_roundmenu()
gameFile.write(str(wins))
elif (play == "Scissors" and comp_play == "Rock" or play == "Rock" and comp_play == "Paper" or play == "Paper" and comp_play == "Scissors"):
print("You lose!")
losses += 1
print_roundmenu()
gameFile.write(str(losses))
response = ""
while response != 1 and response != 2 and response != 3:
try:
response = int(input("\nEnter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
continue
elif response == 2:
print(username, ", here are your game play statistics...")
print("Wins: ", wins)
print("Losses: ", losses)
print("Ties: ", ties)
print("Win/Loss Ratio: ", wins, "-", losses)
return False
elif response == 3:
return False
def get_choice():
play = ""
while play != 1 and play != 2 and play != 3:
try:
play = int(input("What will it be? "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if play == 1:
play = "Rock"
if play == 2:
play = "Paper"
if play == 3:
play = "Scissors"
return play
playing = True
print("Welcome to the Rock Paper Scissors Simulator")
print_menu()
response = ""
while playing:
while response != 1 and response != 2 and response != 3:
try:
response = int(input("Enter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
username = input("What is your name? ")
gameFile = open(username + ".rps", "w+")
playing = start_game(username, playing)
elif response == 2:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
elif response ==3:
playing = False
This code block:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
will repeat infinitely unless you set response to something other than 2. Notice here that all you're doing in this block is (1) asking for username, (2) opening the file, and (3) dumping the file contents with pickle. You're not actually starting the game, like you are in the if response == 1 block. So the same prompt keeps repeating infinitely.
A good thing to do in these situations is to manually step through your code by hand - "what did I do to get here, and what is happening as a result of that?"

A local or global name can not be found error [duplicate]

This question already has answers here:
Python NameError from contents of a variable
(2 answers)
Closed 8 years ago.
I'm trying to make a simple rock paper scissors game, and I get an error with in the line, guess = input. It says I need to define the function or variable before I use it in this way and I am unsure of how I can do that. This is using Python/JES programming
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
guess = input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
return user_guess()
def is_valid_guess(guess):
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
Using raw_input instead of input seems to solve the problem.
guess = raw_input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
and also in
answer = raw_input("Would you like to play again? Enter 'y' for yes or 'n' for no: ")
I'm using Python 2.7.x

Rock paper scissors scoring problems [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Please can someone tell me how to do a basic scoring system to go into this code.
import random
print 'Welcome to Rock, paper, scissors!'
firstto=raw_input('How many points do you want to play before it ends? ')
playerscore=+0
compscore=+0
while True:
choice = raw_input ('Press R for rock, press P for paper or press S for scissors, CAPITALS!!! ')
opponent = random.choice(['rock', 'paper' ,'scissors' ])
print 'Computer has chosen', opponent
if choice == 'R' and opponent == "rock":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'P' and opponent == "paper":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'S' and opponent == "scissors":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'R' and opponent == "paper":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'P' and opponent == "scissors":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'S' and opponent == "rock":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'P' and opponent == "rock":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
elif choice == 'S' and opponent == "paper":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
elif choice == 'R' and opponent == "scissors":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
print 'Player score is',playerscore
print 'Computer score is',compscore
if playerscore == firstto:
'You won the game :)'
exit()
elif compscore == firstto:
'You lost the game :('
exit()
The problem lies with raw_input on line 3. raw_input always returns a string, whereas what you need is an int. If you change line 3 to:
firstto = int(raw_input('How many points do you want to play before it ends? '))
your code will work.
To sanitize user input (so that your code does not come crashing down when the user enters "hello" instead of 5), you can wrap the raw_input call into a try, except statement.
For instance:
valid_input = False # flag to keep track of whether the user's input is valid.
while not valid_input:
firstto_str = raw_input('How many points do you want to play before it ends? ')
try:
# try converting user input to integer
firstto = int(firstto_str)
valid_input = True
except ValueError:
# user input that cannot be coerced to an int -> raises ValueError.
print "Invalid input, please enter an integer."
As an aside, your code was stuck in an infinite loop because you were using the string provided by raw_input in comparisons with integers. This will always return False:
>>> "5" == 5
False
There are many ways to optimize this code, but your immediate problem is the raw_input and the entry of points. This returns a string, while you need an int. Wrap it with int() and you'll be fine. That is, until someone enters a something that cannot be parsed.
firstto = int(raw_input('How many points do you want to play before it ends? '))
EDIT: If you're interested, I've tried optimizing your code a bit (without going to extremes):
import random
what_beats_what = [('R', 'S'), ('S', 'P'), ('P', 'R')]
choices = {'R': 'Rock', 'P': 'Paper', 'S': 'Scissors'}
def outcome(player_a, player_b):
for scenario in what_beats_what:
if player_a == scenario[0] and player_b == scenario[1]:
return 'A'
elif player_b == scenario[0] and player_a == scenario[1]:
return 'B'
print 'Welcome to Rock, paper, scissors!'
score_to_win = 0
while True:
try:
score_to_win = int(raw_input('How many points do you want to play before it ends? '))
if score_to_win > 0:
break
except ValueError:
pass
print 'Try again, with a positive integer.'
human_score = 0
cpu_score = 0
while human_score < score_to_win and cpu_score < score_to_win:
human_choice = ''
while True:
human_choice = raw_input('Press R for rock, press P for paper or press S for scissors: ').upper()
if human_choice in choices:
break
else:
print 'Try again ...'
cpu_choice = random.choice(choices.keys())
print 'Computer has chosen: {0}'.format(choices[cpu_choice])
result = outcome(human_choice, cpu_choice)
if result == 'A':
print "Human wins!"
human_score += 1
elif result == 'B':
print "CPU wins!"
cpu_score += 1
else:
print 'It is a tie!'
print 'Human score is: {0}'.format(human_score)
print 'CPU score is: {0}'.format(cpu_score)
print 'You won the game :)' if human_score > cpu_score else 'You lost the game :('
Modify your first raw_input value. You are getting a string there.
For better result, validate the input as well :-)
while 1:
firstto=raw_input('How many points do you want to play before it ends? ')
if firstto.isdigit():
firstto = int(firstto)
break
else:
print "Invalid Input. Please try again"
This will accept only the strings with numbers. Even if some one gives input as "5.0", it will be neglected.
For better reading on raw_input, click here. To learn more about built-in string methods, read here.
PS: This is not related to the question. But a little suggestion. Your code could be made much simpler. If you are learning, keep this code as v0.1 and update it upon your progress.

Categories