Bulls and Cows Game - Python programming for beginners - python

I am a beginer programming Python and for a evaluation assignment I was asked to program a Bulls and Cows game using very simple code.
I have some code already written, but can't seem to make the function work. The function should be able to compare the four digit number the user wrote (num_guess) to the random number generated by the program (stored in a list called num).
I can input the value, but have no further feedback from the program.
Could you please check my code and help me?
Thanks!
import random
guess = raw_input("What is your guess? ")
if (len(guess) != 4):
guess = raw_input("Your guess must be 4 characters long! What is your guess?")
num_guess = []
for c in guess:
num_guess.append(int(c))
def compare(num_guess):
num = []
for i in range(4):
n = random.randint(0, 9)
while n in num:
n = random.randint(0, 9)
num.append(n)
if num_guess == num:
print "Congratulations! Your guess is correct"
output = []
if num_guess[0] == num [0]:
output.append["B"]
else:
output.append["C"]
if num_guess[1] == num [1]:
output.append["B"]
else:
output.append["C"]
if num_guess[2] == num [2]:
output.append["B"]
else:
output.append["C"]
if num_guess[3] == num [3]:
output.append["B"]
else:
output.append["C"]
return output
nguesses = 0
while nguesses < 11:
nguesses = nguesses + 1, compare

Without giving you the corrected code you will want to call the function at the end of your code. If you want to see result do:
print compare(num_guess)
This will show you an additional issue with all of these parts
output.append[]
I'm not sure if it is just how you pasted it but you may want to clean up the indentation. Also:
while n in num:
n = random.randint(0, 9)
This above section is not needed. Have fun and figure out how to make it work well.

Related

Mathematic questions in python

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!

while function with the in operator not working

gone = []
turn = 0
def play(XO,player):
while 0 == 0:
num = input("\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
while ((str(num).isdigit() == False) or ((int(num) <= 9 and int(num) >= 1) == False)) or (num in gone):
num = input("\nValue was not an available number.\n"+player+" enter an available number where you want to put an '"+XO+"'.\n > ")
So, in the second while loop I'm having a problem. You see the (num in gone) part? I'm trying to make it so if num is found in the gone list then it will be true, but it isn't working. Instead it passes through it.
I've tested to see if (not num in gone) applies the opposite effect, and it does!
If you need to see my entire code I can post it... btw this is for a Tic-Tac-Toe program I am making.
You're putting too much logic in one condition. Splitting it up will help you a lot.
Try something like this:
gone = []
turn = 0
def play(XO, player):
while True:
num = input(
f"\n{player} enter an available number "
f"where you want to put an '{XO}'.\n > "
)
try:
num = int(num)
except ValueError:
print("Not a valid number, try again")
continue
if num < 1 or num > 9:
print("Number not in correct range, try again")
continue
if num in gone:
print("Number already gone, try again")
continue
gone.append(num)
turn += 1

Python. Variable in while loop not updating.

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

How to run a function several times for different results in Python 3

EDIT: Thanks for each very detailed explanations for the solutions, this community is golden for someone trying to learn coding!! #DYZ, #Rob
I'm a newbie in programming, and I'm trying to make a simple lotto guesses script in Python 3.
The user inputs how many guesses they need, and the program should run the function that many times.
But instead my code prints the same results that many times. Can you help me with this?
I'm pasting my code below, alternatively I guess you can run it directly from here : https://repl.it/#AEE/PersonalLottoEn
from random import randint
def loto(limit):
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess
guess = [] #Need to create an empty list 1st
#User input to select which type of lotto (6/49 or 6/54)
while True:
choice = int(input("""Please enter your choice:
For Lotto A enter "1"
For Lotto B enter "2"
------>"""))
if choice == 1:
lim = 49 #6/49
break
elif choice == 2:
lim = 54 #6/54
break
else:
print("\n1 or 2 please!\n")
times = int(input("\nHow many guesses do you need?"))
print("\nYour lucky numbers are:\n")
for i in range(times):
result = str(sorted(loto(lim)))
print(result.strip("[]"))
Your loto function is operating on a global variable, guess. Global variables maintain their values, even across function calls. The first time loto() is called, guess is []. But the second time it is called, it still has the 6 values from the first call, so your while loop isn't executed.
A solution is to make the guess variable local to the loto() function.
Try this:
def loto(limit):
guess = [] #Need to create an empty list 1st
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess

How to get python to go back to start of loop and not use random?

I'm a bit new to python and was giving myself a task, I wanted a number guessing game that gets you to guess four numbers and the program will keep telling you how many numbers you guess right till you guess the full list of numbers.
running = True
import random
def compareLists(a, b):
return list(set(a) & set(b))
def start():
rNums = random.sample(range(10), 4)
gNums = []
print("Get ready to guess 4 numbers!")
for i in range(0, 4):
x = int(input("Guess: "))
gNums.append(x)
print("You guessed: ", gNums)
comparison = len(compareLists(rNums, gNums))
while gNums and rNums:
if gNums != rNums:
print("You guessed " + str(comparison) + " numbers right, keep guessing!")
break
elif gNums == rNums:
print("What amazing luck!")
while running:
start()
The problem is that when I use a break a new list of 4 numbers is created, I want python to just go back to the start of the loop and not make a whole new list!
You want to use continue. Try it with a toy example:
i = 0;
while i < 10:
i += 1
if i % 2 == 0:
continue
print i
Output:
1
3
5
7
9
You can put the
rNums = random.sample(range(10), 4)
outside the loop and pass rNums to start. This way you will have the same four numbers in the list. Hope this helps
For the sake of minimizing the amount of loops going on in your code, I would probably first pop your random numbers in a dictionary.
Something like this (probably more efficient way of doing this...but it's the first thing that popped in my head):
from collections import Counter
d = Counter(random.sample(range(10), 4))
Start your while loop, and keep asking the user to guess. Every time they make a right guess, just perform this operation:
d.pop(correctly_guessed_num)
Once your dictionary is empty, you are done and you break the loop.
EDIT adding my quick stab at the implementation. Not fully thought through, might be some edge cases that break this...but this is the overall idea. Hope it helps.
from collections import Counter
import random
d = Counter(random.sample(range(1, 10), 4))
size = len(d) - 1
while True:
x = int(input("Guess: "))
if size == 0:
print("you guessed them all, way to go")
break
if x not in d:
print("keep going buddy")
continue
else:
d.pop(x)
size -= 1
print("A right guess")

Categories

Resources