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.
Related
from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break
I'm a very new programmer(started less than a month ago). I really need some help with this.
Sorry if it's a bit long...
How this works is that my guesses go down every time I get something wrong(pretty obvious). Or it is supposed to, anyway.
This is a program I created as a prototype for a hangman project. Once I get this right, I'll be able to attempt the bigger project. Tell me if the full command above works differently for you or if you have any suggestion as to how to make it shorter or better or it's too early for me to attempt a project as big as this. Thank you!
import random
player_name = input("What is your name? ")
print("Good luck, " + player_name + "!")
words = ["program", "giraffe", "python", "lesson", "rainbows", "unicorns", "keys", "exercise"]
guess = " "
repeat = True
word = random.choice(words)
guesses = int(len(word))
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
the issue is with the scope of your conditionals
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
this will fix the guesses issue, but you'll need to refactor the play-again logic.
Something like this
repeat = True
gameOver = False
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
gameOver = True
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
gameOver = True
if gameOver:
playAgain = input("Do you want to play again? (input Yes/No)")
if playAgain == "Yes" or "yes":
word = random.choice(words)
repeat = True
gameOver = False
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...
With my guess the number program, when I try to run it tells me the the variable "number" is not defined. I would appreciate it and be thankful if someone came to my aid in this!
import random
guesses = 0
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
Your problem is that number is not defined in the function correct. number is defined in _main_. When you call correct in _main_, it does not get access to number.
This is the fixed version of your code:
import random
guesses = 0
number = random.randint(1, 100)
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
What I changed is I moved the definition of number to the top, which allowed it to be accessed by all functions in the module.
Also, your code style is not very good. Firstly, do not name your main function _main_, instead use main. Additionally, you don't need a function to print out 'lower' and 'higher.' Here is some improved code:
import random
def main():
number = random.randint(1, 100)
guesses = 0
while True:
guessed_num = int(input('Guess the number: '))
guesses += 1
if guessed_num > number:
print('Guess lower!')
elif guessed_num < number:
print('Guess higher!')
else:
print('Correct!')
print('The number was {}'.format(number))
print('It took you {} guesses.'.format(guesses))
break
main()
Your specific problem is that the variable number is not defined in function correct(). It can be solved by passing number as an argument to correct().
But even if you correct that problem, your program has another major issue. You have defined guesses globally, but you still pass guesses as an argument to lower(), higher() and correct(). This creates a duplicate variable guesses inside the scope of these functions and each time you call either of these functions, it is this duplicate variable that is being incremented and not the one you created globally. So no matter how many guesses the user takes, it will always print
You took 1 guesses.
Solution:
Define the functions lower() and higher() with no arguments. Tell those functions thatSo ultimately this code should work:
import random
guesses = 0
def higher():
global guesses
print("Lower")
guesses = guesses + 1
def lower():
global guesses
print("Higher")
guesses = guesses + 1
def correct(number):
global guesses
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_():
print("Welcome to guess the number")
guesses = 0
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher()
elif guess < number:
lower()
elif guess == number:
correct(number)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
_main_()
elif answer == "N":
exit()
else:
exit()
_main_()
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.