bash:Python Number游戏中意外标记“newline”附近的语法错误

时间:2017-04-25 18:59:29

标签: python bash python-2.7

我正在尝试用Python创建一个简单的“猜数游戏”。

我的代码:

minimum = 1
maximum = 100
current_number = 50




def new_number(x):
    global sign, current_number, minimum, maximum
    if x == ">":
        minimum = current_number + 1
        curent_number = minimum + maximum / 2
        guess()
    else:
        maximum = current_number - 1
        current_number = minimum + maximum / 2
        guess()


print "Pick a number between 1 - 100, keep it in your head"
print "I'm going to guess it within 6 guesses"

def guess():
    print "Is your number > or < %d"  % current_number

guess() 

sign = raw_input(": ")
new_number(sign)

尝试使用数字“27”运行它似乎在第一次迭代时工作正常。但是,在输入第二次迭代后,输入==“&gt;”,我收到:

bash: syntax error near unexpected token `newline'

错误指向的没有特定的行号。我确信它与if x == ">":部分有关。

1 个答案:

答案 0 :(得分:1)

你不是一个循环,你的第二次迭代&#39;根本不是python,你的python脚本已经返回了。

检查代码的这些更改:

minimum = 1
maximum = 100
current_number = 50




def new_number(x):
    global sign, current_number, minimum, maximum
    if x == ">":
        minimum = current_number + 1
        current_number = (minimum + maximum) / 2
        guess()
    else:
        maximum = current_number - 1
        current_number = (minimum + maximum) / 2
        guess()


print "Pick a number between 1 - 100, keep it in your head"
print "I'm going to guess it within 6 guesses"

def guess():
    print "Is your number >, < or = %d"  % current_number

guess() 

while(1):
    sign = raw_input(": ")
    if (sign == '='):
        break
    new_number(sign)

问题在于,当你没有循环时,当你的脚本在第一次迭代后返回时,你可能会在bash中点击< <enter>,所以你遇到了bash错误。

我还建议您重构代码以避免使用全局变量,请查看:Why are global variables evil?以了解这对您的代码有何不妥。