Does anybody know why the score counter isn't working in this program? The program is designed to run 10 random maths questions and then display the score. However although it asks the questions, it will always display the score as being '0'
name = input('Type in your name')
questioncount = 0
score = 0
import random
for questioncount in range(0,10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.randrange(1,4)
if (sign) == 1 :
print('{}x{}'.format(number1, number2))
elif (sign) == 2 :
print ('{}+{}'.format(number1, number2))
elif (sign) == 3 :
print ('{}-{}'.format(number1, number2))
answer = input('What is the answer?')
if (sign) == 1:
if (answer) == number1*number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1+number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1-number2:
score == score+1
else:
pass
pass
print('you got {} answers right!'.format(score))
There are some problems:
You forgot to change the numbers in the if statements.
You have to parse the input of the answer into int because input returns a string.
score == score+1 is a comparison and it always returns false. It should be "=". score = score + 1 or in a shorter way score += 1 is exactly the same
2 ifs nested for just one thing could be written in the same if statement.
You wrote this:
if (sign) == 2:
if (answer) == number1+number2:
score += 1
else:
pass
It could be:
if (sign) == 2 and (answer) == number1+number2:
score += 1
You should use if/elif statements instead of else:pass
This way
if (sign) == 1 and (answer) == number1*number2:
score += 1
elif (sign) == 2 and (answer) == number1+number2:
score += 1
elif (sign) == 3 and (answer) == number1-number2:
score += 1
and even better
if (sign == 1 and answer == number1 * number2) or (sign == 2 and answer == number1 + number2) or (sign == 3 and answer == number1 - number2) :
score += 1
That said, I would write this program like this:
import random
name = input('Type in your name\n')
score = 0
for _ in range(10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.choice(["*", "+", "-"])
expression = "{0} {1} {2}".format(number1,sign,number2)
print(expression)
answer = int(input('What is the answer?\n'))
print("-------------")
if answer == eval(expression):
score += 1
print('{}, you got {} right answers!'.format(name, score))
Notes:
The use of _ it's because it is not important. You can call it whatever you want and you don't even have to declare it before.
The \n means carriage return.
You should do some more changes to prevent user from writting others characters in the answer, but I think you have work enough to do with this.
Related
Basically i need to make a game im python that can have a arbitrarily number of people that alternatly answers a multiplication question. But my issue is that i dont know how to keep it running until i hit 30 points. Ive tried to use dict's where the key is the player name and the value is the score. But it stops after the script only has ran once. I tried with a while loop but it went on forever. please help!
import random as r
n = int(input("Insert number of players: "))
d = {}
for i in range(n):
keys = input("Insert player name: ")
#to set the score to 0
values = 0
d[keys] = values
#to display player names
print("Player names are:")
for key in d:
print(key)
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
break
I think this will work
winner = False
while not winner :
for value in d.values():
if value < 30:
random1 = r.randint(0,9)
random2 = r.randint(0,9)
print(f"The two numbers you should multiplie is {random1} and {random2}")
correct = random1*random2
user_inp = input("Insert answer: ")
user_inp = int(user_inp)
if user_inp == correct:
print("Correct!")
d[keys] += 1
else:
print("Wrong!")
d[keys] -= 2
else:
winner = True
break
I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')
I want to take two input. The program must accept only valid scores (a score must fit in the range [0 to 10]). Each score must be validated separately. If the input is not valid, I want to print "Wrong input".
After taking two valid input, I want to print sum of the values.
count = 0
count2 = 0
while True:
a = float(input())
if 0 <= a <= 10:
count2 += a
count2 += 1
b = float(input())
if 0 <= b <= 10:
count2 += b
count += 1
else:
print('Wrong input')
if count == 2:
break
print('Sum = {}'.format(count2))
Sample input:
-3.5
3.5
11.0
10.0
Output:
Wrong input
Wrong input
sum = 13.5
By taking two while loops you can easily verify each input individually till you get the expected value.
while True:
a = float(input())
if 0<=a<=10:
break
else:
print('Wrong Input')
while True:
b = float(input())
if 0<=b<=10:
break
else:
print('Wrong Input')
print("sum =", a+b)
So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()
I am a beginner with python and I wrote a quiz program, how do I repeat a question in my quiz if the answer given is wrong? I'd also like to give the user an option to skip to the next question in the same text box as the answer.
This is my current source code:
score = 0
q1 = input("What is the square root of 64?: ")
if q1 == ("8"):
print("Correct!")
score = score + 1
if q1 == ("skip"):
break
else:
print("Incorrect.")
print("")
q2 = input("Who was president during the year 1970?: ")
if q2 == ("Richard Nixon") or q2 == ("richard nixon"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q3 = input("How many stars are on the American flag?: ")
if q3 == ("50"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q4 = input("In the US, which state has the largest population?: ")
if q4 == ("California") or q4 == ("california"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
q5 = input("Who discovered the Americas in 1492?: ")
if q5 == ("Christopher Columbus") or q5 == ("christopher columbus"):
print("Correct!")
score = score + 1
else:
print("Incorrect.")
print("")
if score == 0:
print("Your score is 0. Better luck next time.")
if score == 1:
print("Your score is 1. Better luck next time.")
if score == 2:
print("Your score is 2. Better luck next time.")
if score == 3:
print("Your score is 3. Not bad. Try again soon!")
if score == 4:
print("Your score is 4. Not bad. Try again soon!")
if score == 5:
print("Your score is 5. Awesome! You rock!")
You'll want to make use of functions to call the same code to show the question.
To do the skipping, you can have the program detect a special answer (in the example below it's "skip") and use that to recognize when to skip to the next question).
Here's an example:
QUESTIONS = {'question1' : 'answer', 'question2': 'answer'}
score = 0
def ask_question(question, answer):
global score
while True:
response = input(question + "\n")
if response == 'skip':
return
elif response == answer:
score += 1
break
def question_loop():
for question, answer in QUESTIONS.items():
ask_question(question, answer)
def print_results():
#print results here
pass
question_loop()
print_results()