This is some of my homework but i am really stuck and can't find any advice online.
def main():
endProgram = 'n'
print()
while endProgram == 'n':
total = 0
totalPlastic = 0
totalMetal= 0
totalGlass = 0
endCount = 'n'
while endCount == 'n':
print()
print('Enter 1 for Plastic')
print('Enter 2 for Metal')
print('Enter 3 for Glass')
option = int(input('Enter now: '))
if option == 1:
totalPlastic = getPlastic(totalPlastic)
elif option == 2:
totalMetal = getMetal(totalMetal)
elif option == 3:
totalGlass = getGlass(totalGlass)
else:
print('You have entered an invalid input')
return main()
endCount = input('Do you want to calculate the total? (y/n): ')
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
break
endProgram = input('Do you want to end the program? (y/n): ')
def getPlastic(totalPlastic):
plasticCount = int(input('Enter the number of Plastic bottles you have: '))
totalPlastic = totalPlastic + plasticCount * .03
return totalPlastic
def getMetal(totalMetal):
metalCount = int(input('Enter the number of Metal cans you have: '))
totalMetal = totalMetal + metalCount * .05
return totalMetal
def getGlass(totalGlass):
glassCount = int(input('Enter the number of Glass bottles you have: '))
totalGlass = (totalGlass + glassCount * .10)
return totalGlass
def calcTotal(totalPlastic, totalMetal, totalGlass):
total = totalPlastic + totalMetal + totalGlass
return total
def printNum(total):
print('Your total recyclable value is $', total)
main()
My problem is I run the code and it works fine for 99% of it. The program will ask any type and amount of bottle, and it totals it correctly too, the issue is that the outer loop never gets asked. After it prints the total it just goes right back to asking what type of bottle you have instead of asking you whether or not you want to end the program. Any help is appreciated thanks.
Remove the break just before Do you want to end the program? (y/n)
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
break
Here you are using break and the loop gets out and does not go forward.
break is used in while loop endProgram == 'n' and it breaks and never goes forwards.
One more thing it is a bad habbit of making defining first. Always define main after the other functions and do not just call main().
Use this -
if(__name__ == '__main__'):
main()
The break statement was exiting your script, therefore your line endProgram = input('Do you want to end the program? (y/n): ') was unreachable, that is why it was never "asked".
Also, fixed some of your indentation, give it a go.
def main():
endProgram = 'n'
print()
while endProgram == 'n':
total = 0
totalPlastic = 0
totalMetal = 0
totalGlass = 0
endCount = 'n'
while endCount == 'n':
print()
print('Enter 1 for Plastic')
print('Enter 2 for Metal')
print('Enter 3 for Glass')
option = int(input('Enter now: '))
if option == 1:
totalPlastic = getPlastic(totalPlastic)
elif option == 2:
totalMetal = getMetal(totalMetal)
elif option == 3:
totalGlass = getGlass(totalGlass)
else:
print('You have entered an invalid input')
return main()
endCount = input('Do you want to calculate the total? (y/n): ')
print()
total = calcTotal(totalPlastic, totalMetal, totalGlass)
printNum(total)
endProgram = input('Do you want to end the program? (y/n): ')
def getPlastic(totalPlastic):
plasticCount = int(input('Enter the number of Plastic bottles you have: '))
totalPlastic = totalPlastic + plasticCount * .03
return totalPlastic
def getMetal(totalMetal):
metalCount = int(input('Enter the number of Metal cans you have: '))
totalMetal = totalMetal + metalCount * .05
return totalMetal
def getGlass(totalGlass):
glassCount = int(input('Enter the number of Glass bottles you have: '))
totalGlass = (totalGlass + glassCount * .10)
return totalGlass
def calcTotal(totalPlastic, totalMetal, totalGlass):
total = totalPlastic + totalMetal + totalGlass
return total
def printNum(total):
print('Your total recyclable value is $', total)
main()
Related
I tried to make simple codes for supermarket checkout, but I have an issue with the while loop statement. Please check the code below and picture I sent.
I don't know why after I input "n", it does not go back to the loop.
def start():
quan = 1
price = 0
end = False
total = 0
while end == False:
food = (input("Enter your food: "))
quan = int(input("Enter quantative: "))
price = float(input("Price of food: "))
disscount = float(input("Do you have disscount? enter '0' for no disccount. "))
end = input("Finish? y or n: ")
sum = price * quan
sub_total = sum - (sum * disscount * 0.01)
total += sub_total
if end == "y":
print("Total price is ", total)
end = True
elif end == "n":
end = False
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
start()
The if again block needs to be indented:
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
Otherwise, you hit your if statement without necessarily having defined again. If it is not defined, you get the error you cite.
Ok so I am creating a program so that the user inputs their plane departure time
if the plane departure time is within 45 minutes of current (strftime) then they can procees to board
else, they are told how long until they can make way to gate
e.g. their plane leaves at 8.00 and current time is 7.00 (they cant board yet) so it says they have to wait for 15 minutes
bag = 0
minute = 0
array = []
f_row = ""
f_col = ""
name = ""
x = 0
from time import strftime
def weight():
global bag
print("Bag checking section")
print("")
bag = int(input("Enter weight of your bag: "))
if bag >= 23:
bag += 1
print("You need to pay £4 per extra KG")
print("New total to pay is: £",bag * 4)
elif bag > 0 and bag < 23:
print("Price: free")
else:
print("Try again")
def exchange():
print("Welcome to our exchange system")
print("")
money = float(input("How much money to exchange: £"))
print("1 for DOLLARS")
print("2 for RUPEE")
choice = input("Option: ")
if choice == "1":
print("£",money,"exchanged to $",round((money * 1.35)))
elif choice == "2":
print("£",money,"exchanged to ₹",round((money * 99.40)))
def boarding():
print("Check to see how long until you can board")
print("")
departure = input("Enter time of flight in 24h format: ")
hour = departure[0]+departure[1]
minute = departure[2]+departure[3]
print(hour,minute)
time = minute - 45
print(time)
def seats():
print("")
print("Choose your seats")
print(" ")
name = input("Enter name: ")
f_row = int(input("Enter row to sit in: "))
f_col = int(input("Enter column number: "))
grid = []
print("")
if array[f_row][f_col] != "empty":
print("Seat taken, try again")
elif array[f_row][f_col] == "empty":
array[f_row][f_col] = name
def make():
for x in range(10):
array.append([])
for y in range(7):
array[x].append("empty")
def show():
for row in range(10):
for col in range(7):
symbol = array[row][col]
print(symbol, end = " ")
print()
#main
while True:
print("")
print(strftime("%H:%M%p"))
print("")
print("1 to weigh bag")
print("2 for exchange")
print("3 for time until you can get on plane")
print("4 for choosing seat")
print("5 to exit program")
print("")
choice = input("Option: ")
print("")
if choice == "1":
weight()
elif choice == "4":
make()
show()
seats()
make()
show()
elif choice == "5":
break
elif choice == "2":
exchange()
elif choice == "3":
strftime("%H:%M%p")
print("")
boarding()
else:
print("Try again")
please note I have just started python and will not understand lots of complex code
if possible can it be reallt basic how to do this? thanks
So I ran into trouble with this code again with output. Basically, there are some key features I need it to print, but whenever I manage to get it to print one thing it completely messes up the rest of the printing. So for example, I need it to print Roll # 1 (1 - 3) was (whatever number) not Roll (whatever number) if that makes sense. But I also need it to only max out to 3 rolls. This is where my second issue comes in; whenever I try to code it to subtract the bet from the bank when a user doesn't match any rolls, it counts my subtraction as a fourth roll and screws up the math. So instead of Roll #1 through #3 its now up to Roll #4
My third problem is, I need to the program to continue looping until the user enters 0 (zero) to end the script or the bank amount reaches 0 (zero).
You should redesign your program. First of all, you are generating new results for each condition check at
if guess == rollDice():
bank = bet * 2
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
Your code is not properly indented.
[...]
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
else:
guess != rollDice()
bank = bank - bet
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
And so on...
Have a function that simulates a single dice roll, like:
def roll():
return random.randint(1, 6)
And handle the rest in your main function like:
prog_info()
while True: #main loop
rolls = list() #redefines after each loop
score = 2
for i in range(3): #3 dice roll
bank, bet = total_bank(bank)
guess = get_guess()
if not guess: #exit condition
break
rolls.append(roll())
if sum(rolls) == guess:
bank = bet * score
break #break on match
score = score - 0.5 #after each roll we have less money to win
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
A couple changes get the result you want
Pass the roll count to the rollDice function
Add an else to the bottom of the if block to check 0 bank
Here is the updated code:
import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def prog_info():
print("My Dice Game .v02")
print("You have three rolls of the dice to match a number you select.")
print("Good Luck!!")
print("---------------------------------------------------------------")
print(f'You will win 2 times your wager if you guess on the 1st roll.')
print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
print(f'You can win your wager if you guess on the 3rd roll.')
print("---------------------------------------------------------------")
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0':
print('Thanks for playing!')
exit()
bet = int(get_bet)
return bank,bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
while True:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * .5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet # no match
if bank == 0:
print('You have no money left. Thanks for playing!')
exit()
Output
You have $500 in your bank.
Enter your bet (or 0 to quit): 500
Choose a number between 2 and 12: 4
Roll # 1 was 11
Roll # 2 was 6
Roll # 3 was 7
You have no money left. Thanks for playing!
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')
I want to keep track of the variable TOTAL_TRI. TOTAL_TRI contains the number of correctly answered questions from the game. I need to save that value and pass it to the function statistics when statistics is called. Essentially, the player will play the game py_game, TOTAL_TRI will hold the number of questions they got right, and when the player calls the function statistics, it will display the number of questions they got right? I've been toying with this for a while with no significant progress. Any ideas?
P.S.
The other games in the menu are not yet implemented, but they'll do the same play-save correct number of questions-and let the player call to statistics kind of thing.
import random
from random import choice
from random import randint
#py_game------------------------------------------------------------------------
def py_game():
for k in range (1,3):
print('\nPractice Problem', k, 'of 2')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
else:
print("Sorry that's not the correct answer")
points = 0
for k in range (1,11):
print('\nProblem', k, 'of 10')
min_pyramid_size = 3
max_pyramid_size = 5
total_chars = 0
num_rows = random.randint(min_pyramid_size, max_pyramid_size)
for i in range(num_rows):
x = ''.join(str(random.choice('*%')) for j in range(2*i+1))
print(' ' * (num_rows - i) + x)
total_chars = total_chars + x.count('%')
try:
user_answer = int(input('Enter the number of % characters' + \
' in the pyramid: '))
except:
user_answer = print()
if user_answer == total_chars:
print('You are correct!')
points +=1
else:
print("Sorry that's not the correct answer")
TOTAL_TRI = points
#------------------------------------------------------------------------------
def statistics(points):
print('\nPyramid Game---------------------------')
incorrect = 10 - (points)
print ('You answered', points, 'questions correctly')
print ('You answered', incorrect, 'questions incorrectly')
#Main Menu--------------------------------------------------------------------------
def main_menu():
calculation_game = print("Enter 1 for the game 'Calculation'")
bin_reader = print("Enter 2 for the game 'Binary Reader'")
trifacto_game = print("Enter 3 for the game 'Trifacto'")
statistics = print("Enter 4 to view your statistics")
display_data = print("Enter 5 to display data")
save_game = print("Enter 5 to save your progress")
user_input = int(input('Make your selection: '))
if user_input == 1:
calculation()
if user_input == 2:
binary_reader()
if user_input == 3:
py_game()
if user_input == 4:
statistics(TOTAL_TRI)
if user_input == 5:
save_game()
if user_input != 1 or 2 or 3 or 4 or 5:
print('invalid input')
print('\n')
main_menu()
main_menu()
Using globals is code smell just waiting to happen. Pass your variable as an argument to your function. That's all.