Python Guess number game - While loop not responding - python

I am a relative newcomer and was trying to create a game where the user and the comp take turns at guessing each others games. I know I am doing something wrong in the while / if operators when the user enters a string eg. Y.
In two places:
1. where the user decides who should go first (if a in ["Y", "y"]
2. while loop in compguess function (while ans = False:) it just skips down.
a = input("Shall I guess first? (Y/N):")
userscore = 1
compscore = 1
def compguess():
global compscore
low = 0
high = 100
c = 50
ans = False
while ans = False:
print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
def userguess():
global userscore
g = r.randint(1,100)
h = input("Enter your guess number:")
i = int(h)
while g != i:
if g > i:
h = input("You guessed lower. Guess again:")
i = int(h)
userscore = userscore + 1
else:
h = input("You guessed higher. Guess again:")
i = int(h)
userscore = userscore + 1
if a in ["Y", "y"]:
compguess()
userguess()
else:
userguess()
compguess()
if userscore == compscore:
print("Its a tie !!")
elif userscore < compscore:
print ("Congrats ! You won !")
else:
print ("I won !! Better luck next time")

I'd change your while loop condition to:
while not ans:
Also, in r.randint(1,100), r is undefined. If you want to use a function from random, you need to import it:
You could do either import random or from random import randint. If you want to keep the r, you can do import random as r.
You should also indicate when the guessing games end. Although it's implied they flow right into each other and I was confused at first.
The wording is incorrect for the computer guessing:
Is the number 50 ?
Enter Y if correct / L if your number is lower or H if higher:H
Is the number 25 ?
Enter Y if correct / L if your number is lower or H if higher:L
Is the number 37 ?
Enter Y if correct / L if your number is lower or H if higher:Y
I won !! Better luck next time
Initial guess is 50. Then, I say my number is higher. Then the subsequent guess is lower. You reversed either the math or the phrasing.

while ans = False:
should be
while ans == False:

print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
Here you check if d is H (higher) and you calculate like it is lower ((50 + 0) /2) = 25
So you need to switch that
Also you forgot one more = in while ans = False:

Related

designing a game in python where random mathematical problems appear for the user to solve

The code is supposed to generate random equations for the user to answer with num1 being in the range of 1 to 9 while num2 in the range 0,10
The user starts with 100 points
if user enters x the program terminates
if user enter wrong answer the score decreases by 10
if user enters correct answer the score increases by 9
I've been successful in doing steps one to 3 however when it comes to checking if the inputted answer by the user is correct it always returns it as wrong even if its correct example
I assume this is because my code doesn't evaluate the question and been trying to figure out why
import random
# set variables
score = 100 # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9) # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10) # this variable will be a random number between 0 and 10
# this function prints the dashes
def dash():
print("-" * 50)
while score >= 0 and score <= 200:
dash()
print("You currently hold: ", score, " points")
print("Get more than 200 points you win, under 0 you lose")
sign = random.choice(operator) # chooses random operator
real_answer = number_1,sign,number_2
print(str(number_1) + str(sign) + str(number_2), "?")
dash()
print("Press x to close program")
answer = input("Enter your guess of number: ")
if answer == "x":
print("Program has been terminated properly")
break
elif answer == real_answer:
score = score + 9
continue
elif answer != real_answer:
score = score - 10
continue
if score < 0:
print("Unlucky, You lost")
elif score > 200:
print("CONGRATULATIONS YOU WON")
Issue was that real_answer and inputted answer were different data types, this should fix it by making them both floats.
import random
# set variables
score = 100 # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9) # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10) # this variable will be a random number between 0 and 10
# this function prints the dashes
def dash():
print("-" * 50)
while score >= 0 and score <= 200:
dash()
print("You currently hold: ", score, " points")
print("Get more than 200 points you win, under 0 you lose")
sign = random.choice(operator) # chooses random operator
# make a variable called real answer equal to the answer of the equation
if sign == "+":
real_answer = number_1 + number_2
elif sign == "-":
real_answer = number_1 - number_2
elif sign == "*":
real_answer = number_1 * number_2
elif sign == "/":
real_answer = number_1 / number_2
print(str(number_1) + str(sign) + str(number_2), "?")
dash()
print("Press x to close program")
answer = input("Enter your guess of number: ")
if answer == "x":
print("Program has been terminated properly")
break
elif float(answer) == real_answer:
score = score + 9
continue
elif float(answer) != real_answer:
score = score - 10
continue
if score < 0:
print("Unlucky, You lost")
elif score > 200:
print("CONGRATULATIONS YOU WON")
The error here is that the variable real_answer is not an integer, but instead a tuple. For example, 1+7 gives (1, '+', 7), instead of 8.
Their are two main fixes to this:
The first fix is to create a dictionary which can contain the functions for each symbol. It would look something like this:
signs = {
'+': (lambda a, b: a + b),
'-': (lambda a, b: a - b),
'*': (lambda a, b: a * b),
'/': (lambda a, b: a // b)
}
Now, to call this function, you can do real_answer = signs[sign](number_1,number_2). Essentially, this calls the function from the dictionary depending on what the sign is. If the sign is / the code recognises that divide means lambda a, b: a // b and calls this function with number_1 and number_2
The other, but slightly more messy verisio is to use eval. What eval does is runs a string as code. For example, you could do:
real_answer = eval(f"{number_1}{sign}{number_2)")
While this does work, eval is generally not the best method.
The last thing to point out is that you don't cast your answer variables to an integer. When comparing numbers in your if statements, you want to use int(answer) to make sure you're using the integer version of your answer.
The full code should look something like this:
import random
# set variables
score = 100 # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9) # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10) # this variable will be a random number between 0 and 10
signs = {
'+': (lambda a, b: a + b),
'-': (lambda a, b: a - b),
'*': (lambda a, b: a * b),
'/': (lambda a, b: a // b)
}
# this function prints the dashes
def dash():
print("-" * 50)
while score >= 0 and score <= 200:
dash()
print("You currently hold: ", score, " points")
print("Get more than 200 points you win, under 0 you lose")
sign = random.choice(operator) # chooses random operator
real_answer = signs[sign](number_1,number_2)
print(str(number_1) + str(sign) + str(number_2), "?")
dash()
print("Press x to close program")
answer = input("Enter your guess of number: ")
if answer == "x":
print("Program has been terminated properly")
break
elif int(answer) == real_answer:
score = score + 9
continue
elif int(answer) != real_answer:
score = score - 10
continue
if score < 0:
print("Unlucky, You lost")
elif score > 200:
print("CONGRATULATIONS YOU WON")

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

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))

Variable value inside loop vs. outside loop

I'm curious why the following blocks of syntax treat the variable "ans" differently depending on where "ans" is in the code. In the first example, "ans" increments/decrements correctly based on user input. In the second, "ans" stays equal to the original value (in this case 50) despite user input. The variables "low" and "high" are outside of the loop but still save the values from the loop, while "ans" is outside the loop and does not. Appreciate the help.
1.
low = 0
high = 100
print("Please think of a number between 0 and 100!")
while True:
ans = int((high + low)/2)
print("Is your secret number", str(ans), "?")
x = input("Enter h if too high, l if too low, or c if correct: ")
if x == "l":
low = ans
elif x == "h":
high = ans
elif x == "c":
print("Game over. Your secret number was: ", ans)
break
else:
print("Sorry I did not understand your input.")
x = input("Enter h if too high, l if too low, or c if correct: ")
2.
low = 0
high = 100
ans = int((high + low)/2)
print("Please think of a number between 0 and 100!")
while True:
print("Is your secret number", str(ans), "?")
x = input("Enter h if too high, l if too low, or c if correct: ")
if x == "l":
low = ans
elif x == "h":
high = ans
elif x == "c":
print("Game over. Your secret number was: ", ans)
break
else:
print("Sorry I did not understand your input.")
x = input("Enter h if too high, l if too low, or c if correct: ")

Categories