Monday, 15 September 2014

python - Having a syntax error while trying to create a random number generating game -



python - Having a syntax error while trying to create a random number generating game -

i cannot figure out why i'm having syntax error. says number not defined 'number' set 'raw_input'. can help me out? here's code , error message-

def main(): number = raw_input('i have number between 1 , 10. can guess it? please type first guess: ') guess(number) def guess(number): randomnumber = random.randrange(1,10) right = false while not correct: if number > randomnumber: print'too high. seek again.' elif number < randomnumber: print'too low. seek again.' elif number == randomnumber: print'correct!' playagain = raw_input('excellent! guessed number! play 1 time again (y or n)? ') if playagain == 'y': main() traceback (most recent phone call last): file "<pyshell#48>", line 2, in <module> if number > randomnumber: nameerror: name 'number' not defined

i'm not sure you're getting current error, encounter different syntax error when attempting run code. beingness said, there many things causing problems here, not assignment of number.

in python, indentation controls how statements in code executed. things def , if must have body indented, otherwise cause either syntax or logic errors.

this page words improve do.

in current program:

def main(): empty

number = raw_input( ... outside of main() method

guess(number) outside main() method

most of guess() outside of function body

correct = false not match other indentation level

additionally, when indentation fixed, current code doesn't inquire user input more once, , won't maintain same target number on multiple guess() calls. main() method not called.

try this:

class="lang-python prettyprint-override">import random def main(): guess() def guess(): number = int(raw_input('i have number between 1 , 10. can guess it? please type first guess: ')) randomnumber = random.randrange(1,10) while true: if number > randomnumber: print 'too high. seek again.' elif number < randomnumber: print 'too low. seek again.' elif number == randomnumber: print 'correct!' break number = int(raw_input('i have number between 1 , 10. can guess it? please type next guess: ')) playagain = raw_input('excellent! guessed number! play 1 time again (y or n)? ') if playagain == 'y': main() main()

python syntax

No comments:

Post a Comment