Problem with guessing game, player has infinite guesses - python-3.x

I'm trying to build a guessing game in Python. You have a limited number of around 5 guesses/lives and if you run out of them, you will lose the game. (for reference: it uses both random(for random number) and termcolor(for color) modules)
Program:
from termcolor import colored
import random
def lostit():
print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
while decideto not in ("yes", "no"):
decideto = input(colored("Invalid response:", "red"))
if decideto is "yes":
guessnum()
elif decideto is "no":
print("Bye, bye.")
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 0 # Chances
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
print(colored("Great job! You guessed it!", "green"))
So far, it works when you type in the right number. However, I've experienced problems with the lives/guesses part. I've tried to set a limit to how many tries the player has, however the program seems to ignore this, meaning the player basically has infinite lives. How do I solve this?

print(colored("Sorry! You lost!", "red"))
decideto = input("Try again? (yes/no):")
should likely be indented.
This is also strange. You don't have a variable called lostit, but you have a loop with that variable:
while lostit not in ("yes", "no"):
The logic on your code is simply wrong. See this loop:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
You are looping while the guess isn't equal to number you selected.
I would reorg. Main function defines the number to guess, how many guesses they get, it loops while two things are true (guess isn't equal to number and guess count is less than total number of guesses). Also note the scope of variables.
from termcolor import colored
import random
def guessnum():
numtoguess = random.randint(1, 10)
print(colored("I've picked a random number from 0 to 9! Guess what it is! You've got 3 hints and 5 guesses!", "green"))
usernum = input(colored("Try to guess it: ", "cyan"))
guesses = 5 # The limit
usertries = 1 # Chances, but they already used a guess
while (usernum != numtoguess) and (guesses >= usertries):
again = input("Try again? (yes/no):")
while again not in ("yes", "no"):
again = input(colored("Invalid response choose yes/no:", "red"))
if decideto is "yes":
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1
elif decideto is "no":
print("Bye, bye.")
return
if usernum == numtoguess:
print(colored("Great job! You guessed it!", "green"))
if guesses >= usertries:
print(colored("Sorry! You lost!", "red"))

Take a look at this section:
if guesses >= usertries:
while usernum != numtoguess:
usernum = input(colored("Wrong! Guess again: ", "red"))
usertries += 1 # Tried to make it add until the limit, but doesn't work
elif guesses == usertries:
lostit()
First of all, your if and elif are not mutually exclusive: let's say guesses is equal to usertries. It will enter to first if (since you use >=) and not the second elif (because it entered the first one). In other words, Elif code is not reachable.
Seoncd, your while loop is inside the if. It keeps running until you guess the right number, and only then compare your guess with "lives". You should substitute the statements to check the lives inside the loop:
while guesses >= usertries:
usernum = input(colored("Wrong! Guess again: ", "red"))
if usernum != numtoguess:
usertries += 1
# User is wrong. We add one to our counter
else
# user is right. Do something to break the loop
# When we reach here, we ended loop: means user lost
lostit()
The logic is: as long as user has guesses, ask him for another number. compare the number: if he is right, do something. else, keep loop.

Related

How to separate if statements and exit code to execute the program properly?

I was doing beginner python projects as I am a beginner still. I came upon this guessing game project and Wanted to do a Yes or No type of question on whether the user wants to take part in guessing or not.
If user enters Yes, they take part, if anything else ("No" or anything the program exits the code)
However I seem to be doing something wrong, when I enter Yes, the program exits the code anyway. What am I doing wrong? Thank you all,
Here is the code. I am only posting a part of it, where I most probably get the error.
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
if response != "Yes" and response != "yes":
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
if response != "Yes" or "yes":
equates to this:
if response != "Yes" # which resolves to False when response is a 'no'
OR
"yes" # which is a non-empty string, which Python equates to True.
So basically, you code is equivalent to:
if False OR True:
and thus it always runs the exit() function.
In addition to the items noted above, the if statement should be checking both conditions and thus it should be using and instead of using or, as shown below (HT to #tomerikoo):
What you need is TWO separate tests in the if statement:
if response != "Yes" and response != "yes":
If you believe that you might have other versions of yes answers OR if you think that doing a comparison against a general sequence of terms might be easier to understand, you can also do this test instead:
if response in ['Yes', 'yes', 'y', 'Y', 'YES']:
Debugging:
For folks who are new to programming, in Python, it is sometimes fast and easy to use a simple print() function to rapidly evaluate the current state of a variable, to ensure that it really points at the value you believe it does. I added a print statement below with a comment. It would be beneficial to see what value is associated with response. (Caveat: there are professional tools built into Python and into code editors to help with watching variables and debugging, but this is fast and easy).
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
print(response) # checking to see what was actually returned by the
# input() method
if response != "Yes" and response != "yes":
print(response) # check to see what the value of response is at
# the time of the if statement (i.e. confirm that
# it has not changed unexpectedly).
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
In python "non-empty random str" is True and empty string "" is False for conditional usages. So,
if "yes":
print("foo")
prints 'foo'
if "":
print("foo")
else:
print("bar")
prints 'bar'
In your case you want program to exit if response is not "Yes" or not "yes". You have two conditions evaluated in if statement:
response == "Yes" --> False
"yes" --> True
if 1 or 2 --> True --> so exit.
so it should be like that:
if response not in ["Yes", "yes"]:
exit()
else:
do_something()

Set IF statment to check for specific characters, breaks while loop when using any character instead

I am new to python. I was making a guess the random number game, and I run into issues when having both int and str as inputs, I want the user to exit the program when pressing Q or q, while the game to check for numbers as well. After hours of googling and rewriting this is what I came up with:
#! Python3
import random
upper = 10
number = random.randint(1, upper)
print(number) #TODO: THIS LINE FOR TESTING ONLY
print("Guess a number between 1 and {}. Press Q to quit!".format(upper))
total_guesses = 0
guess = 0
while guess != number:
total_guesses += 1
guess = input()
if guess.isalpha():
if guess == "q" or "Q":
break
elif guess != "q" or "Q":
print("Please type in a valid guess.")
guess = 0
if guess.isnumeric():
guess = int(guess)
if guess == number:
print("Good job! You guessed the number in {} tries!.".format(total_guesses))
break
if guess < number:
print("Guess Higher!")
if guess > number:
print("Guess lower!")
else:
print("Valid inputs only")
guess = 0
This code ALMOST works as intended; issues I have now is that at line 13 and 14 the loop breaks every time when any letter is typed, even though I set the if statement to only check for Q or q, and I can't understand why this is doing it. Any help is appreciated!
if guess == 'q' or "Q":
The way this line is read by python is -
if guess == "q":
and also -
if "Q":
"Q" is a character, which means it's truthy. if "Q" returns True. Try:
if guess == "q" or guess == "Q":
if you feels that's too much, other options include -
if guess in ["Q", "q"]:
if guess.upper() == "Q":

Error message of 'ValueError: int() base must be >= 2 and <= 36, or 0' why?

I am making a little text based game where you have to guess the number that is between certain criteria which can either be preset by the user or by a random number generator but the problem is when I try to randomly generate the two parameters for the game I get an error 'ValueError: int() base must be >= 2 and <= 36, or 0'
I dont actually know what I should try as I have never encountered this problem before.
import random
Guess = 0
Run = ("Yes")
while Run == ("Yes"):
Number_1 = random.randint(1, 30)
Number_2 = random.randint(int(Number_1, 999999999999))
Answer = random.randint(int(Number_1), int(Number_2))
while int(Guess) != int(Answer):
Guess = (input("\nWhat is your guess? > "))
if int(Guess) < int(Answer):
print("The answer is Greater then that.")
if int(Guess) > int(Answer):
print("The answer is less then that.")
print("Congrates on guessing correctly!!")
Again = (input("\nDo you want to play again? ('y' or 'n') > "))
if Again == ("y"):
Run = ("Yes")
if Again == ("n"):
Run = ("No")
I expect it to generate 2 numbers a lowest possible number and a highest possible and then have the user try to guess that number but it cant seem to properly generate the number.
You've misplaced a closing paren in the statement Number_2 = random.randint(int(Number_1, 999999999999)), so instead of asking for a random int between Number_1 and 999999999999, you're telling the system to parse Number_1 as expressed in base-999999999999.

why is the print statement on "total bones" not running?

Im trying to get the print statement to run without it having to run each time the "bones" iteration runs. it should be after the two guesses have been made.
[ ]Complete Foot Bones Quiz
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
def foot_bones_quiz(guess, answer):
total_bones = 0
for bones in answer:
total_bones += bones.count(bones)
if guess.lower() == bones.lower():
return True
else:
pass
return False
**print("Total number of identified bones: ", total_bones)**
guess = 0
while guess < 2:
guess = guess + 1
user_guess = input("Enter a bone: ")
print("Is ", user_guess.lower(), " a foot bone?", foot_bones_quiz(user_guess, foot_bones))
print("Bye, Thanks for your answers.")
foot_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform",
"intermediate cuneiform", "medial cuneiform"]
# Declare total as global variable rather than in the loop, as we are calling this loop twice, and this will not store the count from previous loop iteration
total_bones = 0
def foot_bones_quiz(guess, answer):
global total_bones
for bones in answer:
# First bones is a string, so bones.count(bones) is just giving 1 all the time, so you have to increase the count, only when a bone is actually identified
if guess.lower() == bones.lower():
total_bones += bones.count(bones)
return True
else:
pass
return False
guess = 0
while guess < 2:
guess = guess + 1
user_guess = input("Enter a bone: ")
print("Is ", user_guess.lower(), " a foot bone?", foot_bones_quiz(user_guess, foot_bones))
print("Bye, Thanks for your answers.")
# Now we actually print, how many guesses were correct out of the 2 made
print("Total number of identified bones: ", total_bones)
Tested it on Ubuntu, python 3.6, attaching the screen shots as well.

Option to save output printed on screen as a text file (Python)

Either I'm not using the right search string or this is buried deep within the interwebs. I know we aren't supposed to ask for homework answers, but I don't want the code answer, I want to know where to find it, cause my GoogleFu is busted.
Assignment is to create a program that will roll two 6-sided dice n times, with n being user-defined, between 1 and 9. The program then displays the results, with "Snake Eyes!" if the roll is 1-1, and "Boxcar!" if the roll is 6-6. It also has to handle ValueErrors (like if someone puts "three" instead of "3") and return a message if the user chooses a number that isn't an integer 1-9.
Cool, I got all that. But he also wants it to ask the user if they want to save the output to a text file. Um. Yeah, double-checked the book, and my notes, and he hasn't mentioned that AT ALL. So now I'm stuck. Can someone point me in the right direction, or tell me what specifically to search to find help?
Thanks!
Check out the input function:
https://docs.python.org/3.6/library/functions.html#input
It will allow you to request input from a user and store it in a variable.
You can do something like this to store your final output to a text file.
def print_text(your_result):
with open('results.txt', 'w') as file:
file.write(your_result)
# Take users input
user_input = input("Do you want to save results? Yes or No")
if(user_input == "Yes"):
print_text(your_result)
I hope this helps
Well, it's not pretty, but I came up with this:
def print_text():
with open('results.txt', 'w') as file:
file.write(str(dice))
loop = True
import random
min = 1
max = 6
dice = []
while loop is True:
try:
rolls = int(input("How many times would you like to roll the dice? Enter a whole number between 1 and 9: "))
except ValueError:
print("Invalid option, please try again.")
else:
if 1 <= rolls <= 9:
n = 0
while n < rolls:
n = n + 1
print("Rolling the dice ...")
print("The values are:")
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
dice.append(dice1)
dice.append(dice2)
print(dice1, dice2)
diceTotal = dice1 + dice2
if diceTotal == 2:
print("Snake Eyes!")
elif diceTotal == 12:
print("Boxcar!")
else: print("Invalid option, please try again.")
saveTxt = input("Would you like to save as a text file? Y or N: ")
if saveTxt == "Y" or saveTxt == "y":
print_text()
break

Resources