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

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

Related

How can I get two variables to hold the amount of higher than and lower than guesses?

I am creating a game in which the computer selects a random number 1-10
Then the user guesses the number until they get it right.
The trouble I am having is that when the users enter the wrong answer the variables high or low should be updated, but it just continues looping until the user does enter the right answer. Which causes high and low to always be at 0.
Any ideas? I know there is probably something wrong with the way I am looping?
Any pushes in the right direction would be great!
# module to generate the random number
import random
def randomNum():
selection = random.randint(0,9)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = randomNum()
guess = userGuess()
high = 0
low = 0
if guess != correctNum:
print('uhoh try again!')
guess=userGuess()
elif guess > correctNum:
print('That guess is too high!')
high = high + 1
elif guess < correctNum:
print('That guess is too low')
low = low + 1
else:
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
main()
Try modifying your main function :
def main():
correctNum = randomNum()
guess = userGuess()
high = low = 0 # nifty way to assign the same integer to multiple variables
while guess != correctNum: # repeat until guess is correct
if guess > correctNum:
print('That guess is too high!')
high = high + 1
else:
print('That guess is too low')
low = low + 1
print('Try again!')
guess=userGuess()
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
Also, be careful with random.randint(0,9) : this will give a number between 0-9 (including 0 and 9, but never 10)!
You want to be doing random.randint(1, 10)
# module to generate the random number
import random
def get1to10():
selection = random.randint(1,10)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = get1to10()
guess = 0
high = 0
low = 0
# use a while loop to collect user input until their answer is right
while guess != correctNum:
guess = userGuess()
# use if statements to evaluate if it is < or >
if guess > correctNum:
print('This is too high!')
high = high + 1
continue
# use continue to keep going through the loop if these are true
elif guess < correctNum:
print('this is too low!')
low = low + 1
continue
else:
break
# the outcome of the game:
print('----------------------')
print('Guesses too high:', high)
print('Guesses too low:',low)
print('The correct answer was:', '*',correctNum,'*', sep = '' )
print('Thank you for playing!')
print('---------------------')
main()
I found this solution to work well for what I needed!
Thank you everyone who answered this post!
You can try using a dictionary:
guesses = {'Higher': [],
'Lower': [],
'Correct': False,
} # A Dictionary variable
def add_guess(number, correct_number):
if number > correct_number:
guesses['Higher'].append(number)
elif number < correct_number:
guesses['Lower'].append(number)
else:
guesses['Correct'] = True
return guesses
add_guess(number=5, correct_number=3) # Higher
add_guess(10, 3) # Higher
add_guess(2, 3) # Lower
# Correct is False, and higher has the numbers (10, 5) while lower has the numbers (2)
print(guesses)
add_guess(3, 3) # Correct should now be True
print(guesses)
This, of course, isn't the entire code but should point you in the right direction. There is a ton of resources on python dictionaries online.

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!

how to integrate a simple menu in python

This is my current HiLo game, I want to integrate a menu with 4 options, 1. read csv file 2. play game 3. show results and 4. exit, any help is appreciated.
Because I don't know where to start.
import\
random
n = random.randint(1,20)
print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")`enter code here`
You could place your game loop inside a menu loop, and all the code for csv file, etc. inside these loops...
However, it is surely preferable to learn a little bit about functions, in order to organize your code a little bit:
Here, I placed your game loop inside a function, and also created functions for the other options; right now, they only print what they should be doing, but as you add features, you will fill this with code.
import random
def read_csv():
print('reading csv')
def show_results():
print('showing results')
def play_game():
n = random.randint(1,20)
# print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")
while True:
choice = int(input("1. read csv file 2. play game 3. show results and 4. exit"))
if choice == 4:
break
elif choice == 2:
play_game()
elif choice == 3:
show_results()
elif choice == 1:
read_csv()

Number Guessing Game (Python)

Working in Python 3.
I'm still relatively new to Python (only a few weeks worth of knowledge).
The prompt that I was given for the program is to write a random number game where the user has to guess the random number (between 1 and 100) and is given hints of being either too low or too high if incorrect. The user would then guess again, and again until they reach the solution. After the solution, the number of guesses should tally at the end.
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
main()
I'm struggling to figure out how to make the loop work. I need the random number to be static while the user guesses with inputs. After each attempt, I also need them to be prompted with the correct message from the if/else check.
You could set 'userNum' to be 0, and encase all the input in a while loop:
userNum = 0
while (userNum != number):
This will continually loop the guessing game until the user's guess equals the random number. Here's the full code:
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
userNum = 0
while (userNum != number):
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
print("You win")
main()
You can just put your guesses in a simple loop:
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
while win == 0:
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
main()
Any of the other answers will work, but another check you can do for the loop is 'not win', which will stop the loop for any value of win that isn't zero.
while not win:
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
...
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
# input
while(True): #Infinite loop until the user guess the number.
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
break #Break out of the infinite loop
else:
message = "Too low, try again."
low += 1
print(message) ##Display the expected message
print()
print(message)
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
if __name__ == '__main__':
main()
There's so many ways you can go about this kind of task, it's what makes programming epic.
I have written a little something that answers your question, it even has a simple feel to it!
What i've done is done a for loop to give the user a total of range(10) tries. For every guess the user makes, it adds 1 'tries' to 0. In my if statement, all I'm wanting to know is if the guess is the same as the_number and below the number of tries available, you've done it. Otherwise, higher or lower :)
Hope this helps!
import random
print("\nWelcome to the guessing game 2.0")
print("Example for Stack Overflow!\n")
the_number = random.randint(1, 100)
tries = 0
for tries in range(10):
guess = int(input("Guess a number: "))
tries += 1
if guess == the_number and tries <= 10:
print("\nCongratulations! You've guessed it in", tries, "tries!")
break
elif guess < the_number and tries < 10:
print("Higher...")
tries += 1
elif guess > the_number and tries < 10:
print("Lower...")
tries += 1
elif tries >= 11:
print("\nI'm afraid to haven't got any tries left. You've exceeded the limit.")
import random
def display_title():
return print("Number Guessing Game")
def play_game():
cpu_num = random.randint(1, 10)
user_guess = int(input("Guess a number from 1 to 10:")
while user_guess != cpu_num:
print("Try Again")
user_guess = int(input("Guess a number from 1 to 10:"))
if user_guess == cpu_num:
print("Correct!")
def main():
title = print(display_title())
game = print(play_game())
return title, game
print(main())

Categories