Implementing Cows and Bulls game - python

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

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}.")

Python if and else statement not expected output

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.

Repeated prints from loop

I am trying to create a program similar to the game Mastermind. I am having an issue in my while loop where it constantly prints "You got " + str(correct) + " correct!"
import random
import replit
def useranswer(input):
userinput.append(input)
return input
number = 0
answer = 0
guesses = 0
correct = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
for i in range(0,4):
answer = str(input('Give me a number: '))
useranswer(answer)
print(generation)
while userinput != generation:
guesses += 1
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got " + str(correct) + " correct! ")
correct = 0
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " + str(guesses) + " tries!")
If you want it to exit the while loop after printing the line print("You got " + str(correct) + " correct! ") then you'll need to do something within the while loop to make the check not true.
Right now if userinput != generation is true then it will loop forever because nothing in the loop ever changes that to be false.
You need to get the player's input within the while loop if you want it to keep looping until something happens, otherwise an if statement might be better.
Ive made couple of changes to your code. Take a look at it
Removed def userinput().
Moved userinput inside the while loop.
import random
import replit
number = 0
answer = 0
guesses = 0
x = 0
userinput = []
generation = []
c = []
replit.clear()
for i in range(0,4):
num = random.randrange(1,9)
generation.append(num)
while userinput != generation:
guesses += 1
correct = 0
userinput = []
for i in range(0,4):
answer = int(input('Give me a number: '))
userinput.append(answer)
for i in range(0,4):
if generation[i] == userinput[i]:
correct += 1
print("You got ",correct, " correct! ")
if guesses==1:
print("Good job! You became the MASTERMIND in one turn!")
else:
print("You have become the MASTERMIND in " ,guesses, " tries!")

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

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