在Python中传递许多参数到输入3.猜数字游戏[重复]

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

我尝试使用此代码进行“猜数字”游戏:

import random
print("Pick any number between 1-100 and I'll try to guess it")
x = 1
y = 100
tries = 0
answer = "whatever"

while answer != "yes":
guess = random.randint(x, y)
answer = input("Is your number ", guess, "? Or is it 'lo'wer or 'hi'gher?")
if answer == "hi":
    x = guess + 1
if answer == "lo":
    y = guess - 1
tries += 1

print ("Got it! Your number is ", los, "! It took me ", tries, " Tries! :)")
input("End")

但是我收到一条错误消息:

Traceback (most recent call last):
File "/home/Documents/python/numbers.py", line 11, in <module>
answer = input("Is your number ", guess, "? Or is it 'lo'wer or 'hi'gher?")
TypeError: input expected at most 1 arguments, got 3

我知道我不应该期望

input
接受超过 1 个参数,但是我该如何解决这个问题?

python python-3.x error-handling
2个回答
1
投票

您可以在输入上方添加一行并稍微更改输入函数调用。

import random
print("Pick any number between 1-100 and I'll try to guess it")
x = 1
y = 100
tries = 0
answer = "whatever"

while answer != "yes":
  guess = random.randint(x, y)
  input_message = "Is your number ", guess, "? Or is it 'lo'wer or 'hi'gher?"
  answer = input(input_message)

  if answer == "hi":
    x = guess + 1
  if answer == "lo":
    y = guess - 1
  tries += 1

print ("Got it! Your number is ", los, "! It took me ", tries, " Tries! :)")
input("End")

0
投票

input
需要文档中提到的单个字符串

如果存在提示参数,则会将其写入标准输出,且不带尾随换行符。

使用

format
代替

answer= input("Is your number {}? Or is it 'lo'wer or 'hi'gher?".format(guess))
© www.soinside.com 2019 - 2024. All rights reserved.