在循环中创建变量的问题

时间:2011-03-08 16:47:22

标签: python loops

我正在学习python,其中包含一本通过创建游戏来教授的书。我必须编写代码,所以我输入一个数字,计算机根据更高或更低的输入做出有根据的猜测。输入我的号码后,我一直收到错误:

Traceback (most recent call last):
  File "C:\Users\Rayvenx\Desktop\My_programs\Number_game_pcguess.py", line 7, in 
    highlow = raw_input("\nIs it", guess, "?:")
TypeError: [raw_]input expected at most 1 arguments, got 3

以下是代码:

import random

number = raw_input("\nWhat is your number 1-100? :")

guess = random.randrange(100) + 1

highlow = raw_input("\nIs it", guess, "?:")

while guess != number:
    if highlow == "lower":
        guess = random.randrange(100) + 1  guess

        highlow = raw_input("\nIs it", guess, "?:")


print "\nHaha! I win!"

raw_input("\n\nPress enter to exit game.")

3 个答案:

答案 0 :(得分:1)

highlow = raw_input("\nIs it %s?:"%guess)

或者,使用格式方法(在Python 2.6中引入):

highlow = raw_input("\nIs it {0}?:".format(guess))

或者,如果使用Python3:

highlow = raw_input("\nIs it {}?:".format(guess))

答案 1 :(得分:1)

这一行传递了3个参数。

highlow = raw_input("\nIs it", guess, "?:")

将字符串格式化在外部或格式化

中的字符串
mystr = "\nIs it %s ?;" % guess
highlow = raw_input(mystr)

highlow = raw_input("\nIs it %s ?;" % guess)

答案 2 :(得分:0)

你的问题是,当你期望一个时,你给了raw_input三个参数;)

但是,严肃地说:你的调用看起来像raw_input("is it", guess, "?:")应该使用Python的字符串格式来格式化传递给raw_input的字符串:raw_input("is it %s?" %(guess, ))