Python程序请求输入两次,第一次不返回值

2024-09-28 03:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,在get_response()函数中,如果您输入'y'或'n',它第一次显示为无效,但第二次则有效。
我怎么解决这个问题?在

import random

MIN = 1
MAX = 6

def main():

    userValue = 0
    compValue = 0

    again = get_response()

    while again == 'y':
        userRoll, compRoll = rollDice()
        userValue += userRoll
        compValue += compRoll
        if userValue > 21:
            print("User's points: ", userValue)
            print("Computer's points: ", compValue)
            print("Computer wins")
        else:
            print('Points: ', userValue, sep='')
        again = get_response()

    if again == 'n':
        print("User's points: ", userValue)
        print("Computer's points: ", compValue)
        if userValue > compValue:
            print('User wins')
        elif userValue == compValue:
            print('Tie Game!')
        else:
            print('Computer wins')


def rollDice():

    userRoll = random.randint(MIN, MAX)
    compRoll = random.randint(MIN, MAX)
    return userRoll, compRoll

def get_response():

    answer = input('Do you want to roll? ')

    if answer != 'y' or answer != 'n':
        print("Invalid response. Please enter 'y' or 'n'.")
        answer = input('Do you want to roll? ')

main()

Tags: answergetifresponserandomminmaxcomputer
3条回答

answer != 'y' or answer != 'n':始终为真;or应为and。在

您在逻辑上认为“答案不是y或n”,而是在代码中

not (answer == 'y' or answer == 'n')

应用你得到的恶魔法则

^{pr2}$

也许您应该使用in重新构造。在

您还需要return answer

def get_response():
    while True:
        answer = input('Do you want to roll? ')

        if answer not in {'y', 'n'}:
            print("Invalid response. Please enter 'y' or 'n'.")
        else:
            return answer

它应该是answer != 'y' and answer != 'n':

相关问题 更多 >

    热门问题