While,Python 中不循环

问题描述 投票:0回答:3

我正在尝试制作一个带有回合的石头剪刀布游戏。我正在使用 while 循环,但它不会回到开头。 我尝试过在 while 内部、外部和许多其他东西中声明变量,但它就是不起作用。 我将把代码留在这里。 感谢您的帮助!

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))


python django loops if-statement while-loop
3个回答
2
投票

在循环中使用 return 会破坏它。 您应该将结果保存到变量中,并在循环完成后返回它。


0
投票

当您在函数内点击

return
语句时,即使
return
语句位于循环内,您也会退出该函数。您应该将所有
return
语句更改为
print()
函数,
print()
函数对于向用户显示信息很有用。
return
语句对于将数据返回到程序以便其他组件使用它非常有用。

另一件事是你不需要将函数

play(computer_win, user_win, jugadas)
传递给
print()
函数。


0
投票

return
语句将完成函数执行。它们不仅会退出您的
while
循环,而且您的函数将返回最终值,在本例中是一个字符串。由于您在每次迭代开始时读取用户输入,因此我认为您打算使用
print
来代替。看看下面的代码

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')

至于代码的第二部分,请记住

return
不会将结果打印到终端,所以也许您也想在那里使用
print

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 ...."

在Python中你不需要使用显式的return语句,没有return语句你的函数将完成执行并返回

nil

© www.soinside.com 2019 - 2024. All rights reserved.