Variable value inside loop vs. outside loop - python

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

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!

Python Guess number game - While loop not responding

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:

Beginner Python-Looping to the beginning of a programme

I will start fresh! I have included the full code so you can get a picture for what i am trying to do. Prob (1) I can not loop back to the very beginning. Prob (2) It is not looping # the While higher_or_lower part of the code. it just goes through the if and else higher_or_lower statements. Thanks
done = False
while done == False:
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess)
input("Correct!\nWell done\n\n")
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the number game. Goodbye")
done = True
breaK
Ok, a primer in how Python indentation works.
number = 1
while number < 10:
print(number)
number += 1
print("this will print everytime because it's inside the while")
Output:
1
this will print everytime because it's inside the while
2
this will print everytime because it's inside the while
3
this will print everytime because it's inside the while
4
this will print everytime because it's inside the while
5
this will print everytime because it's inside the while
6
this will print everytime because it's inside the while
7
this will print everytime because it's inside the while
8
this will print everytime because it's inside the while
9
this will print everytime because it's inside the while
Notice that the second print prints every time because of it's indentation.
Now the second example:
number = 1
while number < 10:
print(number)
number += 1
print("this will print AFTER the loop ends")
Output:
1
2
3
4
5
6
7
8
9
this will print AFTER the loop ends
See how it only printed after the loop ended? That is because of the indentation. You should correct your code and indent it properly...
Ok, I corrected the code and it seems to be working now. Most of it was because of the indentation. Please try to understand how it works...
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result #this was out indented
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a guessing number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess) # this was out indented
print("Correct!\nWell done\n\n") # this all the way to the bottom was out indented
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the awesome number game. Goodbye")
done = True
It looks like adding a little structure would help you out.
Something like this might help you with doing your control flow. Hopefully gives you an outline that makes sense and makes it easier to run the loop multiple times.
""" Guess the number game.
"""
import random
def is_same(targ, num):
""" Check for correct entry. """
if targ == num:
result = "WIN"
elif targ > num:
result = "LOW"
else:
result = "HIGH"
return result
def play_game():
""" Play the game 1 time, returns play_again """
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print("""\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""")
Choose_Level = input("\t\tPlease choose your Level : ")
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
# this could be simplified to: while choose_level not in 'EMF':
Choose_Level = input("Sorry. You must type in one of the letters " +
"'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! " +
"You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1, 10)
elif Choose_Level == "M":
computer_number = random.randint(1, 50)
else:
computer_number = random.randint(1, 100)
counter = 1
higher_or_lower = ""
while higher_or_lower != "WIN":
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter += 1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
print("\nSorry, you are to low. Please try again.\n:")
elif higher_or_lower == "HIGH":
print("Guess attempts", counter)
print("\nSorry, To high. Please try again. \n:")
else:
print("Correct!\nWell done\n\n")
break
print("""
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = input("\t\t Please choose a option 'S' or 'E' ")
while start_again != "S" and start_again != "E":
# can simplify: while start_again not in 'SE':
start_again = input("You must enter a upper case letter" +
"'S' or 'E' to continue")
if start_again == "S":
return True
else:
return False
def main():
""" Main loop for playing the game. """
play_again = True
while play_again:
play_again = play_game()
print("Thanks for playing the number game. Goodbye")
if __name__ == '__main__':
main()

Categories