Display the number of times each output was displayed in 'X's - python

while True:
try:
wins = int(input("enter number of wins: "))
draws = int(input("enter number of draws: "))
losses = int(input("enter number of losses: "))
except ValueError:
print('try again')
continue
if wins>3:
print('qualify')
elif losses>3:
print('disqualify')
elif draws>3:
print('try again')
restart = str(input('enter "restart" to restart or "quit" to quit'))
if restart == 'restart':
continue
elif restart == 'quit':
#quit and display number of occurrences of qualify, disqualify and try again in 'X's

First you need to track the count of each result. You could do this with three different variables, but I think it's a little easier to use a dictionary, or better yet a Counter:
from collections import Counter
counts = Counter()
Make sure to initialize this outside your loop, since you want to keep the same Counter through multiple iterations of the loop; if you reset it inside the loop, it won't keep track of anything!
Then track the results as you see them:
if wins > 3:
result = "qualify"
elif losses > 3:
result = "disqualify"
elif draws > 3:
result = "try again"
else:
print("Not enough of anything to produce a result!")
continue
print(result)
counts[result] += 1
and then at the end, you can convert the counts into "X" marks by string multiplication:
for result in counts:
print(f"{result}: {'X' * counts[result]}")
All together it looks like:
from collections import Counter
counts = Counter()
while True:
try:
wins = int(input("enter number of wins: "))
draws = int(input("enter number of draws: "))
losses = int(input("enter number of losses: "))
except ValueError:
print("try again")
continue
if wins > 3:
result = "qualify"
elif losses > 3:
result = "disqualify"
elif draws > 3:
result = "try again"
else:
print("Not enough of anything to produce a result!")
continue
print(result)
counts[result] += 1
if str(input('enter "restart" to restart or "quit" to quit')) == "quit":
break
for result in counts:
print(f"{result}: {'X' * counts[result]}")

I didn't understand your question but based on what I understood I constructed a solution. This will show you the result of occurrence of qualify and disqualify
qualifycount=0
disqualifycount=0
while True:
try:
wins = int(input("enter number of wins: "))
draws = int(input("enter number of draws: "))
losses = int(input("enter number of losses: "))
except ValueError:
print('try again')
continue
if wins>3:
print('qualify')
qualifycount+=1
elif losses>3:
print('disqualify')
disqualifycount+=1
elif draws>3:
print('try again')
restart = str(input('enter "restart" to restart or "quit" to quit'))
if restart == 'restart':
continue
elif restart == 'quit':
#quit and display number of occurrences of qualify, disqualify and try again in 'X's
print("Number of qualify:"+str(qualifycount))
print("Number of disqualify:"+str(disqualifycount))
restart= str(input('press X to run again or press enter to quit'))
if restart=='X':
continue
else:
break

Related

How do I make a program keep repeating until I input a specific data that stops it?

I'm trying to make a program in python so that when I input a number from 1 to 10, a specific set of program goes on and asks for another number from 1 to 10 and runs another program, until I enter 0(zero) and the program stops.
So my guess was using a while loop but it didn't quite work out.
user_input = input()
user_input = int(user_input)
while user_input != 0:
(program)
else:
quit()
Try this:
user_input = int(input())
while user_input != 0:
(program)
user_input = int(input())
quit()
With your current code you only ask for input once so the loop won't end. This way you can input a new number after every iteration.
Your current program only asks once and then the loop keeps repeating. You need to keep asking for input inside the loop.
def program():
print("Executing Task....")
user_input = int(input())
while user_input != 0:
program()
user_input = int(input())
printf("Program Terminated")
Here it is:
def program():
pass
user_input = int(input())
while user_input:
program()
user_input = int(input())
quit(0)
A different way using iter with a sentinel:
def program(number):
if number < 0 or number > 10:
print('Invalid number:', number)
else:
print('Valid number:', number)
def quit():
print('quitting')
def get_number():
return int(input('Enter a number from 1 to 10: '))
for number in iter(get_number, 0):
program(number)
else:
quit()
not_zero = True
while not_zero:
num = int(input("Enter a number: "))
if num == 0:
not_zero = False
you can stop your loop using a boolean value.

I want to print when the user fails to type a positive number it will tell them the number was not valid (eg -8.25)

def itemPrices():
items = []
while True:
itemAmount = float(input("Enter the amount for the item: "))
if itemAmount < 0:
continue
again = input("Do you want to add another item? Enter 'y' for yes and 'n' for no: ")
items.append(itemAmount)
if again == "y":
continue
elif again == "n":
numItems = len(items)
print(f"You purchased {numItems} items.")
sumAmount = sum(items)
print(f"The total for this purchase is {sumAmount} before tax.")
print(f"The average amount for this purchase is {sumAmount/numItems}.")
if numItems >= 10:
tax = (9/100)*sumAmount
else:
tax = (9.5/100)*sumAmount
print(f"You owe ${tax} in tax.")
break
else:
print("Invalid input")
continue
itemPrices()
while True:
user_input = input("type a number")
try:
if float(user_input) < 0:
print('this number is less than zero please try again')
continue
else:
print("good job this number is valid")
# place the code you want to execute when number is positive here
break
except ValueError:
print("this is not a number please enter a valid number")
continue

Python array loop not looping/validator issues

I'm not exactly sure what I did, but when testing my code it either crashes immediately or gets stuck in a loop. If the first input is a value error (string) and the next is a number it loops as long as the pattern is kept. But if first user entry is int then program crashes. Please any help would be appreciated.
def main():
courseArray = []
keepGoing = "y"
while keepGoing == "y":
courseArray = getValidateCourseScore()
total = getTotal(courseArray)
average = total/len(courseArray)
print('The lowest score is: ', min(courseArray))
print('The highest score is: ', max(courseArray))
print('the average is: ', average)
keepGoing = validateRunAgain(input(input("Do you want to run this program again? (Y/n)")))
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray)
except ValueError:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
counter += 1
return courseArray
def valScore(courseArray):
score = int(courseArray)
if score < 0:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
elif score > 100:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
else:
return courseArray
def validateRunAgain(userInput):
if userInput == "n" or userInput == "N":
print("Thanks for using my program")
return "n"
elif userInput == "y" or userInput == "Y":
return "y"
else:
print("Please enter y or n")
validateRunAgain(input("Do you want to run this program again? (Y/n)"))
return getValidateCourseScore()
def getTotal(valueList):
total = 0
for num in valueList:
total += num
return total
main()
There are too many inputs from the user, so I have cut down on them and changed it.
Here are the sections of your code which I have changed :
Here valScore() I presume validates the input score so, I also gave the index of element to be validated. If it is not valid we remove it from the array and raise ValueError, since it raises error our counter is not updated.
keepGoing = validateRunAgain()
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray, counter - 1)
counter += 1
except ValueError:
print("Please enter a valid score between 0-100")
continue
return courseArray
def valScore(courseArray, counter):
score = courseArray[counter]
if score < 0 or score > 100:
courseArray.pop()
raise ValueError
def validateRunAgain():
while True:
userInput = input("Do you want to run this program again? (Y/n)")
if userInput == 'y' or userInput == 'Y':
return 'y'
elif userInput == 'n' or userInput == 'N':
print('thank you for using my program')
return 'n'
else:
print('Enter Y or N')

Python Positioning correctly in a while loop

My current code works but when the option menu appears, and i select an option, its supposed to repeat from the selection again, however my code restarts from the start where it asks to enter a number rather than entering an option.
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
So it means that I need to reposition my code within the while loop, or take the input stage to a different position?
You need a nested loop
(tried to change your original code as little as possible) I changed it to include your options menu within a while loop (in addition to another break statement outside the while loop, to make sure the program doesn't repeat itself (unless you want it to...)).
n = 0
amount = 0
total = 0
while n != "":
try:
n=int(input("Enter a number: "))
amount = amount+1
total = total + n
except ValueError:
average = total/amount
choice = -1 # new
while(choice != 0): # new
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break
break # new
keep in mind this COULD be a good deal more robust, and there exists no functionality for handling options selected outside the ones specified (though should someone enter a 5 or something it will just repeat)
Sometimes I find it cleaner to have your cope loop forever with while True and to break out of it as necessary. I also try to reduce nesting where possible, and I don't like to use exception handling for a valid input choice. Here's a slightly reworked example:
amount = 0
total = 0
while True:
n = input("Enter a number: ")
if n == "":
break
amount = amount+1
total = total + int(n)
average = total/amount
while True:
print()
print("Which option would you like?")
print("1 - Number of values entered")
print("2 - Total of the values entered")
print("3 - Average of values entered")
print("0 - Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
print(amount, "numbers were input.")
elif choice == 2:
print("The total of the sequence is", total)
elif choice == 3:
print("The average is",average)
elif choice == 0:
print("Exit")
break

how to implement empty string in python

I need to be able to prompt the user to enter an empty string so it can check if the answer is correct. but every time I do that I can error saying invalid literal for int()
so I need to change my user_input so it can accept int() and strings(). how do I make that possible ?
# program greeting
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
#print("Enter coins that add up to 81 cents, one per line.")
import sgenrand
#prompt the user to start entering coin values that add up to 81
while True:
total = 0
final_coin= sgenrand.randint(1,99)
print ("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
while total <= final_coin:
user_input = int(input("Enter next coin:"))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
if total > final_coin :
print("Sorry - total amount exceeds", (final_coin))
elif total < final_coin:
print("Sorry - you only entered",(total))
else:
print("correct")
goagain= input("Try again (y/n)?:")
if goagain == "y":
continue
elif goagain == "n":
print("Thanks for playing ... goodbye!" )
break
Store the value returned by input() in a variable.
Check that the string is not empty before calling int().
if it's zero, that's the empty string.
otherwise, try int()ing it.

Categories

Resources