I'm making a quiz. The user has 3 tries to guess the answer to the question.
My problem is that the scoring system isn't working properly. If the user guesses the answer the first time it adds 3 points, which works. However, the program adds 0 points if the user guesses the second time when it's supposed to add 1 point.
I've tried asking people around me and swapping the if statements, so that the possibility of the program assuming the score is lost.
songnameguess = input("Guess the name of the song!")
counter = counter + 1
while counter < 3 and songnameguess != randomsong :
songnameguess = input("Nope! Try again!")
counter = counter + 1
if songnameguess == randomsong:
print ("Well done!")
answer = input("Do you want to continue playing?")
print (counter)
if counter == 2:
score == score + 1
print (score)
elif counter == 1:
score = score + 3
print (score)
When the user guesses the answer correctly the first time, they are supposed to have 3 points added to their score, and when the user guesses the answer correctly the second time, they are supposed to have 1 point added to their score. If the user does not guess the score in three tries, the game ends.
This line of code is wrong
score == score + 1
== should not be used but = should be used
Hope it helps
Related
I have produced a simple game using the turtle module. The objective of the game is to return to the original position in a certain number of moves, through left and right inputs. Therefore, I tried to make a scoring (point) system that counts the number of moves the user has done and prints a winning message if the user returns to the original position in the specified number of moves. If the user (player) fails to do so it prints a failure message. However, it doesn't count up each move (point) and when it prints the score it always prints "1" no matter how many moves the player has done. Apologies if the questions seem too simple but help is much appreciated.
Here is the code:
import turtle
print("Try to return to original position in exactly 12 moves")
my_turtle = turtle.Turtle()
fx = my_turtle.pos()
score = 0
tries = 12
def turtles():
while True:
score = 0
directions = input("Enter which way the turtle goes: ")
if directions == "Right" or directions == "R":
my_turtle.right(90)
my_turtle.forward(100)
score += 1
print(score)
if fx == my_turtle.pos() and tries == score:
print("Well done")
elif fx == my_turtle.pos and tries > score or score > tries:
print("Return to original position in exactly 12 moves")
directions1 = input("Enter which way the turtle goes: ")
if directions1 == "Left" or directions1 == "L":
my_turtle.left(90)
my_turtle.forward(100)
score += 1
print(score)
if fx == my_turtle.pos() and tries == score:
print("Well done")
elif fx == my_turtle.pos and tries > score or score > tries:
print("Return to original position in exactly 12 moves")
turtles()
turtle.done()
The problem is the score = 0 call at the top of the loop. This resets the score at every loop iteration, so there's no way score could ever be anything other than 0 or 1.
This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.
This is my code, The computer is supposed to guess a number between 1 and 100. The computer's guesses should either decrease or increase by half of the previous guess. The third time through the loop going only higher it breaks, or if I use higher after saying lower it breaks. Both ways, it will stop adding its guesses and divide the previous guess by two, instead of adding the previous guess divided by two to the previous guess. i.e instead of 50 + (50/2) = 75 my code does 50/2 = 25. So where it breaks on higher is at 87, instead of adding half of the previous guess, which would be six, it divides 87 by 2 equaling 43. (I have now edited this question, and the code and everything should work besides where I need help. Thank you)
pcguess = 50
useranswer = 50
print("Wanna see a magic trick?")
print("Please think of a random number between 1 and 100.")
print("Now that you have written down your number")
print("I will guess it in ten guesses or less.")
a = print("My first guess is", pcguess)
tries = 0
while tries < 100000:
newguess = pcguess//2
b = input("Was that your number?")
if b == "no":
tries += 1
c = input("Is your number higher or lower than my guess?")
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess
pcguess = newguess
tries += 1
elif c == "higher":
print("Then my next guess is:")
print(useranswer + newguess)
useranswer = pcguess + newguess
pcguess = newguess
tries += 1
if b == "yes":
print("I got it in", tries, "tries!")
break
You need to narrow down the possible range of numbers based on the user's "higher"/"lower" responses. So you should store the lower and upper bounds as variables, and adjust them as you get responses. Something like this:
lower = 0
upper = 100
while lower < upper:
guess = (lower+upper)//2
print("My guess is ", guess)
# Find out if the correct answer is higher or lower than this guess
if the correct answer is higher:
lower = guess + 1 # This gives a new lower bound
if the correct answer is lower:
upper = guess - 1 # This gives a new upper bound
The first thing I would change in your code is your where you increment your tries variable. In your current while loop, you are incrementing once every time you execute your while loop and then again after whichever if statement gets executed. This means that every iteration, your number of tries goes up by 2 instead of 1. So why don't you just increment tries once at the beginning of your loop instead?
Second, the reason your useranswer variable doesn't become what you expect is simply because you are updating it wrong. For example
if c == "lower":
print("Then my next guess is:")
print(useranswer - newguess )
useranswer = pcguess - newguess # WRONG
pcguess = newguess
since you are updating useranswer, it should be useranswer = useranswer + newguess or more succinctly useranswer += newguess
Do this for the other if statement as well (where your guess is higher than what the computer is guessing)
Thirdly. This is more a matter of styling but your while loop condition should be more accurate (i.e. since you are telling the user that you will guess their number in 10 tries or less, does your loop condition really need to have tries < 100000?
Sample program in which while loop is illustrated:
answer="0"
while answer!="4":
answer=input("What is 2 + 2?")
if answer!="4":
print("Wrong...Try again.")
else:
print("Yes! 2 + 2 = 4")
Here the loop will execute till the user gives the correct answer, i.e. 4.
I want to add another feature in the above code which prints how many attempts the user took to give the correct answer.
print("You gave correct answer in attempt",answer)
But I am not getting any idea how to do it.
Create a variable which stores the amount of attempts the user has taken:
attempts = 0
while True:
answer = int(raw_input("What is 2 + 2?"))
attempts += 1
if answer == 4:
print("Yes! 2 + 2 = 4")
break
print "Wrong.. try again"
print "It took {0} amount of attempts".format(attempts)
Convert the while-loop into a for-loop:
from itertools import count
for attempts in count(1):
answer = input("What is 2 + 2?")
if answer == "4":
break
print("Wrong...Try again.")
print("Correct in {} attempts!".format(attempts))
Currently working through some tutorials on Python, so if it doesn't work, do excuse my n00b level...
answer=0
attempts = 0
while answer!=4:
answer=input("What is 2 + 2?")
if answer!=4:
print("Wrong...Try again.")
attempts = attempts + 1
else:
print("Yes! 2 + 2 = 4")
print("You gave correct answer in %d attempts" % attempts)
Ok so I've written this and for some reason the multiplier and final score isn't always working for instance:
Would you like to read the rules?(Y/N) n
Would you like to play?(Y/N) y
Lowest number: 1
Hightest number: 6
I'm thinking of a number guess what it is...
Guess: 3
Well Done! You guessed Correctly!
You scored 15 points!
Would you like to play again?[Y/N] n
You scored a total of 15 points!
Your score multipler is 1!
Your final score is 22!
Now as you can see the score is right. The multiplier should be 1.5 which means the the final score should be 22.5. However it's saying the multiplier is 1 and the final score is 22?
However sometimes is works like this:
Would you like to read the rules?(Y/N) n
Would you like to play?(Y/N) y
Lowest number: 1
Hightest number: 10
I'm thinking of a number guess what it is...
Guess: 5
Too low!
You guessed incorrectly. You have 2 live(s) remaining.
Guess: 7
Well Done! You guessed Correctly!
You scored 10 points!
Would you like to play again?[Y/N] n
You scored a total of 10 points!
Your score multipler is 2!
Your final score is 25!
As you can see the range is 10 so the multiplier should be 2.5 however it prints it as 2. With the write multiplier the answer would be 25 however with the answer it provides it should be 20.
I will include my code underneath but this is really really confusing me. I need help soon as I have to had this in tomorrow Please Please Please help me!!
code
#imports required modules
import random
#score set as global variable with the value 0
global score
score = 0
def start():
#askes if user needs rules
rules = input('Would you like to read the rules?(Y/N) ')
#if yes rules are printed
if rules.lower() == 'y':
#prints inctructions
input('\t\t\t\t\tRules\n')
input("Guess the number the computer is thinking of to win but you only have 3 lives.")
input("\nStart by choosing the range of numbers the computer can choose from.")
input("""For example if I wanted a number between 1 and 10 I would type 1 for
lowest number and 10 for highest number.""")
input("""\nThe more lives you have left when you win the more points you get.
The larger the range of numbers you give the computer
the larger your score multipler.""")
input("\nIt can be harder than you think!")
input("\n\t\t\t\t\tEnjoy!")
#if not player is aksed to play
play = input("\nWould you like to play?(Y/N) ")
if play.lower() == 'n':
#if they don't game quits
quit()
#main game code
def main():
global low
global up
#generates number at random between the users two inputs
comp_num = random.randint(low,up)
#score set as global variable within function
global score
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!')
#1 live left player gets 5 points
if lives == 1:
score += 5
print('\nYou scored 5 points!\n')
#2 lives left player gets 10 points
elif lives == 2:
score += 10
print('\nYou scored 10 points!\n')
#3 lives left player gets 15 points
elif lives == 3:
score += 15
print('\nYou scored 15 points!\n')
break
elif guess > up:
#if number is high than possible player gets told
print('\nThat is higher than the highest number you slected')
#reminded of boundries
print('\nRemember your lowest number is',low,'and your highest number is',up,'.')
#asked to try again
print('\nPlease try again!\n')
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
#starts game
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
#if they don't want to play again while loop breaks
break
if play_again.lower() == 'n':
#if they don't game ends
#prints score
input('\nYou scored a total of %i points!\n' % score)
#prints mulipler
input('Your score multipler is %i!\n' % multi)
#calculates total score
total = float(score*
multi)
#prints total score
input('Your final score is %i!\n' % total)
input('Press enter to exit')
#calls intial game function to start
start()
#lower number set as global and value of user input
global low
low = int(input('\nLowest number: '))
#lower number set a global and value of user input
global up
up = int(input('Hightest number: '))
#sets up the score mulitpler
rang = float(up - low + 1)
multi = float(rang/4)
#if the multipler is less then 1 it gets sent to 1 so it doesn't remove points
if multi < 1:
multi = 1
#starts atcual game
print('\nI\'m thinking of a number guess what it is...\n')
#calls main section of game
main()
#calls end of game to give option of playing again and resetting game
end()
Check this:
#if they don't game ends
#prints score
input('\nYou scored a total of %i points!\n' % score)
#prints mulipler
input('Your score multipler is %i!\n' % multi)
#calculates total score
total = float(score*
multi)
#prints total score
input('Your final score is %i!\n' % total)
You print numbers like 15, 1, 22. Those numbers are calculated as they should, but not printed as they should. this is caused by you using wrong format identifiers.
Replace the %i formatters with %f formatters and it will work.