This is just a little game to explain some very basic function in Python for beginner. RANDOM, Loop, Try and except...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | __author__ = 'Benoit'
# guess a number between 1 and 100 in ten tries
import random
answer = 'yes'
while answer == "yes":
NumToGuess = random.randint(1, 100)
NumOfTry = 10
print ("Try to guess a number between 1 and 100 in 10 tries")
while NumOfTry != 0:
try:
x = int (input ("Please enter a number between 1 and 100"))
if x > NumToGuess:
print (x,"is too high")
NumOfTry = NumOfTry - 1
print (NumOfTry, "attempt(s) left")
print ("")
elif x < NumToGuess:
print (x,"is too low")
NumOfTry = NumOfTry - 1
print (NumOfTry, "attempt(s) left")
print ("")
elif x == NumToGuess:
print ("You Win, Congratulations!!!")
NumOfTry = 0
except:
print ("Please enter a valid number. For example 1, 5 an 44 are valid numbers to input.")
else:
print ("The number to guess was: ", NumToGuess)
answer = input ('Do you want to play again? (yes/no)')
else:
print ("Thank you for playing. Goodbye")
|
Actually, it is not good idea to put so big part of code in
try
block and catch base exception. Also python has a name convention, so local variables should be likevar_name
, not CamelCase.I am a beginner at python.
This script works at its basic function, but some choices generate errors. For my learning i have made a new script which catches errors, gives the ability to continue