如何在不重复字符串的情况下结束此程序?

时间:2015-10-20 22:12:24

标签: python python-3.x if-statement

import random

def tryAgain(yesorno):
    yesOrNo = input(yesorno)
    if yesOrNo == 'y':
        main()
    else:
        print("Game over!")
    yesOrNo = input(yesorno)

def playOneGame(low, high):
    secret = random.randint(low,high)
    response = int(input("I'm thinking of a number between 1 and 100: "))
    tries = 1
    while response != secret:
        if response < secret:
            print("Guess higher")
        else:
            print("guess lower")
        response = int(input("I'm thinking of a number between 1 and 100: "))
        tries += 1
    print("That took you ",tries,"tries!")
    return tries

def main():
    playOneGame(1,100)
    tryAgain("Try again? y or n ")

main()

所以这是我的计划,除了一小部分,我已经完成了所有工作。当它通过main()中的tryAgain函数并且我输入'n'而不是停止程序并结束它时,它会再次打印“再试一次?y或n”然后我按下任何东西然后它只是结束。当我输入'n'时,如何使我的程序结束?

1 个答案:

答案 0 :(得分:1)

问题是在tryAgain函数中,您实际上要求用户输入两次。

尝试

import random

def tryAgain(yesorno):
    yesOrNo = input(yesorno)
    return yesOrNo.lower() == 'y'

def playOneGame(low, high):
    secret = random.randint(low,high)
    response = int(input("I'm thinking of a number between 1 and 100: "))
    tries = 1
    while response != secret:
        if response < secret:
            print("Guess higher")
        else:
            print("guess lower")
        response = int(input("I'm thinking of a number between 1 and 100: "))
        tries += 1
    print("That took you ",tries,"tries!")
    return tries

def main():
    while True:
        playOneGame(1,100)
        if not tryAgain("Try again? y or n "):
            break
    print("Game over!")

main()

它有效,我刚试过,这很有趣!