[英]bash: syntax error near unexpected token `newline' in Python Number game
I'm attempting to create a simple "number guessing game" in Python. 我试图在Python中创建一个简单的“数字猜谜游戏”。
My code: 我的代码:
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)
Attempting to run it with the number "27" seems to work fine for the first iteration. 尝试使用数字“ 27”运行它似乎在第一次迭代中运行良好。 However, after an input is placed on the second iteration, where the input == ">", I receive:
但是,将输入放在第二次迭代后,其中输入==“>”,我收到:
bash: syntax error near unexpected token `newline'
There's no specific line number that the error is pointing to. 该错误所指向的行号没有特定。 I am certain it has to do with the
if x == ">":
section. 我确定这与
if x == ">":
部分有关。
You are not in a loop, your 'second iteration' is not python at all, your python script already returned. 您不在循环中,您的“第二次迭代”根本不是python,您的python脚本已经返回。
Check these changes to your code: 检查对代码的以下更改:
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)
The problem is that as you were not in a loop, when your script returned after first iteration, you probably hit < <enter>
in bash, so you got a bash error. 问题在于,由于您不在循环中,因此您的脚本在第一次迭代后返回时,您可能会在bash中命中
< <enter>
,因此出现了bash错误。
I also suggest that you refactor your code to avoid using globals, take a look at: Why are global variables evil? 我还建议您重构代码以避免使用全局变量,请看一下: 为什么全局变量有害? to see how this is bad for your code.
看看这对您的代码有多不利。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.