我的Python代码中某处有一个问题。我找不到它的位置

时间:2019-07-19 12:09:07

标签: python python-3.x

我不知道这是怎么回事。运行它,我可以输入数字,但是它停止工作。它说:“ TypeError:play_game()缺少1个必需的位置参数:'limit'。但是我不确定那里缺少什么?

#!/usr/bin/env python3

import random

def display_title():
    print("Guess the number!")
    print()

def get_limit():
    limit = int(input("Enter the upper limit for the range of numbers: "))
    return limit

def play_game(limit):
    number = random.randint(1, limit)
    print("I'm thinking of a number from 1 to " + str(limit) + "\n")
    while True:
        guess = int(input("Your guess: "))
        if guess < number:
            print("Too low.")
            count += 1
        elif guess >= number:
            print("Too high.")
            count += 1
        elif guess == number:
            print("You guessed it in " + str(count) + " tries.\n")
            return

def main():
    display_title()
    again = "y"
    while again.lower() == "y":
        limit = get_limit()
        play_game()
        again = input("Play again? (y/n): ")
        print()
    print("Bye!")

# if started as the main module, call the main function
if __name__ == "__main__":
    main()

3 个答案:

答案 0 :(得分:2)

您已经定义了const call = (x) => { return new Promise((resolve, reject) => { setTimeout(() => { resolve({ val: x }); }, 3000) }) } const dummy = async() => { let v = (await call(3)).val + (await call(4)).val; alert(v); } dummy()函数,以将play_game作为参数,但是当您在limit循环中调用此函数时,没有在括号中提供任何值main

您可以尝试像调用它一样添加您指定的play_game()

limit

或者,根据您的代码,由于您要要求用户提供限制,因此请按以下方式调用它:

play_game(25)

或者,如果您希望在不设置限制的情况下呼叫play_game(limit) ,则可以将play_game的定义行更改为以下内容:

play_game()

每当调用该函数而不提供限制值时,它将设置默认值25。

答案 1 :(得分:0)

在您的主要用户中,您在呼叫playgame()时没有提供限制作为参数。

您的主体应该看起来像

def main():
    display_title()
    again = "y"
    while again.lower() == "y":
        limit = get_limit()
        play_game(10)
        again = input("Play again? (y/n): ")
        print()
    print("Bye!")

答案 2 :(得分:0)

是的,play_game()需要参数限制。我已经对您的代码进行了快速检查,还有其他一些问题

  • count变量未初始化
  • 您在每一步中计算随机数
  • 猜测>数字应代替猜测> =数字

这是固定代码,对我有用。我希望它会有用:

import random

count = 0
number = -1

def display_title():
   print("Guess the number!")
   print()

def get_limit():
    limit = int(input("Enter the upper limit for the range of numbers: "))
    return limit

def play_game(limit):
    global number, count
    if number == -1:
        number = random.randint(1, limit)
        print("I'm thinking of a number from 1 to " + str(limit) + "\n")
    while True:
        guess = int(input("Your guess: "))
        if guess < number:
            print("Too low.")
            count += 1
        elif guess > number:
            print("Too high.")
            count += 1
        elif guess == number:
            print("You guessed it in " + str(count) + " tries.\n")
            return


display_title()
again = "y"
while again.lower() == "y":
    limit = get_limit()
    play_game(limit)
    again = input("Play again? (y/n): ")
    print()
print("Bye!")