I'm attempting to create a simple "number guessing game" in 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. 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.
You are not in a loop, your 'second iteration' is not python at all, your python script already returned.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.