Reverse Number Guessing Game Python - python

So, recently i have been trying to program a reverse number guessing game whereby the computer tries to guess the number i have in mind. The output i should get is as shown below:
Enter the range: 6
Think of a random number between 1 and 6 and press enter once done!
Is it smaller than 4, 'y' or 'n'?y
Is it smaller than 2, 'y' or 'n'?n
Is it smaller than 3, 'y' or 'n'?y
Wonderful it took me 3 questions to find out that you had the number 2 in mind!
These are my codes so far:
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y' or 'n'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
else:
print ('Please only type y, Y, n or N as responses')
numberHasBeenGuessed = True
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
The main algorithm is working but somehow it cant detect it when the number has been 'guessed'..
does anyone know why?
I will greatly appreciate the help :)

Here is a version using try/except
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
elif response == "y" or response == "Y":
highBound = randomNumber - 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
When it encounters a ValueError, it will take it that it has found your number. Please make sure there are no other situations that can result in an incorrect answer with this code, as I obviously haven't tested it thoroughly.
You could also put the try/except clauses in a def to make it more compact as they are the same pieces of code, but I wasn't sure if that was allowed or not for your project, so I left it.

You have numberHasBeenGuessed = True outside of the while loop - which means that it can't get called until the loop is over - so it will be forever stuck.
When it gets to your guess - lets say I have the number 7. Your program asks 'Is 7 smaller or larger than 7?' Obviously that makes no sense, 7 is 7. 7 is not smaller or larger than 7: and your program knows that and crashes. So you need to introduce a new user input option:
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "Thats it": #New input option 'Thats it'
numberHasBeenGuessed = True #Stops the while loop
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
Now, you can input 'Thats it' when your number is guessed and the program finishes with the output you want. (Of course, change the inputs and what not to what you want)
Also final programmer tip: comment your code with hashtags, so you know (and others helping) what each part does.

Related

Is it possible this way? Letting computer to guess my number

I want pc to find the number in my mind with random function "every time"
so i tried something but not sure this is the correct direction and its not working as intended
how am i supposed to tell pc to guess higher than the previous guess
ps:code is not complete just wondering is it possible to do this way
def computer_guess():
myguess = int(input("Please enter your guess: "))
pcguess = randint(1, 10)
feedback = ""
print(pcguess)
while myguess != pcguess:
if myguess > pcguess:
feedback = input("was i close?: ")
return feedback, myguess
while feedback == "go higher":
x = pcguess
pcguess2 = randint(x, myguess)
print(pcguess2)
I wrote this a few years ago and it's similar to what you're trying to do except this only asks for user input once then calls random and shrinks the range for the next guess until the computer guess is equal to the user input.
import random
low = 0
high = 100
n = int(input(f'Chose a number between {low} and {high}:'))
count = 0
guess = random.randint(0,100)
lower_guess = low
upper_guess = high
while n != "guess":
count +=1
if guess < n:
lower_guess = guess+1
print(guess)
print("is low")
next_guess = random.randint(lower_guess , upper_guess)
guess = next_guess
elif guess > n:
upper_guess = guess-1
print(guess)
print("is high")
next_guess = random.randint(lower_guess , upper_guess)
guess = next_guess
else:
print("it is " + str(guess) + '. I guessed it in ' + str(count) + ' attempts')
break

Computer guessing number python

I'm very new to programming and am starting off with python. I was tasked to create a random number guessing game. The idea is to have the computer guesses the user's input number. Though I'm having a bit of trouble getting the program to recognize that it has found the number. Here's my code and if you can help that'd be great! The program right now is only printing random numbers and won't stop even if the right number is printed that is the problem
import random
tries = 1
guessNum = random.randint(1, 100)
realNum = int(input("Input a number from 1 to 100 for the computer to guess: "))
print("Is the number " + str(guessNum) + "?")
answer = input("Type yes, or no: ")
answerLower = answer.lower()
if answerLower == 'yes':
if guessNum == realNum:
print("Seems like I got it in " + str(tries) + " try!")
else:
print("Wait I got it wrong though, I guessed " + str(guessNum) + " and your number was " + str(realNum) + ", so that means I'm acutally wrong." )
else:
print("Is the number higher or lower than " + str(guessNum))
lowOr = input("Type in lower or higher: ")
lowOrlower = lowOr.lower()
import random
guessNum2 = random.randint(guessNum, 100)
import random
guessNum3 = random.randint(1, guessNum)
while realNum != guessNum2 or guessNum3:
if lowOr == 'higher':
tries += 1
import random
guessNum2 = random.randint(guessNum, 100)
print(str(guessNum2))
input()
else:
tries += 1
import random
guessNum3 = random.randint(1, guessNum)
print(str(guessNum3))
input()
print("I got it!")
input()
How about something along the lines of:
import random
realnum = int(input('PICK PROMPT\n'))
narrowguess = random.randint(1,100)
if narrowguess == realnum:
print('CORRECT')
exit(1)
print(narrowguess)
highorlow = input('Higher or Lower Prompt\n')
if highorlow == 'higher':
while True:
try:
guess = random.randint(narrowguess,100)
print(guess)
while realnum != guess:
guess = random.randint(narrowguess,100)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
elif highorlow == 'lower':
while True:
try:
guess = random.randint(1,narrowguess)
print(guess)
while realnum != guess:
guess = random.randint(1,narrowguess)
print(guess)
input()
print(guess)
print('Got It!')
break
except:
raise
This code is just a skeleton, add all of your details to it however you like.

The list does not add up

I am creating a random number generator. I want to add up the guess tries I had for different trials and find the average. However, when I add up the list, it will only calculate how many guesses I had for the first trials divided by the number of trials. How could I fix this problem?
import random
import string
#get the instruction ready
def display_instruction():
filename = "guessing_game.txt"
filemode = "r"
file = open(filename, filemode)
contents = file.read()
file.close()
print(contents)
#bring the instruction
def main():
display_instruction()
main()
#set the random letter
alpha_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
letter = random.choice(alpha_list)
print(letter)
guess = ''
dist = []
number_of_guess = []
number_of_game = 1
guess_number = 1
game = True
if guess_number < 5:
rank = 'expert'
elif guess_number >= 5 and guess_number < 10:
rank = 'intermidiate'
else:
rank = beginner
while game == True:
guess_number = int(guess_number)
guess_number += 1
#add the input of user
guess = input("I am thinking of a letter between a and z" + "\n" + "Take a guess ")
#what happens if it is not a letter?
if guess not in alpha_list:
print("Invalid input")
elif alpha_list.index(guess) > alpha_list.index(letter):
print("too high")
dist.append(alpha_list.index(guess) - alpha_list.index(letter))
number_of_guess.append(guess)
#what happens if the guess is less than the letter?
elif alpha_list.index(guess) < alpha_list.index(letter):
print("too low")
dist.append(alpha_list.index(letter) - alpha_list.index(guess))
number_of_guess.append(guess)
elif guess == letter:
print("Good job, you guessed the correct letter!")
guess_number = str(guess_number)
print("---MY STATS---" + "\n" + "Number of Guesses:", guess_number + "\n" + "Level", rank)
replay = input("Would you like to play again? Y/N")
if replay == 'y' or replay == 'Y':
number_of_game += 1
game = True
else:
game = False
print(number_of_guess)
print("---MY STATS---" + "\n" + "Lowest Number of Guesses:" + "\n" + "Lowest Number of Guesses:" + "\n" + "Average Number of Guesses:", str(len(number_of_guess)/number_of_game))
If you want to get the average guesses per game, why you divide the length of the guess list? Why it is even a list? You can save it as an int do:
... "Average Number of Guesses:", (number_of_guess / number_of_game))
Also, note the following:
You initialize number_of_guess with 1, means that you will always count one more guess for the first round.
You do not choose a new letter between each round!

Why does python show 'list index out of range' error?

I am very new to python, and started learning just 1 week ago. This program works very well except when I enter a number into guess1 variable that starts with 0.
import random
import sys
def script():
while True:
number1 = random.randint(1000, 9999)
number1 = int(number1)
while True:
print ("Enter Your Guess")
guess1 = input()
guess1 = int(guess1)
while True:
if guess1 != number1:
break
elif guess1 == number1:
print ("Your Guess Was Right!")
print ("Do you want to play again? Type YES or NO")
ask = input()
ask = str(ask)
if ask == "YES" or ask == "yes":
script()
elif ask == "NO" or ask == "no":
sys.exit()
else:
print ("Invalid input, try again.")
continue
number = list(str(number1))
guess = list(str(guess1))
if len(guess) > 4:
print ("Please type a 4-digit number")
continue
bulls = 0
wr = 0
cows = 0
a = 3
while a >= 0:
if number[a] == guess[a]:
number[a] = 'a'
guess[a] = 'b'
bulls += 1
a -= 1
b = 0
c = 0
while b < 4:
c = 0
while c < 4:
if number[b] == guess[c]:
number[b] = 'a'
guess[c] = 'b'
wr += 1
c += 1
b += 1
z = bulls + wr
cows = 4 - z
bulls = str(bulls)
cows = str(cows)
wr = str(wr)
print ("Cows: "+cows)
print ("Bulls: "+bulls)
print ("Wrongly Placed: "+wr)
break
script()
This was a program written for a game, in which a 4-digit number is to be guessed. We do it by starting with a random number, and we get clues in the form of cows, bulls and wrongly placed. Cows mean the number is wrong, Bulls mean the number is right, and wrongly placed means the number is right but wrongly placed.
The whole thing works properly, but when I enter a number starting with 0, it shows something like this :-
Traceback (most recent call last):
File "GuessingGame.py", line 61, in <module>
script()
File "GuessingGame.py", line 36, in script
if number[a] == guess[a]:
IndexError: list index out of range
Please help, thanks!
UPDATE:
Thanks to user #blue_note 's answer, The program works now! This is how it has been modified -
import random
import sys
def script():
while True:
number1 = random.randint(1000, 9999)
number1 = int(number1)
while True:
print ("Enter Your Guess")
guess1 = input()
number = list(str(number1))
guess = list(str(guess1))
if guess[0] == 0:
guess1 = str(guess1)
else:
guess1 = int(guess1)
while True:
if guess1 != number1:
break
elif guess1 == number1:
print ("Your Guess Was Right!")
print ("Do you want to play again? Type YES or NO")
ask = input()
ask = str(ask)
if ask == "YES" or ask == "yes":
script()
elif ask == "NO" or ask == "no":
sys.exit()
else:
print ("Invalid input, try again.")
continue
bulls = 0
wr = 0
cows = 0
a = 3
while a >= 0:
if number[a] == guess[a]:
number[a] = 'a'
guess[a] = 'b'
bulls += 1
a -= 1
b = 0
c = 0
while b < 4:
c = 0
while c < 4:
if number[b] == guess[c]:
number[b] = 'a'
guess[c] = 'b'
wr += 1
c += 1
b += 1
z = bulls + wr
cows = 4 - z
bulls = str(bulls)
cows = str(cows)
wr = str(wr)
print ("Cows: "+cows)
print ("Bulls: "+bulls)
print ("Wrongly Placed: "+wr)
break
script()
Since my guess will always be wrong if the first digit is 0, I don't have the need to convert it into int.
Again, thanks for the help guys! This was my first question on the website. It is really a cool website.
When you pass, say, an integer starting with 0, say, 0123, and you convert it to int in the next line, you are left with 123 (3 digits). Later, you do number = list(str(number1)), so your number is ['1', '2', '3'] (length 3). Then, you try to get number[a] with a=3, and that's were you get the error.
You could do something like
number = list(str(number1) if number1 > 999 else '0' + str(number1))

Changing random number in python

import random
def guess_number_game():
number = random.randint(1, 101)
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
while playing:
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
playing = False
points += 1
play_again = True
while play_again:
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
play_again = False
elif again == 'no':
play_again = False
else:
print('please type yes or no')
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()
i just started to learn python and i made this simple number guessing game, but
if you try to play again you get the same number.
e.g. the number is 78 and you guessed it but you want to play again so you say you want to play again the number is still 78.
so how do i make it so that the number changes everytime someone plays the game
You need to set the number to the random generated number in the loop.
Example:
import random
def guess_number_game():
playing = True
while playing:
number = random.randint(1, 101)
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
print(number)
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
playing = False
points += 1
play_again = True
while play_again:
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
play_again = False
elif again == 'no':
play_again = False
else:
print('please type yes or no')
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()
import random
def guess_number_game():
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
play_again=False
number = random.randint(1, 101)
#print(number)
while playing:
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
number = random.randint(1, 101)
points += 1
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
elif again == 'no':
playing = False
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()
You define your random number outside of the game, set a new random number when someone decides to play again!
import random
def guess_number_game():
number = randbelow(1, 101)
points = 0
print('You already have ' + str(points) + ' point(s)')
playing = True
while playing:
print(number)
guess = int(input('Guess the number between 1 and 100: '))
if guess > number:
print('lower')
elif guess < number:
print('Higher')
else:
print('You got it, Good job!!')
playing = False
points += 1
play_again = True
while play_again:
again = input('Do you want to play again type yes/no: ')
if again == 'yes':
playing = True
play_again = False
number = randbelow(1, 101)
elif again == 'no':
play_again = False
else:
print('please type yes or no')
print('Now you have ' + str(points) + ' point(s)')
guess_number_game()

Categories