Skip to content Skip to sidebar Skip to footer

Bash: Syntax Error Near Unexpected Token `newline' In Python Number Game

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,

Solution 1:

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.


Post a Comment for "Bash: Syntax Error Near Unexpected Token `newline' In Python Number Game"