PDA

View Full Version : [SOLVED] Yet another number guessing game - Python



Mirge
August 26th, 2009, 04:10 AM
import random

maxTries = 5
minRand = 1
maxRand = 10

# Generate random number & set totalTries to 0
randNumber = random.randint(minRand, maxRand)
totalTries = 0
userGuess = 0

while True:
userGuess = int(input("Please enter your guess: "))

if userGuess == randNumber:
print("Congratulations! You guessed correctly!")
break

if userGuess > randNumber:
print("You guessed too high!")
elif userGuess < randNumber:
print("You guessed too low!")

totalTries = totalTries + 1
if totalTries == maxTries:
print("Game over! The correct number was: " + str(randNumber))
break
Be gentle, this is my first Python app -- ever.

Am I blind, or does Python not support an increment/decrement operator? Trying totalTries++ threw an error.

Mirge
August 26th, 2009, 04:12 AM
I'm starting to enjoy Python though... only 27 lines of code, and it could have easily been shortened, but it was my first app :). Took a whopping 2-3 minutes to build, being a complete beginner to Python I don't consider that too bad!

Couple things that keep tripping me up...

1.) No semicolon to mark end of statement.
2.) No braces to mark blocks (indention instead).
3.) "Casting" I guess it could be called... I keep trying to do something like: (str)randNumber, instead of str(randNumber).

Mirge
August 26th, 2009, 04:17 AM
Additional note: fails (obviously) when input contains non-numeric characters -- suppose I should read up on error/exception handling!

Mirge
August 26th, 2009, 04:37 AM
Changed the user input portion to:



try:
userGuess = int(input("Please enter your guess: "))
except ValueError:
print("Please enter a valid number.")
continue


Pretty neat how easy Python is to pick up actually...

DirtDawg
August 26th, 2009, 04:42 AM
FYI: for increments, try '+=' rather than '++'
example: x += 1

Glad you're having fun. Python is really great.

Mirge
August 26th, 2009, 05:53 AM
FYI: for increments, try '+=' rather than '++'
example: x += 1

Glad you're having fun. Python is really great.

Ahh thanks! That's much better :).

sam191
August 26th, 2009, 06:37 AM
Nice! I remember doing something like this.

One thing to note: use 'raw_input' instead of 'input' for safer coding.

Other than that, I'm glad you're liking Python.

Mirge
August 26th, 2009, 03:05 PM
Nice! I remember doing something like this.

One thing to note: use 'raw_input' instead of 'input' for safer coding.

Other than that, I'm glad you're liking Python.

EDIT: Apparently raw_input() was replaced with input() in Python 3, which is what I'm using :). Thanks for pointing that out though, I wasn't aware of the difference there.