how to integrate a simple menu in python - 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()

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

Repeated prints from loop

I am trying to create a program similar to the game Mastermind. I am having an issue in my while loop where it constantly prints "You got " + str(correct) + " correct!"
import random
import replit
def useranswer(input):
userinput.append(input)
return input
number = 0
answer = 0
guesses = 0
correct = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
for i in range(0,4):
answer = str(input('Give me a number: '))
useranswer(answer)
print(generation)
while userinput != generation:
guesses += 1
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got " + str(correct) + " correct! ")
correct = 0
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " + str(guesses) + " tries!")
If you want it to exit the while loop after printing the line print("You got " + str(correct) + " correct! ") then you'll need to do something within the while loop to make the check not true.
Right now if userinput != generation is true then it will loop forever because nothing in the loop ever changes that to be false.
You need to get the player's input within the while loop if you want it to keep looping until something happens, otherwise an if statement might be better.
Ive made couple of changes to your code. Take a look at it
Removed def userinput().
Moved userinput inside the while loop.
import random
import replit
number = 0
answer = 0
guesses = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
while userinput != generation:
guesses += 1
correct = 0
userinput = []
for i in range(0,4):
answer = int(input('Give me a number: '))
userinput.append(answer)
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got ",correct, " correct! ")
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " ,guesses, " tries!")

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!

random.randint seems to not work, i think

i was doing a Guess the number "project" and I got stuck, when i run it, it ask me to chose a number then nothing happends, here's the code:
import random
play_game = "y"
while (play_game == "y"):
answer = random.randint(1, 100)
try_number = input("Guess a number between 1 and 100: ")
try_number = int(try_number)
counter = 1
while try_number != answer:
if try_number > answer:
print("Your number is too large")
if try_number < answer:
print("Your number is to small")
try_number = int(input("Guess a number between 1 and 100: "))
counter = counter + 1
print("You got it! You tried " + str(counter) + "times")
play_game = input("Continue? ")
Thank you for your time!
Perhaps you're running this on Python 2 instead of Python 3? On Python 2, you need to replace "input" with "raw_input", otherwise it will try to eval() the contents of the input, which is not what you want.
Because you mentioned python 3 in your tags, I'm assuming this is python 3 (Use raw_input for python 2). You have to press enter after inputting your number from 1 to 100. When i tried your code, it worked no problem.
import random
play_game = "y"
while (play_game == "y"):
answer = random.randint(1, 100)
try_number = input("Guess a number between 1 and 100: ")
try_number = int(try_number)
counter = 1
while try_number != answer:
if try_number > answer:
print("Your number is too large")
if try_number < answer:
print("Your number is to small")
try_number = int(input("Guess a number between 1 and 100: "))
counter = counter + 1
print("You got it! You tried " + str(counter) + "times")
play_game = input("Continue? ")

Categories