highscore and keeping score - python-3.x

#This is a for loop to get the score of a player playing a riddle game
#It runs and loops but it's not calculating the score properly. #There're 6 riddles and 3 rounds. #Say I get 4/6 correct my score is 20 but it's displaying 3.0 instead. how do I get a precise answer while importing the math function?
for i in range(6):
print(riddles[i])
#
userchoice = input("Enter A, B, C, or D: ")
if userchoice.upper() == answers[i]:
print("That's Correct")
score += 5
print(f" {score}")
else:
print("That's Incorrect")
score -= 1
print(f"{score}")
total = total + int(score)
highScoreEasy = print(f"Here is your score: {int(total/score)} !!!!!")
print()

Shouldn't it just be a simple sum?
riddles = []
answers = []
riddle_score = 5
total = len(riddles) * riddle_score
score = 0
for i, riddle in enumerate(riddles):
print(riddle)
userchoice = input("Enter A, B, C, or D: ")
if userchoice.upper() == answers[i]:
print("That's Correct")
score += riddle_score
else:
print("That's Incorrect")
print(f"Here is your score: {score}/{total}!")

Related

Python Word guessing game, cannot get While loop to repeat program

I am trying to create a word guessing game in python. I can get the program to run once,
but I want it to run five times in a row keeping track of wins and losses, and this is where
I am running into issues. I have tried adding a counter and nesting the while loop but this does not seem to work. Any help or suggestions would be greatly appreciated. Thanks.
Here is the code I have written:
import random
print('Welcome to the word guessing game!')
input("What is your name? ")
print('Try to guess the word letter by letter, you have ten guesses, good luck!')
words = ['cowboy', 'alien', 'dog', 'airplane',
'trees', 'bridge', 'snake', 'snow',
'popcorn', 'apples', 'road', 'smelly',
'eagle', 'boat', 'runner']
word = random.choice(words)
print("Guess the word!")
guesses = ''
trys = 5
wins = 0
losses = 0
rounds = 0
while rounds < 5:
while trys > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("*")
failed += 1
if failed == 0:
print("You Win")
print("The word is: ", word)
wins = wins + 1
rounds = rounds + 1
break
print()
guess = input("Enter your letter:")
guesses += guess
if guess != word:
trys -= 1
print("Plesae try again, You have", + trys, 'more guesses')
if trys == 0:
print("You Loose, better luck next time")
losses = losses + 1
rounds = rounds + 1
print('Wins:', wins )
print('Losses:', losses)

Python multiply game. My script needs to have a arbitrarily number of players that each have to take turn in answering a multiplication question

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

Number Guessing game Computer Playing

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

repeat question after answer is wrong, including a "skip" option

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

Python Loop until condition is met

I'm trying to write a program for an assignment and for one section, I need to create division questions. I need it so that when the random numbers are picked, the first number will always be larger than the second number. the function that I have created does most of the work but I cant seem to figure out how to get it to loop until the condition is met. In the code, I have tried using a while loop but when I run it, I still get the first number as being a lower number.
Does anyone have any recommendations as to how I could do this?
import random
import time
score = 0
Addition = range(1, 20)
Multiplication = ['1', '2', '3', '4', '5']
Division = ['1', '2', '4', '6', '8', '10']
def additionfunc():
for x in range (0, 4):
a = random.choice(Addition)
b = random.choice(Addition)
c = float(a) + float(b)
print("What is", a," plus", b)
answer = int(input("Please enter your answer: "))
if answer == c:
print("Correct")
print("Plus 10 points")
global score
score = score + 10
print()
time.sleep(1)
else:
print("Incorrect")
print("No points added")
print()
time.sleep(1)
print("Well done, your score was", score)
print()
mainmenu()
def multiplicationfunc():
for x in range (0, 4):
a = random.choice(Multiplication)
b = random.choice(Multiplication)
c = float(a) * float(b)
print("What is", a," multiplied by", b)
answer = int(input("Please enter your answer: "))
if answer == c:
print("Correct")
print("Plus 10 points")
global score
score = score + 10
print()
time.sleep(1)
else:
print("Incorrect")
print("No points added")
print()
time.sleep(1)
print("Well done, your score was", score)
print()
mainmenu()
def divisionfunc():
for x in range (0,4):
a = random.choice(Division)
b = random.choice(Division)
c = float(a) / float(b)
print("What is", a, "divided by", b)
answer = float(input("Please enter your answer: "))
if answer == c:
print("Correct")
print("Plus 10 points")
global score
score = score +10
print()
time.sleep(1)
else:
print("Incorrect")
print("No points added")
print()
time.sleep(1)
print("Well done, your score was", score)
print()
mainmenu()
def mainmenu():
print("Welcome to the Numeracy Game")
print("1. Addition")
print("2. Multiplication")
print("3. Division")
print("Score =", score)
time.sleep(2)
Genre = int(input("Enter the value for the mode:"))
print()
if Genre == 1:
additionfunc()
elif Genre == 2:
multiplicationfunc()
elif Genre == 3:
divisionfunc()
mainmenu();
I hope this is what you need:
division= ['1', '2', '4', '6', '8', '10'] #[1,2,4,6,8,10]
# you could also use random.randint(start, stop)
#if you only want even ints you can use random.randint(0,10,2)
a = random.choice(division) # random.ranint(0,10)
b = random.choice(division) # random.randint(0,10)
if b == 10:
#prevents b from being the biggest number which would result in an endless loop
b = random.choice(division)
while a < b or a==b: # if a is smaller or same as b change a
a = random.choice(division)
else:
# it would be easier to use ints instead string and only convert
# them to string in your print statemnt
c = float(a)/float(b)

Resources