Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create a simple guessing game. Everything works absolutely fine, as it should. But, it can't seem to exit the first while loop which checks if the variable 'guessflag' is less than 15 or not. I also checked whether it is being updated or not by adding some print statements. Please help.
It even exits when it meets the condition which says to exit the program when the user guesses correctly. When I consulted some other queries regarding the same problem at stackoverflow, I tried to make sure that those mistakes don't happen to me. Also, I have to add some more finishing touches to reduce time taken by the program to run, but currently this works absolutely fine.
import random
point = 101
randomint = random.randint(0,100)
hintflag = 0
hintmessage = "To claim a hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***"
guessflag = 0
while guessflag <=15:
def init(param):
global guess, point, guessflag
if(param == 1):
global point,guessflag
point = point - 1
guessflag = guessflag + 1
print(hintmessage)
guess = int(input("Enter your guess. It should be between 1 and 100... "))
proceed()
def proceed():
global hintflag
global point
if (guess < 1 or (guess > 100 and guess != 102)):
print('')
print("Please enter a number between 1 and 100... ")
init(2)
elif ((guess == 102)and(hintflag < 2 and hintflag >= 0)):
if(hintflag == 0):
checkrandeven()
if(hintflag == 1):
checkrandmultiple3()
else:
match()
def checkrandmultiple3():
if (randomint % 3 == 0):
global israndmultiple3, point, hintmessage, hintflag
hintflag = hintflag + 1
israndmultiple3 = True
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is a multiple of 3.")
print("Points: "+str(point))
init(2)
else:
hintflag = hintflag+1
israndmultiple3 = False
point = point-20
hintmessage = 'You have exhausted all your hints'
print("The number to be guessed is not a multiple of 3.")
print("Points: "+str(point))
init(2)
def checkrandeven():
if (randomint % 2 == 0):
global israndeven, point, hintmessage, hintflag
hintflag = hintflag+1
israndeven = True
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print('')
print("Your hint is...")
print("The number to be guessed is even.")
print("***YOU HAVE SPENT 20 POINTS***")
print("Points: "+str(point))
init(2)
else:
israndeven = False
hintflag = hintflag+1
point = point-20
hintmessage = 'To claim your ***LAST*** hint, enter 102 in the input below. ***THE HINT WILL COME AT A COST OF 20 POINTS***'
print("The number to be guessed is odd.")
print("Points: "+str(point))
init(2)
def match():
global randomint, guess, point, guessflag, hintflag
if(randomint != guess):
if(randomint < guess):
print("Try Again! Your number was too high; Try a number lower than "+str(guess))
init(1)
if(randomint > guess):
print("Try Again! Your number was too low; Try a number higher than "+str(guess))
init(1)
if(randomint == guess):
print ("CONGRATULATIONS! You won!")
print ("It took you "+ str(guessflag) + " tries, "+ str(hintflag)+" hints to beat the game!")
print("The number of points you finished with are... "+ str(point))
exit()
init(1)
The 'init(1)' call in your while loop is only actually called once, and your 4 functions call each other recursively. In other words, you never actually finish the first iteration of your while loop, you just go further and further down a chain of:
init -> proceed -> checkrandeven (or checkrandmultiple3) -> init -> proceed -> checkrandeven -> init -> proceed ...
Basically you need to think about restructuring your code to avoid the recursion. Try returning outputs within the main loop and then calling subsequent functions from there.
Related
Looking on for some guidance on how to write a python code
that executes the following:
The program will ask for math problems to solve.
The program will asks for the number of problems.
And asks for how many attempts for each problem.
For example:
Enter amount of programs: 4
Enter amount of attempts: 5
what is: 4x3 =?
Your answer: 16
and so goes on to another attempt if wrong if correct moves onto another problem, just like before and exits when attempts or problems are finished.
I have this code but I want to it only do multiplication ONLY and would like to know how to integrate how to put additional code to limit how many time one can solve the question and how many questions it asks
import random
def display_separator():
print("-" * 24)
def get_user_input():
user_input = int(input("Enter your choice: "))
while user_input > 5 or user_input <= 0:
print("Invalid menu option.")
user_input = int(input("Please try again: "))
else:
return user_input
def get_user_solution(problem):
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
return result
def check_solution(user_solution, solution, count):
if user_solution == solution:
count = count + 1
print("Correct.")
return count
else:
print("Incorrect.")
return count
def menu_option(index, count):
number_one = random.randrange(1, 21)
number_two = random.randrange(1, 21)
problem = str(number_one) + " + " + str(number_two)
solution = number_one + number_two
user_solution = get_user_solution(problem)
count = check_solution(user_solution, solution, count)
def display_result(total, correct):
if total > 0:
result = correct / total
percentage = round((result * 100), 2)
if total == 0:
percentage = 0
print("You answered", total, "questions with", correct, "correct.")
print("Your score is ", percentage, "%. Thank you.", sep = "")
def main():
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
main()
As far as making sure you're only allowing multiplication problems, the following function should work.
def valid_equation(user_input):
valid = True
for char in user_input:
if not(char.isnumeric() or char == "*"):
valid = False
return valid
Then after each user_input you can run this function and it will return True if the only things in the users string are numbers and the * sign and False otherwise. Then you just need to check the return value with a if statement that tells the user that their input is invalid if it returns False. You can add more "or" operations to the if statement if you want to allow other things. Like if you want to allow spaces (or char == " ").
As far as limiting the number of times a user can try to answer, and limiting the number of questions asked, you just need to store the values the user enters when you ask them these numbers. From there you can do nested while loops for the main game.
i = 0
user_failed = False
while ((i < number_of_questions) and (user_failed == False)):
j = 0
while ((j < number_of_attempts) and (user_correct == False)):
#Insert question asking code here
#In this case if the user is correct it would make user_correct = True.
j += 1
if j == number_of_attempts:
user_failed = True
i += 1
So in this situation, the outer while loop will iterate until all of the questions have been asked, or the user has failed the game. The inner loop will iterate until the user has used up all of their attempts for the question, or the user has passed the question. If the loop exits because the user used up all of their attempts, the for loop will trigger making the user lose and causing the outer loop to stop executing. If it does not it will add one to i, saying that another question has been asked, and continue.
These are just some ideas on how to solve the kinds of problems you're asking about. I'll leave the decision on how exactly to implement something like this into your code, or if you decide to change parts of your code to better facilitate systems like this up to you. Hope this helps and have a great one!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Im currently in make of creating a math game that involves: addition, subtraction, multiplication and division. These parts with purple borders around them are the questions that i had created for the addition part when the user chooses to pick addition.
I dont know how to make these question be shown at random. When the user goes to select addition for addition questions everytime he does or goes back to do it again after he is done i want the questions not to be the same each time i want them to be in a different order. So its random each time.
#addition questions
def beginnerquestionsaddition():
os.system('clear')
score = 0
beginner1 = input("2 + 3 = ")
if beginner1 == ("5"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner2 = input("6 + 7 = ")
if beginner2 == ("13"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner3 = input("2 + 5 = ")
if beginner3 == ("7"):
print("Correct, Well Done!")
score += 1
os.system('clear')
time.sleep(1)
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
So this isn't exactly an answer for the specific way you decided to go about this program but this is a much simpler way:
from random import randrange
def beginner_addition():
A = randrange(1,11) # Increase range on harder questions
B = randrange(1,11) # Ex. for intermediate_addition(), randrange would be (10,21) maybe...
C = A + B
ans = input("What's the answer to " + str(A) + "+" + str(B) + "? ")
if ans == str(C):
print('Correct')
else:
print('Incorrect')
while True:
beginner_addition()
Of course, this is just example code. You could easily include your points system and perhaps move up in difficulty when the points hit a certain level. You could also randomize the operation. Sorry if this isn't what you want but I saw your code and I figured there is nothing wrong with simplifying your code...
I'm very new to programming and I've encountered a problem with a basic guessing game I've been writing.
x is a random number generated by the computer. The program is supposed to compare the absolute value of (previous_guess - x) and the new guess minus x and tell the user if their new guess is closer or further away.
But the variable previous_guess isn't updating with the new value.
Any help would be appreciated.
Here is the code so far:
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
while True:
previous_guess = 0 # Should update with old guess to be compared with new guess
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Your previous guess is being reinitialized every time you loop. This is a very common error in programming so it's not just you!
Change it to:
previous_guess = 0
while True:
#Rest of code follows
Things you should be thinking about when stuff like this shows up.
Where is your variable declared?
Where is your variable initialized?
Where is your variable being used?
If you are unfamiliar with those terms it's okay! Look em up! As a programmer you HAVE to get good at googling or searching documentation (or asking things on stack overflow, which it would appear you have figured out).
Something else that is critical to coding things that work is learning how to debug.
Google "python debug tutorial", find one that makes sense (make sure that you can actually follow the tutorial) and off you go.
You're resetting previous_guess to 0 every time the loop begins again, hence throwing away the actual previous guess. Instead, you want:
previous_guess = 0
while True:
guess = ....
You need to initialize previous guess before while loop. Otherwise it will be initialized again and again.
You have updated previous guess in multiple places. You can make it simpler:
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = 0 # Should update with old guess to be compared with new guess
while True:
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
print("Getting warmer...")
else:
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
previous_guess = guess #####
You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this:
Add before while { previous_guess = x }
Add After While { previous_guess += x }
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = x
while True:
# Should update with old guess to be compared with new guess
previous_guess += x
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Picture When u win
Picture When u loose
I am relatively new to programming with python (actually programming in general). I am making this 'Guess My Age' program that only has one problem:
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
num = 80
min_num = 6
tries = 1
number = random.randint(min_num, num)
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower()
while guess != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif guess == "higher":
print("Let me think...")
min_num = number + 1 #### Here is my trouble - Don't know how to limit max number
time.sleep(3) # pause
elif guess == "lower":
print("Let me think...")
num = number - 1
time.sleep(3) # pause
number = random.randint(min_num, num) #<- Picks new random number
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower() #<- Lowercases
tries += 1 #<- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
As you can see, I have 'num' as the max number for the random integer getting picked, but with:
elif guess == "higher":
print("Let me think...")
min_num = number + 1
it can go back up to however high it wants.
I want it to remember the last integer that 'num' was.
Say the program guessed 50 and I said 'Lower'. Then it said 30 and I said 'Higher'
I know I am probably sounding confusing, but please bear with me.
You need to define a maximum number as well as a minimum number. If they say their age is lower than a given age, you should set that age minus 1 as the maximum.
Of course, you also need to set an initial maximal age.
You might find it more useful to look into recursive functions for this kind of problem. If you define a function which takes min_age, max_age and tries_left as parameters, which comes up with a random number with between min_age and max_age and queries the user, you can then rerun the function (within itself) with a modified min_age, max_age and tries_left - 1. If tries_left is zero, concede defeat. This way you might get a better understanding of the logical flow.
I have left code out of this answer because, as you are a beginner, you will find it a useful exercise to implement yourself.
Cant you split out your guess into something like
max_num = 0
min_num = 0
elif guess =="lower":
max_num = number
if min_num!=0:
number = min_num+(max_num-min_num)/2
else:
number = max_num-1
elif guess =="higher":
min_num = number
if max_num!=0:
number=min_num+(max_num-min_num)/2
else:
number=min_num+1
Sorry it's not meant to be fully rigorous, and its a slight change on the logic you have there, but splitting out your variables so you have a higher and lower cap, that should help a lot?
Cheers
Please let me know if you need more elaboration, and I can try to write out a fully comprehensive version
It seems as though I was wrong in the fact that it did not remember the older integers. Before when running the program it would guess a number higher than the 'num' had specified. I don't know what I changed between then and now? But thank you for the help! #.#
This seems to work.
The only changes I really made:
-Variable names were confusing me, so I changed a couple.
-Note that if you try to mess with it (lower than 5, higher than 3... "Is it 4?" if you say it's higher or lower, you'll get an error).
The first time you set min and max numbers, you do it outside of the loop, so this script does "remember" the last guess and applies it to the new min, max inside of the loop. Each time it runs, the min will get higher or the max will get lower, based on the feedback from when the user checks the guess. If you had stuck the "min_num=6" and the "num=80" inside of the loop, the guesses would never get better.
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
max_num = 10
min_num = 1
tries = 1
guess = random.randint(min_num, max_num)
print("\nLet me guess... You are", guess, "years old?")
check = raw_input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower()
while check != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif check == "higher":
print("Let me think...")
min_num = guess + 1
time.sleep(3) # pause
elif check == "lower":
print("Let me think...")
max_num = guess - 1
time.sleep(3) # pause
guess = random.randint(min_num, max_num) # <- Picks new random number
print("\nLet me guess... You are", guess, "years old?")
check = input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower() # <- Lowercases
tries += 1 # <- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)