I'm trying to make a rock paper scissors game with rounds. I'm using a while loop but it doesn't go back to the beginning. I've tried declaring the variables inside of the while, outside, and many other things, but it just doesn't work. I'll leave the code here. Thanks for the help!
import random
computer_win = 0
user_win = 0
jugadas = 0
def play(computer_win, user_win, jugadas):
while (jugadas < 3):
user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: ")
computer = random.choice(['r','p','s'])
if user == computer:
jugadas = jugadas 1
return( f'It\'s a tie. Round {jugadas}/3')
if is_win(user, computer):
user_win =1
jugadas = jugadas 1
return( f'You won! Round {jugadas}/3')
else:
computer_win =1
jugadas = jugadas 1
return( f'You lost! Round {jugadas}/3')
if computer_win >2 or user_win>2:
if computer_win > user_win:
"The computer won"
elif user_win > computer_win:
return "You won!"
else:
return "It's a tie ...."
def is_win(player, opponent):
if(player == 'r' and opponent == 's') or (player =='s' and opponent =='p') \
or (player =='p' and opponent == 'r'):
return True
print(play(computer_win, user_win, jugadas))
CodePudding user response:
Using return in a loop will break it. You should instead save your result to a variable and return it after your loop is finished.
CodePudding user response:
When you hit a return
statement inside a function you'll exit the function even if the return
statement is inside a loop. You should change all return
statements to a print()
function, print()
function is useful for showing information to the user. return
statement is useful for returning data to the program so that other components use it.
Another thing is you don't need to pass the function play(computer_win, user_win, jugadas)
to print()
function.
CodePudding user response:
Welcome to StackOverflow :D
Return statement will finish your function execution. They won't only exit your while
loop, but your function will return a final value, a string in this case. Since you are reading the user input at the beginning of each iteration, I think you meant to use print
instead. Take a look at the code below
if user == computer:
jugadas = jugadas 1
print( f'It\'s a tie. Round {jugadas}/3')
if is_win(user, computer):
user_win =1
jugadas = jugadas 1
print( f'You won! Round {jugadas}/3')
else:
computer_win =1
jugadas = jugadas 1
print( f'You lost! Round {jugadas}/3')
As for the second portion of your code, bare in mind return
won't print the results to the terminal, so maybe you want to use print
there as well:
if computer_win >2 or user_win>2:
if computer_win > user_win:
print "The computer won"
elif user_win > computer_win:
print "You won!"
else:
print "It's a tie ...."
In python you don't need to use explicit return statements, without return statements your function will finish executing and will return nil