Python: Number Guessing Game - python

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.

Related

This program loops the same thing over and over again and I want it to do it once and continuing on to the other programs below the loop

When I run this, it just keeps on repeating itself asking for a number over and over again. I am a beginner at python so please don't judge.
import random
import time
while True:
guess = input("Please enter a lucky number between 1 to 10:\n")
number = random.randint(0, 10)
print ("Random number is " + str(number) + ":")
if guess == number:
print ("Awesome - You guessed correctly!")
answer = input('Would you like to try again? (y/n):\n')
def func():
if answer == 'n':
print ("Have a wonderful day!")
time.sleep(2)
else:
print("Good try, Would you like to play again? (y/n):")
func()
you can do it like this:
import random
import time
number = random.randint(0, 10)
while True:
guess = int(input("Please enter a lucky number between 1 to 10:\n"))
print ("Random number is " + str(number) + ":")
if guess == number:
print ("Awesome - You guessed correctly!")
answer = input('Would you like to try again? (y/n):\n')
if answer == 'n':
print ("Have a wonderful day!")
break
else:
print("generating new number...")
number = random.randint(0, 10)

How to make random.randit get new number, every time the game starts again

i have to make this GUESS THE NUMBER Gamme from 1-100 that will restart if user wants to play again,
the user can try to find the number 10 times.
But i have a problem..
every time the user says "yes" to play again,the program will not change the random number,i try to find some solution but i didnt
here is the code
import random
guesses = 0 # μετραει ποσες προσπαθειεςς εγιναν απο τον χρηστη
print("Hello,lets play a game...and try to find the number i have guess!!")
number = random.randint(1, 100)
**while guesses < 11:
print('Please Guess a number from (1-100):')
enter = input()
enter = int(enter)
guesses = guesses + 1
if enter < number:
print('This number you enter is lower,please try again')
if enter > number:
print('This number you enter is higher,please try again')
if enter == number:
score = 10 - guesses
score = str(score)
guesses = str(guesses)
print('Well Done, You found it! \nYor Score is' + score + '!')
print('DO you want to play again; yes/no:')
out = input()
if out == "no":
break
elif out == "yes":
guesses = 0
if guesses > 10:
number = str(number)
print("i'm sorry you lost, the number is " + number)
print("Have a great time")**
In addition to reset the guesses inside the elif out == "yes" block, reset also the number. Try:
elif out == "yes":
guesses = 0
number = random.randint(1, 100)

Using system.exit

I am trying to add a sys.exit to my code now, but I want it to display the print messages before quitting. Can I do this? Also, at the end of my code, I would like to give the user the option to quit or start again, but when they type quit after finishing the first game, it just uses quit as their name.
import random
import sys
def system_exit(exitCode):
sys.exit()
# uses randrange instead of randint for better results in Python 3.7
# randrange stops just before the upper range, use (1, 11) for 1-10
num = random.randrange(1, 11)
name = input("What is your name? Or if you would rather quit, type quit at
any time. " "\n")
i = name
while i != "quit":
print('Hello', name,'!')
while i.lower() == 'quit':
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.")
system_exit(4)
your_guess = input('Enter a number between 1 and 10.' '\n')
if (your_guess.lower() == "quit"):
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.") #this isn't showing up before closing
your_guess = int(your_guess)
# display the number guessed
print("Your number is", your_guess)
while num != your_guess:
if your_guess < num:
print("Your guess is too low.")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
elif your_guess > num:
print("Your guess is too high")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
else:
print ("Sorry, you did not select a number in the
range or selected to quit. Good bye.") #this isn't showing up before
closing
system_exit(4)
print("The correct number was", num)
print("***************************************************************")
name = input("What is your name? Or if you would rather quit, type
quit. ")
num = random.randrange(1, 11)
print("Thank you for playing!") #this isn't showing up before closing
system_exit(0)
Replace the following line of code:
your_guess = int(input('Enter a number between 1 and 10.'))
with the code below:
your_guess = input('Enter a number between 1 and 10.')
if (your_guess.lower() == 'quit'):
#print some break message
your_guess = int(your_guess)

I am trying to do the basic number guessing game on python

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"

Computer guessing game

import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.

Categories

Resources