Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python程序请求输入两次,不';t第一次返回值_Python - Fatal编程技术网

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

Python程序请求输入两次,不';t第一次返回值,python,Python,这是我的代码,在get\u response()函数中,如果输入“y”或“n”,第一次显示无效,但第二次有效。 我该如何解决这个问题 import random MIN = 1 MAX = 6 def main(): userValue = 0 compValue = 0 again = get_response() while again == 'y': userRoll, compRoll = rollDice() u

这是我的代码,在
get\u 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()

回答!='或者回答n':
始终为真
应该是
应该是
答案!='然后回答n':

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

not (answer == 'y' or answer == 'n')
应用你得到的DeMorgans规则

answer != 'y' and answer != 'n'
也许您应该使用中的
重新构造结构

您还需要
返回答案

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

如果回答!='或者回答n':
始终为真。不是“y”就是“n”。第二个问题:您从未从该函数返回
answer
,或者在'yn'火山中没有回答,这将使
yn
成为有效的input@cricket_007,你是对的,不是用('y','n')回答