Im am trying to create a program where I type a number between 1 and 100 and the computer randomly guesses numbers till it gets the correct number I chose. ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
1. ## Troubles with the while statement

Im am trying to create a program where I type a number between 1 and 100 and the computer randomly guesses numbers till it gets the correct number I chose. I think I have the general concept of this code working, but there are a few things that aren't happening that I want to happen. One of them is that after typing a number that is too big or too small, it ends the program. I need it to continue asking for a number untill a correct number is typed. I've tried placing while around the ifs that tell you if your number is correct, so it can loop, but no such luck. Also, what would I have to do in order for the program to ask for a number again even if I put in a letter or string.

Code:
```# this time, the computer has to guess the number
# By: Justin

# Imports the random number generator

import random

# Prints the title of the program

print "\n\n\t\tWelcome to the \"Stump the Computer!\" game!"
print "\t\tThe game where YOU stump the computer!\n"
print "\t\t\tBy: Justin"
print "\t\t\t \\ \\ \\ \\ \\\n\n"

# Inputing the number

the_number = ""
while not the_number:
the_number = raw_input("Type number: ")
the_number = int(the_number)

# Checks to see if the number is reasonable

if the_number < 1:
print "\aSorry that number is too small, try again"
elif the_number > 100:
print "\aSorry that number is too big"
else:
print "Okay"```

2. As far as checking the input's range, I would do something like this:
Code:
```input = -1
while((input < 1) and (input > 100)):
input = raw_input('Type number (1-100): ')
input = int(input)

# Do stuff now!```
As far as checking whether or not it's an integer, you can use a regular expression, iterate over the characters in the input string to check whether or not it contains a non-digit, or you could probably use Python's exception handling mechanism; I'm sure it includes bad conversion exceptions.

3. Hi.

Originally Posted by Javasnob
Code:
`while((input < 1) and (input > 100)):`
Small typo; probably should be:
Code:
`while((input < 1) or (input > 100)):`
cheers, drl

4. Whoops...thanks for catching that...

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•