hello im new to python and im just making simple programs(for now)
so im doing this guessing game where the user enter a number and tells him if he got it right or not.
here is the code

``````import random
import re
print 'This is a guessing game'
def game(guess):
x=random.randint(1,100)
respond=input(guess)
if respond < x:
print 'nop higher'
elif respond > x:
print 'wow too much'
if respond == x:
print 'you got it!!'
print 'the number was ' + x

game("Guess a number: ")``````

i cant figure out how to loop it. it just does it once and thats it.
Any help is appreciated

You can loop indefinitely with `while True` . Here is the code

``````import random
import re

print 'This is a guessing game'

def game(guess):
x=random.randint(1,100)
while True: # loop indefinitely
respond = int(raw_input(guess)) # better than input()
if respond < x:
print 'nop higher'
elif respond > x:
print 'wow too much'
else:
assert respond == x # necessarily true. We may assert it for debugging
print 'you got it!!'
print 'the number was ' + str(x) # must convert to string for addition
break # exit the loop

game("Guess a number: ")``````

In python 2, use raw_input(), which reads a string, and convert the string to int instead of using input(). (in python 3, input() is python 2's raw_input().)

commented: nice help +15

thank a lot Gribouillis.
works great :)

just a question, if i want the user to choose if he can play again then i just put

``````print 'the number was ' + str(x)
again=raw_input("play again? ")``````

or do i do something else?

Another while loop around the line 20 would be clearer, although it is possible to just generate new value for x after response to continue and not to do the break.

just a question, if i want the user to choose if he can play again then i just put

``````print 'the number was ' + str(x)
again=raw_input("play again? ")``````

or do i do something else?

It's ok, but you can do a little better: offer a default option (yes), and then you must translate the answer into a boolean

``````again = raw_input("play again? [y] ").strip().lower()
again = (again in ('', 'y', 'yes')) # now again is True or False``````

strip() removes white space at both ends, in case the user enters `" yes "` , and lower() converts to lowercase (if the user enters "Yes").

k thanks. really apperciated
:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.