I am trying to make a simple guessing game, but the program exits when the user answers, 'yes', that they know how to play. I don't understand why the 'break' makes the program exit rather than continue to the rest of the code. Extreme newbie, in case you can't tell :P
Thanks for all the help!
import random
import time
def calculat(times):
p = "."
for nums in range(times):
print p
time.sleep(.2)
print p * 2
time.sleep(.2)
print p * 3
time.sleep(.2)
print p * 2
time.sleep(.2)
print p
time.sleep(.6)
print "Welcome to Guess!"
print "Press [Enter] to continue!"
raw_input()
while True:
know = raw_input("Do you know how to play? Enter [yes] or [no]\n")
know = know.upper()
if know == "YES":
break
elif know == "NO":
print " "
print "-INSTRUCTIONS-"
print "Here's how the game works. A number 1 to 100"
print "is generated randomly. Your goal is to guess"
print "as many numbers as possible before you run"
print "out of guesses. You have 10 guesses.Good luck!"
print "Have fun!"
else:
print "Please enter [yes] or [no]!"
while True:
score = 0
number = randint(1,100)
newnum = 1
for tries in range(0,9):
if newnum == 1:
print "Okay, I have a number 1 to 100! What is it?"
else:
print "Guess again! What's the number?"
while True:
try:
guess = input()
if guess <= 100 and guess >= 1:
break
else:
print "You must guess an integer, 1 - 100!"
except:
print "You must guess an integer, 1 - 100!"
if guess == number:
print "Heyo! That's correct!"
score = score + 1
number = randint (1,100)
newnum = 1
if tries != 9:
print "Press [Enter]! Guess another number!"
raw_input()
elif guess < number:
if tries != 9:
print "Darn, that guess was less than the number! Try again!"
print "Press [Enter] to continue!"
raw_input()
elif guess > number:
if tries != 9:
print "Whoa, that guess is too big! Try again!"
print "Press [Enter] to continue!"
raw_input()
print "That's it! Let me calculate your final score! [Press Enter]"
raw_input()
calculate(4)
print "Final Score: " + score
print "Good job!"
raw_input()
print "Would you like to play again? [yes] or [no]?"
play = raw_input()
play = play.upper()
if play == "NO":
print "Okay then, press enter to exit!"
raw_input()
break
elif play == "YES":
print "Yey! Let me think of a new number!"
calculate(2)
else:
print "You couldn't even say yes or no. Get out."
raw_input()
break
Oh yeah, the rest of the code could be broken, too. I haven't gotten past the instructions part.
It ends the program because it immediately encounters an error after the instructions are finished. You've imported random but then tried to use randint, unqualified. You've got to qualify it as random.randint or use from random import randint.
I assume you mean the break statement to escape from the first infinite loop. When I run your code, that break statement works just fine and control proceeds to the second infinite while loop.
However, your program then crashes on the first call to randint() because you aren't importing it correctly. Since the randint() function is from outside of your program (it's in the random module), you need to qualify the calls to randint() as random.randint() - so for the first call, you could use number = random.randint(1, 100). Alternatively, you could import randint using from random import randint, rather than import randint. That way, you would be able to call randint() directly.
Related
# code 1
import time
while True:
from datetime import datetime
print(" Time: "+ "%d:%d:%d " % (datetime.now().hour,datetime.now().minute,datetime.now().second),
end = "\r")
time.sleep(1)
# code 2
name = input("Your good name please: ")
print("Hi "+name)
print('''Lets Play Guessing number game
''')
import random
import math
print("you have only 1 chance to guess the number")
original_no = random.randint(0,10)
player_input = input("Guess a number from 1 to 10: ")
if str(player_input) == original_no:
print("you have entered the correct number!")
elif str(player_input) != original_no:
print("you have entered wrong number")
print(str("the correct number is ") + str(original_no))
when the code gets executed, it only prints the code 1 and doesn't print the code 2.
I want to display time over the number guessing game.
I'm just a beginner ,please help me resolve this issue.
You need to end the while loop, you can do it by simply including a break statement in the loop or just remove while loop in case you want the time to be displayed only once.
while True:
from datetime import datetime
print(" Time: "+ "%d:%d:%d " % (datetime.now().hour,datetime.now().minute,datetime.now().second),
end = "\r")
break
time.sleep(1)
def random():
x_val = randint(1,100)
limit = []
limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if limit2 <= 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print limit2
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif limit2 > 5:
return "You guessed over 5 times. You lose, sucker..."
break
elif limit2 == 4:
print "Last guess!"
continue
print "Welcome to my world! You will have to pick a correct number from 1 to 100!
If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Hi, I am working on a guessing game from 1-100 that I built from ground up by myself and doing research, my original code is not even close to this.
Now, I am stuck on the last part I cannot use the list to limit the input in while loop. I want to stop the game after 5 guesses. However every time it always keep going and once it win it printed out "0" for limit2 variable.
Thank you
The main problem with your code is that you never update the "counter" of the attempted tries made by the user. You initialize it at the beginning (through limit2 = len(limit)), but you never update that value, therefore causing an endless loop.
You simply need to perform the check on len(limit) instead of on limit2.
Working solution can be found below. I took the liberty of commenting limit2 (as it is not needed anymore), improving the indentation, adding two imports, replacing sleep with time.sleep, and fixing the number of checks to perform (if you are aiming at 5 maximum tries, len(limit) needs to be less than 5).
from random import randint
import time
def random():
x_val = randint(1,100)
limit = []
# limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if len(limit) < 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
time.sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
time.sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print len(limit)
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif len(limit) >= 5:
return "You guessed over 5 times. You lose, sucker..."
break
print "Welcome to my world! You will have to pick a correct number from 1 to 100! If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Worthy of note is that -- among several other things that should be fixed in your code -- you should avoid calling a function random, since it is already a name used by a very common module.
I am having trouble writing the code of the basic number guessing game in Python. The objective of the game is to correctly guess a number from 1 to 10 picked at random by the program. I also put some help text that tells the users if they guessed too high or too low. I keep getting a syntax error. This is the code i wrote so far:
print "Welcome to the number guessing game"
print "I have my number..."
import random
while True:
random.randint(1, 10)
number = raw_input("What is your guess[1-10]: ")
if number > random.radint(1, 10):
print "sorry you guessed to high"
elif number < random.radint(1, 10):
print "You guessed to low"
elif number == random.radint(1, 10):
print "You guessed right thanks for playing"
break
else: raw_input("What is your guess[1-10]: ")
It is randint not radint. You are creating a new random number for every test; you should assign a variable to a random number outside of the while loop.
r = random.randint(1, 10)
You must indent if: else: blocks - Python is layout sensitive, e.g.
if number > r:
print "sorry you guessed to high"
You are comparing against a str, need to convert the input to an int().
number = int(raw_input("What is your guess[1-10]: "))
You have an unnecessary else: condition at the end.
So putting it all together:
import random
print "Welcome to the number guessing game"
print "I have my number..."
r = random.randint(1, 10)
while True:
number = int(raw_input("What is your guess[1-10]: "))
if number > r:
print "sorry you guessed to high"
elif number < r:
print "You guessed to low"
else:
print "You guessed right thanks for playing"
break
You could change the while loop to cover the condition:
import random
print "Welcome to the number guessing game"
print "I have my number..."
number = 0
r = random.randint(1, 10)
while number != r:
number = int(raw_input("What is your guess[1-10]: "))
if number > r:
print "sorry you guessed to high"
elif number < r:
print "You guessed to low"
print "You guessed right thanks for playing"
I am making a python code that picks a random number and compares it to a guess made by the user.
import random
attempts=0
secret=random.randint(1,49)
print "welcome to my guessing game"
repeat
def repeat():
guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
if secret==guess:
print "Well Done! you guessed it in "+attempts+" attempts"
elif secret < guess:
print "too high"
guess=raw_input("have another go")
elif secret > guess:
print "too low"
guess=raw_input("have another go")
attempts += 1
while guess != secret and attempts>6:
repeat()
but it is saying that repeat is not defined.
This will allow the user to guess 7 times, then prints game over:
this is for Python 2. for Python 3. use int(input(""))
import random
secret = random.randint(1,49)
attempts = 0
for attempts in range(7):
guess=input("I have thought of a number between 1 and 50. you have to try and guess it: ")
if secret==guess:
print "Well Done! you guessed it "
elif secret < guess:
print "too high"
guess=input(" Enter to have another go")
elif secret > guess:
print "too low"
guess=input("Enter to have another go")
if attempts == 6:
print "Game Over"
The Program is not working because you can not run or call a function before it is created. Also you should call repeat by doing this "repeat()"
I've adapted your code to the following which should work. You might want to read up on Local and Global Variables as that's what was causing your main issue in your code.
import random
def repeat(secret, attempts):
guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
if secret==guess:
print "Well Done! you guessed it in "+attempts+" attempts"
elif secret < guess:
print "too high"
guess=raw_input("have another go")
elif secret > guess:
print "too low"
guess=raw_input("have another go")
attempts += 1
while guess != secret and attempts < 6:
repeat(secret, attempts)
attempts = 0
secret = random.randint(1,49)
print "welcome to my guessing game"
repeat(secret, attempts)
Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000 (inclusive). If the player's guess is incorrect, your program should loop until the player finally gets the number right. Your program should keep telling the player Too high or Too low to help the player “zero in” on the correct answer. After a game ends, the program should prompt the user to enter "y" to play again or "n" to exit the game.
My problem is how do you generate a new random integer each time they want to play again?
Here's my code.
import random
randomNumber = random.randrange(1, 1000)
def main():
print ""
number = input("I have a number between 1 and 1000. Can you guess my number? Please type your first guess: ")
guess(number)
def guess(number1):
correct = False
while not correct:
if number1 > randomNumber:
print "Too high. Try again."
print ""
elif number1 < randomNumber:
print "Too low. Try again."
print ""
elif number1 == randomNumber:
break
number1 = input ("What number do you guess? ")
if number1 == randomNumber:
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y":
main()
main()
Take this line:
randomNumber = random.randrange(1, 1000)
and place it inside guess:
import random
def main():
print ""
number = input("I have a number between 1 and 1000. Can you guess my number? Please type your first guess: ")
guess(number)
def guess(number1):
#########################################
randomNumber = random.randrange(1, 1000)
#########################################
correct = False
while not correct:
if number1 > randomNumber:
print "Too high. Try again."
print ""
elif number1 < randomNumber:
print "Too low. Try again."
print ""
elif number1 == randomNumber:
break
number1 = input ("What number do you guess? ")
if number1 == randomNumber:
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y":
main()
main()
Now, a new random integer will be created each time the function is called.
Put a loop in main() and initialize randomNumber at the beginning of the loop.
please try this remove four spaces starting from random to starting of while loop
import random
print " welcome to game of guessing "
print "you have 6 attempts"
num1 = random.randint(1,100)
print num1 # this is your computer generated number ( skip while running :only for test purpose)
num2 = num1+random.randint(1,15)
print " hint: number is close to " + str(num2)
count=1
while count<=6:
print " enter the number you think"
inputnum=raw_input()
if inputnum==str(num1):
print "congrats you guess the correct number"
break
elif inputnum<str(num1):
print " number is lower than correct one "
count=count+1
elif inputnum>str(num1):
print "number is greater than correct one"
count=count+1
else:
break
You just have to define your main() function like this.
def main():
global randomNumber
print ""
randomNumber = random.randrange(1, 1000)
number = input("I have a number between 1 and 1000. Can you guess my number? Please type your first guess: ")
guess(number)
And everything will be perfect. Hope this helps.