Need Solution for incorrect guess loop - python

Ok, I am creating a memory game. I have developed where the programme asks the user what word was removed, and have successfully developed the part that moves on if they get it right. However, I am struggling to find how to get it to only fail the user if they get it wrong three times. Here's what I have so far:
def q1():
qone + 1
print("\n"*2)
while qone <= 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
else:
print("Incorrect")
q1()
else:
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
`

My approach is to remove recursion and simply increase the counter of failed tries.
def q1():
qone = 0
print("\n"*2)
while qone < 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
return
else:
print("Incorrect")
qone += 1
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return

When you do qone + 1, you need to assign it to something (so perhaps qone += 1)
What is the else outside the while loop linked to?
You seem to have a recursive definition going. Think carefully about the chain of calls that would be made and what your base case should be. Once you know these things, it would be easier for you to write the code. Also, think about whether you need recursion at all: in this case, it doesn't seem like you would.

You should not have the function calling itself, use range for the loop, if the user gets the question correct go to the next question, if they get it wrong print the output:
def q1(removed):
print("\n"*2)
for i in range(3):
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\nCorrect")
return q2()
print("\n\nIncorrect")
input("You're all out of guesses!\nPress enter to return to the menu")
return menu()
If the user has three bad guesses the loop will end and you will hit the "You're all out of guesses!\nPress enter to return to the menu"

Related

Guess the number, play again

I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.

Nest IF needed? in Python

This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.
"""this is a quiz on computer science"""
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another attempt = attempt + 1 (Or alternatively attempt += 1) after the break
So your elif block would look like:
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
attempt = attempt + 1
This allows the attempt counter to increment even if they fail the second time, tiggering the fail and end of loop.
You just add attempt +=1 after the loops.
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
attempt += 1
break
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()

Problems with Rock, Paper, Scissors Python Code

I'm working on a code with python, where we've been asked to create a game of Rock, Paper, Scissors using an external file of options (rock, paper, scissors) as opposed to having the code use any user input. However, for some reason, my code doesn't work. When someone inputs "yes", it prints "Let us play now," but that's it. Nothing else happens.
Why isn't the game completing when a user provides "yes" as input?
from random import randrange
def sample():
computer_input = randrange(1,3)
return computer_input
def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()
tied = 0 #games tied
user_won = 0 #games won by user
comp_won = 0 #games won by computer
user_input = ""
computer_input = ""
print("Rules of the game...")
print("Would you like to turn up with a game of rock, paper, or scissors? ;) Yes or no? -->")
answer = input()
if (answer == "yes"):
play = True
print("Let us now play.")
## elif(answer == "no" or "No"):
## play = False
## print("Sorry. Maybe we can play next time ;)")
## else:
## play = False
## print("Please try again!")
## main()
while True:
if(computer_input == "1"):
if(user_input == a[0]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[1]):
user_won = user_won + 1
print("You won! Paper covers Rock")
elif(user_input == a[2]):
comp_won = comp_won + 1
print("You lost! Rocks knocks out scissors")
## else:
## print("Try again!")
elif (computer_input == "2"):
if (user_input == a[0]):
comp_won = comp_won + 1
print("You lost! Paper covers Rock")
elif(user_input == a[1]):
tied = tied + 1
print("Game is tied!")
elif(user_input == a[2]):
user_won = user_won + 1
print("You won! Scissors cuts Paper")
## else:
## print("Try again!")
else :
if(user_input == a[0]):
user_won = user_won + 1
print("You won! Rock knocks out scissors")
elif(user_input == a[1]):
comp_won = comp_won + 1
print("You lost! Scissors cuts Paper")
elif(user_input == a[2]):
tied = tied + 1
print("Game is tied!")
## else:
## print("Try again!")
##
##print("Game over")
##print("Statistics")
##print("Games tied -->", tied)
##print("Game won by comp -->", comp_won)
##print("Game won by user -->", user_won)
##
main()
Notice that on line 5 below, you set computer_input to the result of sample():
def main():
a = []
infile = open("input2.txt", "r")
for line in infile:
a.append(line)
computer_input = sample()
But then a few lines later, you set it to "":
user_input = ""
computer_input = ""
Your while loop is checking against the value of computer_input, but it assumes it will be a number. It has no case to handle the empty string. I would recommend removing that line.
Also note that your while loop is checking the value of user_input, but you never seem to actually read input into that variable.
There are many, many problems with this code.
Every time you define or use a variable, you should have a clear idea of
why it is defined this way or exactly what this use of the variable is
going to accomplish.
You have a loop, which seems to indicate that you meant for more than
one round of the game to be played when you run the code once.
But there is only one place where the computer's choice is set
to a number 1, 2, or 3, and it occurs only once.
(Besides, as has already been pointed out, then you change the
computer's choice to "" without even reading the number once.)
You have no apparent way to get out of the loop within the logic of the code.
It is unclear what you think you are supposed to be reading from the
user's input file. You put the contents of the file in the array a line
by line, but then you only ever look at a[0], a[1], and a[2].
What were the first three lines of the file supposed to contain?
Why only three lines? What does it mean to ask whether
user_input == a[0]?
(I have a hunch that you were supposed to set the user input on each
round to a member of a, not compare user_input to a member of a.)
(Also notice that you set user_input = "" earlier, so unless you read
empty strings into the entries of a, expressions like
user_input == a[0] will always be false.)
What is the point of setting play = True? (Or even setting
play = False as in the commented-out code?) You never do anything that
would read the value of play.
What is the point of keeping count in the variables tied,
user_won, and computer_won? You never read those variables either,
except when you're setting new values of them.
It might help if you write some smaller functions with very clear
purpose, input and output. The sample() function is promising, but
everything else is in main().
For example, figuring out who won, given the computer's choice and
the player's choice, could be a function.
By writing such a function you would remove dozens of lines of code from
the loop in main(), replacing them with perhaps one line of code.
It's much, much easier to write well-designed loops when
the block of code inside the loop is short.

How to stop the beginning of my function's loop from repeating

I have created a code in which the user will input their choice which will continue in a loop if the variable 'contin' equals "yes". When the user enters the choice "no" or any other input it will print their overall answers or the error message and end the loop. Instead it then repeats the beginning of the function (in this case it's whether the user wanted to continue or not). Is there a way for me to prevent this from happening?
This is the code:
def userinput():
while True:
contin = input("Do you wish to continue the game? If so enter 'yes'. If not enter 'no'.")
if contin == 'yes':
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"']
guess = input("What symbol do you wish to change? ")
symbol_dictionary[guess] = input("Input what letter you wish to change the symbol to.(Make sure the letter is in capitals.) ")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
else:
print("Please enter a valid input.")
All you need to do is exit the function; add a return in your no branch:
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
# exit the function
return
Just add a break or a return at the end of the elif statement:
print("Well done! You have completed the game!")
break # or return
This will exit the loop. Break makes more sense in this context.

Python While Statements

I'm a bit confused on the logic of doing this.
I want the user to be able to input the number of items they have, and then ask them at the end if they are done. Right now I'm asking after every single item, and I don't like it.
How should I modify this code to get what I want?
Input:
if next1 == "2":
next2=input("How many would you like to add? ")
val = int(next2)
print("")
count = 0
while count < int(next2):
count = count + 1
next3=input(str(count) + ". Input: ")
print("")
check=input("Are you sure? (Y/N) ")
while check not in ("YyYesNnNo"):
check=input("Are you sure? (Y/N) ")
if check in ("YyYes"):
add(next3)
home()
elif check in ("NnNo"):
sort(numbers)
home()
Function:
def add(next2):
numbers.append(next2)
sort(numbers)
home()
Okay, well generally you might do something like this
def confirm_with_user():
user_data = ""
while user_data not in "YyYesNnNo":
user_data = input("Are you sure? (Y/N) ")
return user_data.lower() in "yes":
Then at the point in your code when you want to confirm with your user you just do
if confirm_with_user():
#proceed...
else:
#They don't want to proceed

Categories

Resources