Python if and else statement not expected output - python

I am trying to make an animal quiz using python 3.9. On one of the questions getting it wrong 3 times doesn't start a new question like it should. Instead it is just blank. On the person's first and second attempt everything works smoothly. Any and all help is appreciated. Here is my code:
def check_guess(guess, answer):
global score
global name
still_guessing = True
attempt = 0
while still_guessing and attempt < 3:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False
elif attempt <= 1:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
if attempt == 3:
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear')

You have to put the if attempt == 3 in your while loop, because the loop while run infinitely until the guess is right, so when attempt's value is 3, it will do nothing because it is still in a loop and there is no if statement telling it what to do once the value is 3.
EDIT: Also change the loop conds to still guessing and attempt <= 3
attempt = 0
def check_guess(guess, answer):
global score
global name
global attempt
still_guessing = True
while still_guessing and attempt <= 3:
print(f"attempt {attempt}")
if attempt == 2:
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
else:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False

I think the elif bellow should evaluate <= 2, not 1:
elif attempt <= 2:
But than the last 'Try again' message is still printed. You can solve that putting an attempt check condition right before the 'Try again' message. In case the condition evaluate to True, you break the loop:
elif attempt <= 2:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
attempt = attempt + 1
if attempt > 2:
break
guess = input('Try again ')
Remember to adjust you While condition in this case, as the attempt check is not necessary anymore.
If I may, I did some refactoring in the code, so you can check out other ways to achieve the same goal.
def check_guess(guess, answer, attempts):
global score
global name
while True:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
score = [0, 1, 2, 3]
final_score = score[attempts]
print(f'Score: {final_score}')
break
attempts -= 1
if attempts == 0:
print('the correct answer was %s' % answer)
print('There is always next time!!')
break
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear', attempts=3)

I notice some mistakes.
First, you don't need if attempt == 3 or 2 because you are using a while loop (while loop is based on the condition at first).
Second, it is better to integrate "break" to not have an infinite loop.
While loop starts from 0 and ends at 2 (takes 3 values).
I rewrote the code, for you.
def check_guess(guess, answer):
global score
global name
still_guessing = True
attempt = 0
while still_guessing and attempt < 2:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False
elif attempt <= 1:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
break
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
To test the code add print("pass OK")
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear')
print("pass OK")
Don't forget to upvote :) (Ramadan Karim!!!)

in your while loop
'attempt' never become 3, so the code can't jump to the next part if attmpt == 3
so in the while loop, the elif condition should be elif attempt <= 2: then attempt = attempt + 1 can reach 3

Use below code it works for me .
def check_guess(guess, answer):
global score
global name
still_guessing = True
attempt = 0
while still_guessing and attempt < 3:
if guess == answer:
print('Correct wow, i expected worse from someone named %s' % name)
if attempt == 0:
score = score + 3
elif attempt == 1:
score = score + 2
elif attempt == 2:
score = score + 1
still_guessing = False
elif attempt <= 2:
print('HAAAAAAAAAAAAAAAAAAAAAAAAAAAA IMAGINE NOT GETTING THAT RIGHT!!!')
print('L bozo + ratio')
guess = input('Try again ')
attempt = attempt + 1
if attempt == 3:
print('the correct answer was %s' % answer)
print('There is always next time!!')
still_guessing = False
score = 0
print('Welcome to the animal quiz')
print()
print('In this game you will have to guess the animal')
name = input('What is your name? ')
print('Cool name, I feel like i heard of it before hmmm %s..' % name)
print()
print('Enough stalling onto the game!!!')
guess1 = input('Which bear lives in the north pole ')
check_guess(guess1.strip().lower(), 'polar bear')
I have change 1 into 2.

Related

How do I limit input attempts in python?

I am trying to limit the attempts in a quiz I am making, but accidentally created an infinte loop. What am I doing wrong here?
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(guess, answer):
global score
still_guessing = True
attempt = 3
while guess == answer:
print('That is the correct answer.')
score += 1
still_guessing = False
else:
if attempt < 2:
print('That is not the correct answer. Please try again.')
attempt += 1
if attempt == 3:
print('The correct answer is ' + str(answer) + '.')
guess_1 = input('Where was Hitler born?\n')
check_questions(guess_1, 'Austria')
guess_2 = int(input('How many sides does a triangle have?\n'))
check_questions(guess_2, 3)
guess_3 = input('What is h2O?\n')
check_questions(guess_3, 'water')
guess_4 = input('What was Germany called before WW2?\n')
check_questions(guess_4, 'Weimar Republic')
guess_5 = int(input('What is the minimum age required to be the U.S president?\n'))
check_questions(guess_5, 35)
print('Thank you for taking the quiz. Your score is ' + str(score) + '.')
Here is how you should handle it. Pass both the question and the answer into the function, so it can handle the looping. Have it return the score for this question.
score = 0
print('Hello, and welcome to The Game Show')
def check_questions(question, answer):
global score
for attempt in range(3):
guess = input(question)
if guess == answer:
print('That is the correct answer.')
return 1
print('That is not the correct answer.')
if attempt < 2:
print('Please try again.')
print('The correct answer is ' + str(answer) + '.')
return 0
score += check_questions('Where was Hitler born?\n', 'Austria')
score += check_questions('How many sides does a triangle have?\n', '3')
score += check_questions('What is H2O?\n', 'water')
score += check_questions('What was Germany called before WW2?\n', 'Weimar Republic')
score += check_questions('What is the minimum age required to be the U.S president?\n', '35')
print(f"Thank you for taking the quiz. Your score is {score}.")

how can i give a boolean a value inside a function with a while loop

i'm trying to make a guessing game, and i want to give the user 5 chances, but the loop keeps going after the chances given if the answer is incorrect.
if the answer is correct the program will print the losing text
i think the problem is with the value of full but the solutions i've tried broke the code
def proceso(ingreso, correcto, usos, usos_completos, usos_visibles, full):
if usos < usos_completos:
while ingreso != correcto and not full:
print("you have " + str(usos_visibles) + " chances")
ingreso = input("guess the word: ")
usos += 1
int(usos_visibles)
usos_visibles -= 1
else:
full = True
if full:
print("you lost. Correct answer was: " + correcto)
else:
print("you won")
palabra_secreta1 = "cellphone"
palabra_ingresada = ""
oportunidades = 0
limite_oportunidades = 5
contador_visible = 5
sin_oportunidades = False
print("5 oportunities")
proceso(palabra_ingresada, palabra_secreta1, oportunidades, limite_oportunidades, contador_visible, sin_oportunidades)
You should use break if the correct word is inputted and then count the number of chances taken in the while loop and then use else to print if the correct input has not been given after the desired number of attempts. I've removed some arguments because they seemed to be the same and I'm not sure what they mean, but maybe they're useful? Also, you should use f-strings for formatting variables into strings:
def proceso(correcto, usos_completos):
usos = 0
while usos != usos_completos:
print(f"you have {usos_completos-usos} chances")
ingreso = input("guess the word: ")
if ingreso == correcto:
print("you won")
break
else:
usos += 1
else:
print(f"you lost. Correct answer was: {correcto}")
palabra_secreta1 = "cellphone"
limite_oportunidades = 5
print("5 oportunities")
proceso(palabra_secreta1, limite_oportunidades)

Access a function variable from outside the function in python

I have a python function and would like to retrieve a value from outside the function. How can achieve that without to use global variable. I had an idea, if functions in python are objects then this could be a right solution?
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
while check_difficulty.tries > 0:
I am new to python so excuse me...
def check_difficulty(difficulty):
if (difficulty == 1):
return 10
elif (difficulty == 2):
return 5
elif (difficulty == 3):
return 3
tries = 0
while tries > 0:
difficulty = int(input("Choose your difficulty: "))
tries = check_difficulty(difficulty)
tries = tries - 1
if you use a while loop and put everything inside in a structured way, a function will not be needed.
You can change this to a class to get your tries:
class MyClass:
def __init__(self):
self.tries = 0
def check_difficulty(self, difficulty):
if (difficulty == 1):
self.tries = 10
elif (difficulty == 2):
self.tries = 5
elif (difficulty == 3):
self.tries = 3
ch = MyClass()
try:
difficulty = int(input("Choose your difficulty: "))
ch.check_difficulty(difficulty)
except ValueError:
difficulty = int(input("Type a valid number: "))
ch.check_difficulty(difficulty)
ch.tries
# 5
If you want the question answered within the construct of your current code simply put your try, except before the function. You can call a function anywhere in the code it doesn't ave to be after the function is created . So something like this:
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
while check_difficulty.tries > 0:
however, I would have to agree with the other answers and just kind of put everything together within the same loop and you won't have to worry about this. I created a guessing game recently that actually had something similar to this. Here is the difficulty portion of that code:
def guessing_game():
again = ''
# Define guesses/lives
while True:
try:
guesses_left = int(input('How many guess would you like(up to 4)?: '))
if 1 > guesses_left or guesses_left > 4:
print('You must choose between 1 and 4 for your guess amount. Try again.')
continue
break
except:
print('You must enter a valid number between 1 and 4. Try again.')
# Define difficulty based on guesses_left
difficulty = ''
if guesses_left == 1:
difficulty = 'Hard Mode'
elif guesses_left == 2:
difficulty = 'Medium Mode'
elif guesses_left == 3:
difficulty = 'Easy Mode'
elif guesses_left == 4:
difficulty = 'Super Easy Mode'
print('You are playing on ' + difficulty + ' with ' + str(guesses_left) + ' guesses.')
#code continues under this line to finish#

Implementing Cows and Bulls game

I have to code the Cows and Bulls game in which I have to generate 4 random number and ask the users to guess it. I have been trying for the past few hours to code it but can't seem to come up with a solution.
The output I want is:
Welcome to cows and Bulls game.
Enter a number:
>> 1234
2 Cows, 0 Bulls.
>> 1286
1 Cows, 1 Bulls.
>> 1038
Congrats, you got it in 3 tries.
So far, I have got this:
print("Welcome to Cows and Bulls game.")
import random
def number(x, y):
cowsNbulls = [0, 0]
for i in range(len(x)):
if x[1] == y[i]:
cowsNbulls[1] += 1
else:
cowsNbulls[0] += 1
return cowsNbulls;
x = str(random.randint(0, 9999))
guess = 0
while True:
y = input("Enter a number: ")
count = number(x, y)
guess += 1
print(str(count[0]), "Cows.", str(count[1]), "Bulls")
if count[1] == 4:
False
print("Congrats, you done it in", str(guess))
else:
break;
And the output is:
Welcome to Cows and Bull game.
Enter a number: 1234
4 Cows, 0 Bulls.
It would not continue. I was just wondering what the problem is.
Try this:
print(str(count[0]), "Cows.", str(count[1]), "Bulls")
if count[0] == 4:
print("Congrats, you done it in", str(guess))
break
You want to break the while loop if the count equals 4, otherwise it should continue to run.
There are some things wrong with your code:
The while True statement has the same indent level as a function
Inside the while statement you use break which is why the statement only executes once if you fail to get the correct anwser the first time
"x & y" variables?? Please in the future use vars that make sense, not only to you, but to others
In the function "number" you have a this validation x[1] == y[i] this wont do anything, it will only compare the first char of the string
Below I made some repairs to your code, see if it's something like this that you are looking for:
import random
def number(rand_num, guess):
cowsNbulls = {
'cow': 0,
'bull': 0,
}
for i in range(len(rand_num)):
try:
if rand_num[i] == guess[i]:
cowsNbulls['cow'] += 1
else:
cowsNbulls['bull'] += 1
except:
pass
return cowsNbulls;
def game_start():
rand_number = str(random.randint(1, 9999))
tries = 0
locked = True
print("Welcome to Cows and Bulls game.")
while locked:
print(rand_number)
guess = input("Enter a number (Limit = 9999): ")
cows_n_bulls = number(rand_number, guess)
tries += 1
print(str(cows_n_bulls['cow']), "Cows.", str(cows_n_bulls['bull']), "Bulls")
if cows_n_bulls['cow'] == 4:
print("Congrats, you done it in", str(tries))
locked = False
game_start()

Python Warm / Cold Declaring Variable outside while loop

I'm writing a simple warmer / colder number guessing game in Python.
I have it working but I have some duplicated code that causes a few problems and I am not sure how to fix it.
from __future__ import print_function
import random
secretAnswer = random.randint(1, 10)
gameOver = False
attempts = 0
currentGuess = int(input("Please enter a guess between 1 and 10: "))
originalGuess = currentGuess
while gameOver == False and attempts <= 6:
currentGuess = int(input("Please enter a guess between 1 and 10: "))
attempts += 1
originalDistance = abs(originalGuess - secretAnswer)
currentDistance = abs(currentGuess - secretAnswer)
if currentDistance < originalDistance and currentGuess != secretAnswer:
print("Getting warmer")
elif currentDistance > originalDistance:
print("Getting colder")
if currentDistance == originalDistance:
print("You were wrong, try again")
if currentGuess == secretAnswer or originalGuess == secretAnswer:
print("Congratulations! You are a winner!")
gameOver = True
if attempts >= 6 and currentGuess != secretAnswer:
print("You lose, you have ran out of attempts.")
gameOver = True
print("Secret Answer: ", secretAnswer)
print("Original Dist: ", originalDistance)
print("Current Dist: ", currentDistance)
It asks for input before I enter the loop, which is to allow me to set an original guess variable helping me to work out the distance from my secret answer.
However, because this requires input before the loop it voids any validation / logic I have there such as the if statements, then requires input directly after this guess, now inside the loop.
Is there a way for me to declare originalGuess inside the loop without it updating to the user input guess each iteration or vice versa without duplicating currentGuess?
Thanks
There doesn't seem to be a need to ask the user before you enter the loop... You can just check if guesses = 1 for the first guess...
gameOver=False
guesses = 0
while not gameOver:
guesses += 1
getUserInput
if guesses = 1 and userInput != correctAnswer:
print "try again!"
checkUserInput
print "good job!, it took you {} guesses!".format(guesses)

Categories