How do I loop this code? - python

How do I loop this code with a "do you want to run this again" question?
count = 1
total = 0
markslist = list()
while count <= 10:
newmark = input("Input Mark Out Of 100 (" + str(count) + ") ")
markslist.append(newmark)
if newmark > 100:
import sys
sys.exit("Error Mark is greater than 100 re-run program")
total = total + newmark
count = count + 1
average = (total / 10)
print "Average Mark = " + str(average)

Just wrap the entire code in a loop similar to this:
while True:
again = input('Go? (y/n): ')
if again != 'y':
break
# The entirety of the rest of your program would go here.

Related

How can I print variable which is int from while loop and if else in Python

The error I get from the program is undefined variable.
*
# Python 3.9.4
# import sys
# print(sys.version)
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
Iterate = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
for i in range(Iterate): # It will run how many time based on Iterate input
Score = float(input("Enter score: "))
Counter = True
while Counter:
if 80 <= Score < 100:
Accumulate1 = Accumulate + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate + 1
elif Score < 50:
Accumulate4 = Accumulate + 1
else:
print("The number is a negative value or incorrect")
Again = input("Enter yes for restarting again or if you want to exit the program please press anything: ")
if Again in ("y", "Y", "YES", "Yes", "yes"):
continue
else:
break
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)
This is my first post in Stackoverflow.
pardon me for any inappropriate content.
Thanks you so much.
You stated
Counter = True
without iteration, thus it will run indefinitely. With while loop you need to set some constraints.
I realised why you had the While loop in there, but it still wasn't working for me effectively - if all answers were within range it never terminated. This should work for you, it does for me. I changed it so it checks every time somebody enters a score that it is within the correct range, so you don't have to repeat the whole loop in the event of incorrect values
SubjectT = input("Enter your subject: ")
Tutor_Name = input("Enter your name: ")
NoOfStudents = int(input("How many students are there? "))
# Set counter
# create count for each student
Accumulate = 0
Accumulate1 = 0
Accumulate2 = 0
Accumulate3 = 0
Accumulate4 = 0
def validRange(score):
if 0 <= score <=100:
return True
else:
return False
i = 1
while (i <= NoOfStudents): # It will run how many time based on Iterate
validInput = False
while (not validInput):
Score = float(input("Enter score: "))
if ( not validRange(Score)):
print("The number is a negative value or incorrect")
else:
validInput = True
if 80 <= Score < 100:
Accumulate1 = Accumulate1 + 1
elif 80 > Score >= 65:
Accumulate2 = Accumulate2 + 1
elif 65 > Score >= 50:
Accumulate3 = Accumulate3 + 1
elif Score < 50:
Accumulate4 = Accumulate4 + 1
i = i+1
print(f"Subject title:", {SubjectT}, "\nTutor:", {Tutor_Name})
print("Grade", " Number of students")
print("A", "Students: ", Accumulate1)
print("B", "Students: ", Accumulate2)
print("C", "Students: ", Accumulate3)
print("D", "Students: ", Accumulate4)

Guessing Game - Looping Problem in Python

I had to build a game which awards players based on their guess. The user guesses a number and the algorithm compares that to a randomly-generated 2-digit number and awards the player accordingly.
Problem: The player needs to play this game 3 times before the game ends. When I loop it 3 times with a while loop it only loops by asking the user for their guess and does not print or return the award message. When I remove the while loop and use a for loop it only runs once and prints the message.
How do I solve this looping issue and run this program thrice?
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
play = 3
turns = 1
def lottery_game():
for x in range(play):
lottery = random.randrange(10,99)
lot = list(map(int, str(lottery)))
guess = int(input("Choose a 2 digit number: "))
n_guess = list(map(int, str(guess)))
if guess == lottery:
return "You won: " + str(jackpot) + " Euros"
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
return "You won: " + str(award2) + " Euros"
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
return "You won: " + str(award3) + " Euros"
else:
return "I am sorry, you won: " + str(noaward) + " Euros" + " try again"
while i <= 3:
lottery_game()
i = i + 1
According to your code, you're not initialising your i variable before your while you shoud definitely do it. But for your use case, you shouldn't use a while, you should use a for loop like this:
for i in range(0,3):
This will run the code in the loop three times.
You need to
replace return with print statement:
replace while i <= 3 with for i in range(3)
Here is updated code:
import random
jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
def lottery_game():
lottery = random.randrange(10, 99)
lot = list(map(int, str(lottery)))
guess = int(input('Choose a 2 digit number: '))
n_guess = list(map(int, str(guess)))
if guess == lottery:
print(f'You won: {jackpot} Euros')
elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
print(f'You won: {award2} Euros')
elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
print(f'You won: {award3} Euros')
else:
print(f'I am sorry, you won: {noaward} Euros. Try again')
for i in range(3):
lottery_game()
Sample output:
Choose a 2 digit number: I am sorry, you won: 0 Euros. Try again
Choose a 2 digit number: You won: 100 Euros
Choose a 2 digit number: You won: 10000 Euros
you have not initialized i
Before the while statement add i=1

I don't understand how my calculations are being read as a str instead of an integer when the variables are valued with numbers

I am making a number guessing game for a project as a part of my intro to the coding class. I am trying to calculate the total earnings for the user, but I keep getting a type error and I have no idea what I am doing wrong.
print("To begin the game pay two dollars")
print("You can collect your winnings when you stop playing")
import sys
count = 0
Jackpot_wins = 0
Reversed_digits = 0
Digit_WrongPlacement = 0
Digit_RightPlacement = 0
Digit_RightPlacement_two = 0
Digit_WrongPlacement_two = 0
JackpotValue = 100
Reversed_digitsValue = 10
Digit_RightPlacementValue = 10
Digit_WrongPlacementValue = 5
Cost_Per_Play = 2
Game_start = input("Would you like to play? enter 'y' for yes and 'n' for no: ")
if Game_start == "n":
print("Thats ok, maybe next time")
sys.exit()
while Game_start == "y":
count = count + 1
Money_Spent = count * Cost_Per_Play
Player_Number = int(input("Enter a number 0-99: "))
print(Player_Number)
import random
Hidden = random.randint(0,99)
Reversed_digits = (str(Hidden)[::-1])
print(Hidden)
Jackpot = Hidden == Player_Number
PN = int(Player_Number / 10)
RN = int(Hidden / 10)
PN1 = int(Player_Number % 10)
RN1 = int(Hidden % 10)
if Jackpot:
print("Jackpot!!! You win 100 dollars!!!")
Jackpot_wins = int(Jackpot_wins + 1)
elif Player_Number == Reversed_digits:
print("Right digits, wrong order!... You win 10 dollars!")
Reversed_digits = int(Reversed_digits + 1)
elif PN == RN:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement = int(Digit_RightPlacement + 1)
elif RN1 == PN1:
print("One digit correct, place correct. You win 10 dollars!")
Digit_RightPlacement_two = int(Digit_RightPlacement_two + 1)
elif PN1 == RN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement = int(Digit_WrongPlacement + 1)
elif RN1 == PN:
print("One digit correct, place incorrect. You win 5 dollars!")
Digit_WrongPlacement_two = int(Digit_WrongPlacement_two + 1)
else:
print("Completely wrong")
Game_start = input("To continue type 'y' to end type anything: ")
JP_money = Jackpot_wins * JackpotValue
RD_money = Reversed_digits * Reversed_digitsValue
DRP_money = Digit_RightPlacement * Digit_RightPlacementValue
DRP1_money = Digit_RightPlacement_two * Digit_RightPlacementValue
DWP_money = Digit_WrongPlacement * Digit_WrongPlacementValue
DWP1_money = Digit_WrongPlacement_two * Digit_WrongPlacementValue
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
Total_earnings = Winnings - Money_Spent
if Game_start != "y":
print("See you next time! You played ", count, "rounds.")
print("you spent $ ", Money_Spent)
print("Wow you won the Jackpot", Jackpot_wins, "times!")
print("Your total earnings are", Total_earnings, "Congrats!")
I expected the code to keep tally of the wins and their varying values but I am either getting a type error or a value that is unbelievable like 72727171723
Yes, I tested the code, in your Winning calculation RD_Money is returning string number,
Winnings = JP_money + RD_money + DRP_money + DRP1_money + DWP_money + DWP1_money
For resolving this you can just convert it in the calculation like this
Winnings = JP_money + int(RD_money) + DRP_money + DRP1_money + DWP_money + DWP1_money
or you can do this
RD_money = int(Reversed_digits) * Reversed_digitsValue
This will solve your problem

Python 3: Returning variable through multiple functions

I have been given a basic python problem that requires me to make a simple addition quiz. However, I cannot seem to return my count variable which is supposed to update the number of correct questions the user has answered, which makes it stuck at 0. I have tried defining the variable count in every function containing it as an argument but still does not work. Say if the user were to answer 4 questions and got 3 correct, it would display it as "You have answered 4 questions with 3 correct", but instead it displays "You have answered 4 questions with 0 correct".
Every time your check_solution and menu_optionfunctions get called, you initialize count = 0. This means every time the user requests another question, count gets reset to 0, twice. You're going to want to remove those count = 0 calls, and you also want to capture your updates to count within menu_option. Your final program should look something like this:
import random
def get_user_input():
count = 0
user_input = int(input("Enter 1 to play or press 5 to exit: "))
while user_input > 5 or user_input <= 0:
user_input = int(input("Invalid menu option. Try again: "))
menu_option(user_input, count)
if user_input == "5":
print("Exit!")
return user_input
def get_user_solution(problem):
answer = int(input(problem))
return answer
def check_solution(user_solution, solution, count):
curr_count = count
if user_solution == solution:
curr_count += 1
print("Correct.")
else:
print("Incorrect.")
print(curr_count)
return curr_count
def menu_option(index, count):
if index == 1:
num1 = random.randrange(1, 21)
num2 = random.randrange(1, 21)
randsum = num1 + num2
problem = str(num1) + " " + "+" + " " + str(num2) + " " + "=" + " "
user_answer = get_user_solution(problem)
count = check_solution(user_answer, randsum, count) # count returned by check_solution is now being captured by count, which will update your count variable to the correct value
return count
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct.")
print("Your score is 0%. Thank you.")
else:
score = round((correct / total) * 100, 2)
print("You answered", total, "questions with", correct, "correct.")
print("Your score is", str(score) + "%.")
def main():
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exiting.")
display_result(total, correct)
main()
You need catch the return from check_solution(user_answer, randsum, count) and return that count
As the comment stated, you are initializing count to 0 every time your check_solution or menu_option is called.
It looks like you want to use count = count the variable being passed to your function.
Just a quick edit:
You actually don't need to return count. In Python, variables are passed by reference so your count will get updated as long as it's being passed to your functions.
You have the option of initializing count to 0 before all functions, thus creating a global variable. Then you won't need to declare it on any function nor pass it as argument.
This is a culmination of several errors in logic.
You give count to functions as input and immediately overwrite it.
I would instead say def menu_option(index, count=0):. This will set count=0 if no variable is supplied (creating a default), otherwise it will set count as whatever you pass into the function
Your check_solution() function returns a number, but when you call it with check_solution(user_answer, randsum, count) you never assign this returned value to anything/use it again.
You can assign this to a variable (say output) and then return output instead of return count
Fixing these still doesn't fully solve the problem, but gets a little bit closer (now it gets stuck on "you answered x questions with 1 correct"):
import random
def get_user_input(count = 0):
user_input = int(input("Enter 1 to play or press 5 to exit: "))
while user_input > 5 or user_input <= 0:
user_input = int(input("Invalid menu option. Try again: "))
menu_option(user_input, count)
if user_input == "5":
print("Exit!")
return user_input
def get_user_solution(problem):
answer = int(input(problem))
return answer
def check_solution(user_solution, solution, count):
count = 0
if user_solution == solution:
count += 1
print("Correct.")
else:
print("Incorrect.")
return count
def menu_option(index, count=0):
if index == 1:
num1 = random.randrange(1, 21)
num2 = random.randrange(1, 21)
randsum = num1 + num2
problem = str(num1) + " " + "+" + " " + str(num2) + " " + "=" + " "
user_answer = get_user_solution(problem)
output = check_solution(user_answer, randsum, count)
return output
def display_result(total, correct):
if total == 0:
print("You answered 0 questions with 0 correct.")
print("Your score is 0%. Thank you.")
else:
score = round((correct / total) * 100, 2)
print("You answered", total, "questions with", correct, "correct.")
print("Your score is", str(score) + "%.")
def main():
option = get_user_input()
total = 0
correct = 0
while option != 5:
total += 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exiting.")
display_result(total, correct)
main()
I think a more simplistic approach would look something like:
import random
def generate_question():
num1 = random.randint(1, 25)
num2 = random.randint(1, 25)
question = '{} + {} = '.format(num1, num2)
answer = num1 + num2
return question, answer
def main():
correct = 0
total = 0
option = True
while option != '5':
total += 1
question, answer = generate_question()
user_guess = int(input(question))
if user_guess == answer:
print('Correct.')
correct += 1
else:
print('Incorrect.')
option = input("Enter 5 to exit, or anything else to play again")
print('You answered {} questions with {} correct'.format(total, correct))
main()

figuring out how to find the average of entered numbers

here is my current code:
total = 0.0
count = 0
data = input("Enter a number or enter to quit: ")
while data != "":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter to quit: ")
average = total / count
if data > 100:
print("error in value")
elif data < 0:
print("error in value")
elif data == "":
print("These", count, "scores average as: ", average)
The only problem now is "expected an indent block"
I would do something cool like
my_list = list(iter(lambda: int(input('Enter Number?')), 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
if you wanted to do conditions, something like this would work
def getNum():
val = int(input("Enter Number"))
assert 0 < val < 100 or val == 999, "Number Out Of Range!"
return val
my_list = list(iter(getNum, 999)) # Thanks JonClements!!
print sum(my_list)
print sum(my_list)/float(len(my_list))
To calculate an average you will need to keep track of the number of elements (iterations of the while loop), and then divide the sum by that number when you are done:
total = 0.0
count = 0
data = input("Enter a number or enter 999 to quit: ")
while data != "999":
count += 1
number = float(data)
total += number
data = input("Enter a number or enter 999 to quit: ")
average = total / count
print("The average is", average)
Note that I renamed sum to total because sum is the name of a built-in function.
total = 0.0
count = 0
while True:
data = input("Enter a number or enter 999 to quit: ")
if data == "999":
break
count += 1
total += float(data)
print(total / count)

Categories

Resources