How to get final grand total in a program? - python

This program will ask the user for the number of half-dollars, quarters, dimes, nickels, and pennies s/he has and then compute the total value. The total value of the change is shown both as the total number of cents and then as the separate number of dollars and cents. I want to include a final total that displays after the user is finished; which will display the total of all amounts entered throughout the session(i.e. all loop iterations). So how can I code this?
#getCoin function
def getCoin(coinType):
c = -1
while c < 0:
try:
c = int(input("How many " + coinType + " do you have? "))
if c < 0:
print("Coin counts cannot be negative. Please re-enter.")
except ValueError:
print("llegal input. Must be non-negative integer. Re-enter.")
c = -1
return c
print("Welcome to the Change Calculator")
print()
choice = input ("Do you have any change (y/n)?")
while choice.lower() == "y":
h = getCoin("Half-Dollars")
q = getCoin("Quarters")
d = getCoin("Dimes")
n = getCoin("Nickel")
p = getCoin("Pennies")
print()
TotalVal = (h*50) + (q*25) + (d*10) + (n*5) + p
print("You have " + str(TotalVal) + " cents.")
dollars = TotalVal // 100 # // is for division but only returns whole num
cents = TotalVal % 100 # % is for modulos and returns remainder of whole number
print("Which is " + str(dollars) + " dollars and " + str(cents) + " cents.")
choice = input("Do you have more change (y/n)? ")
print("Thanks for using the change calculator.")
finalTotal = TotalVal
print("You had a total of" + finalTotal + " cents.")
print("Which is" + str(finalTotalDollars) + " dollars and" + str(finalTotalCents) + " cents.")

To make it so when a user wants to play again, you could use an external file to write to and read from using open, read and write, to store user info.
You could use notepad as .txt and write user name, money, and repeat, so login checks and calls the money at the line after the name.

Related

How can I make a "list(range)" work when the quantity is not valid?

So, i'm new to python and trying to learn it, i've watched some clips on youtube and came up with this, but the last part to check in the quantity is or is not in the list range is not working....
print ("Hello, my name is Dave, welcome to our coffe shop!!")
name = input ("What is your name?\n")
print("Hello " + name + ", thank you for comming to our coffe shop!")
print ("What can i get you ?")
menu = str("caffe latte, " + "tea, " + "black coffe")
menu_choice = ["caffe latte","tea","black coffe"]
choice1 = input() # anything
print ("This is our menu:")
print (menu)
unavailable = True
# order loop for the coffe
while unavailable:
order = input ()
if order in menu_choice:
unavailable = False
print ("And how many " + order + " would you like?")
else:
print ("Sorry we dont have " + order + ", this is our menu :\n" + menu)
if order == "caffe latte":
price = 13
elif order == "tea":
price = 9
elif order == "black coffe":
price = 15
#quantity loop
list(range(1, 10))
#here is the problem i'm having RN, the part with if not in in list is skipped
choice_number = True
while choice_number:
quantity = input()
total = price * int(quantity)
if quantity not in {list} :
choice_number = False
if quantity == "1" :
print ("Alright " + name, "that will be " + str(total) +"$,", "a", order + " comming at you!")
elif quantity >= "2" :
print ("Alright " + name, "that will be " + str(total) +"$,", quantity + " " + order + " comming at you!")
else:
print ("Quantity invalid, please select a number from 1 to 10.")
Assign this list(range(1, 10)) in a variable like qty_lst = list(range(1, 10)).
or you can simnply write:
if quantity not in list(range(1, 10)):
quantity = input("Enter Quantity")
total = price * int(quantity)
if quantity not in range(1,10) :
print ("Quantity invalid, please select a number from 1 to 10.")
else:
if quantity == "1":
print("Alright " + name, "that will be " + str(total) + "$,", "a", order + " comming at you!")
elif quantity >= "2":
print("Alright " + name, "that will be " + str(total) + "$,", quantity + " " + order + " comming at you!")
I would recommend getting rid of the listed range and just doing it like this, also you don't need a while True loop its not really needed
if quantity < 1 or quantity > 10:
# not in range
else:
# in range
Dont use if ... in range(), i'm not sure about this, but i think that doing so, python will not know that the sequence is in order and will check your value against all the sequence.
If i'm wrong, let's say i learned something :D

how can i limit the user by letting him input a number only if higher than minimum_range?

import random
def input_range():
minimum_range = 5
users_range = input("set the maximum value for the range, minimum " + minimum_range + ":")
if int(users_range) > int(minimum_range):
print("The maximum range you selected is:", users_range)
else:
print("Out of range, try again")
random_number = random.randint(int(minimum_range), int(users_range))
print(random_number)
def name_user_request():
users_name = input("what's yor name? ")
print("Hi " + users_name + " nice to meet you")
input_range()
name_user_request()
this code i posted gives me an error if i input a number lower than minimum_range (in this case 5) any help would be great.
Thanks!
Try a recursion !!
import random
def input_range():
minimum_range = 5
users_range = input("set the maximum value for the range, minimum " + str(minimum_range) + ":")
if int(users_range) > int(minimum_range):
print("The maximum range you selected is:", users_range)
random_number = random.randint(int(minimum_range), int(users_range))
print(random_number)
return
else:
print("Out of range, try again")
input_range()
return
def name_user_request():
users_name = input("what's yor name? ")
print("Hi " + users_name + " nice to meet you")
input_range()
name_user_request()
You can use while loop to ask for a valid input over and over again (I changed other lines to use f-strings):
import random
def input_range():
minimum_range = 5
prompt = f"Set the maximum value for the range, minimum {minimum_range}: "
while (users_range := int(input(prompt))) < minimum_range:
print("Out of range, try again")
print(f"The maximum range you selected is: {users_range}")
random_number = random.randint(minimum_range, users_range)
print(random_number)
def name_user_request():
users_name = input("what's yor name? ")
print(f"Hi {users_name}, nice to meet you!")
input_range()
name_user_request()
Note that it uses "walrus" operator := (introduced in python 3.8). Without walrus operator, you can replace the while part with
users_range = int(input(prompt))
while users_range < minimum_range:
print("Out of range, try again")
users_range = int(input(prompt))

Loops in Python terminating Programm

I am new to coding and Python in general, and I can't figure this out.
I added loops so that the program does not terminate every time there is a typo, however I messed up something with the second loop presumably.
I think it might be connected to the whitespace, but I can't figure it out.
The Programm terminates after taking in the "calories_burned" variable.
def start():
print("""This is a Weight Calculator, please follow the instructions.""")
name = input("What is your name? ")
age = int(input("How old are you? "))
if 19 <= age <= 78:
height = float(input("How tall are you in cm? "))
current_weight = float(input("How much do you currently weigh? "))
goal_weight = float(input("How much do you want to weigh? "))
calories_consumed = int(input("How many calories did you consume today? "))
calories_burned = int(input("How many calories did you burn today? "))
def activity():
global rmr
activity_factor = input("Choose an activity factor: Sedentary, Lightly active, Moderately Active, Very Active ")
zif activity_factor == "sedentary":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.2))
if activity_factor == "lightly active":
rmr = int(round((10 * current_weight + 6.25 * height - 5 * age + 5) * 1.375))
if activity_factor == "moderately active":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.550))
if activity_factor == "very active":
rmr = int(round(((10 * current_weight) + (6.25 * height) - (5 * age) + 5) * 1.725))
else:
activity()
daily_deficit = int((rmr + calories_burned - calories_consumed))
print("Your daily deficit is: " + str(daily_deficit))
import numpy
mean_deficit = [daily_deficit]
calculation_mean_deficit = int(round(7500 / numpy.mean(mean_deficit)))
reach_goal = int(round((current_weight - goal_weight) * calculation_mean_deficit))
print(mean_deficit)
print(name + " it will take you " + str(calculation_mean_deficit) + " days to loose 1 kg.")
print(name + " it will take you " + str(reach_goal) + " days to reach your goal.")
choice = input("do you wish to continue Y/N?")
if choice == "n":
return
else:
start()
else:
print("Invalid age")
start()
start()
You don't call the activity() function anywhere in your code, so once the program collects the inputs it doesn't do anything else and exits.
Also it's "lose" not "loose"

(Basic?) File compiles fine, doesn't execute as intended

I'm running this on cygwin using atom as my editor. Python3.
Hi,
Basic Python question that really baffles me. I've looked around on SO and found a lot of questions regarding similiar issues, but can't find one that covers the issue I'm facing.
Before I go into details; this is an assignment that I'm working on so if you don't want to spill "all the beans", then just give me some sort of guidance.
I've been tasked with splitting a chat-bot into two files, one that handles the main() function and one that handles all the possible functions that the input-choices from main() uses.
For some reason both files compile fine, but when I call main.py
(either by >python main.py // // // // or by > ./main.py)
I get no prompt at all. Neither do I get a prompt while trying the same with marvin.py.
Both files are in the same directory.
This is main():
#!/usr/bin/env python3
import marvin
def main():
"""
This is the main method, I call it main by convention.
Its an eternal loop, until q is pressed.
It should check the choice done by the user and call a appropriate
function.
"""
while True:
menu()
choice = input("--> ")
if choice == "q":
print("Bye, bye - and welcome back anytime!")
return
elif choice == "1":
myNameIs()
elif choice == "2":
yearsToSec()
elif choice == "3":
weightOnMoon()
elif choice == "4":
minsToHours()
elif choice == "5":
celToFahr()
elif choice == "6":
multiplyWord()
elif choice == "7":
randNumber()
elif choice == "8":
sumAndAverage()
elif choice == "9":
gradeFromPoints()
elif choice == "10":
areaFromRadius()
elif choice == "11":
calcHypotenuse()
elif choice == "12":
checkNumber()
else:
print("That is not a valid choice. You can only choose from the menu.")
input("\nPress enter to continue...")
if __name__ == "__main__":
main()
As you can see I do import marvin after the environment-variables have been loaded.
There are no indentation errors or anything else when compiling either files (as mentioned above).
Disclaimer: I don't think you need to read marvin, tbh...
And this is marvin.py:
#!/usr/bin/env python3
from random import randint
import math
def meImage():
"""
Store my ascii image in a separat variabel as a raw string
"""
return r"""
_______
_/ \_
/ | | \
/ |__ __| \
|__/((o| |o))\__|
| | | |
|\ |_| /|
| \ / |
\| / ___ \ |/
\ | / _ \ | /
\_________/
_|_____|_
____|_________|____
/ \
"""
def menu():
"""
Display the menu with the options that Marvin can do.
"""
print(chr(27) + "[2J" + chr(27) + "[;H")
print(meImage())
print("Welcome.\nMy name is Ragnar.\nWhat can I do for you?\n")
print("1) Present yourself to Ragnar.")
print("2) Have Ragnar calculate your minimum age (in seconds).")
print("3) Have Ragnar calculate weight on the moon.")
print("4) Try Ragnar's abilities by having him calculate minutes to hour(s).")
print("5) Have Ragnar calculate Fahrenheit from Celcius.")
print("6) See if Ragnar can multiply a word of your liking by a factor of your choice.")
print("7) Have Ragnar print 10 numbers within a range of your choice.")
print("8) Keep entering numbers and have Ragnar print their sum and average.")
print("9) Let Ragnar calculate your grade by entering your score!.")
print("10) Let Ragnar calculate the area of a circle with the radius of your choice.")
print("11) Let Ragnar calculate the hypotenuse of a triangle with the sides of your choice.")
print("12) Have Ragnar compare a given number to your previous number.")
print("q) Quit.")
def myNameIs():
"""
Read the users name and say hello to Marvin.
"""
name = input("What is your name? ")
print("\nMarvin says:\n")
print("Hello %s - your awesomeness!" % name)
print("What can I do you for?!")
def yearsToSec():
"""
Calculate your age (years) to seconds
"""
years = input("How many years are you?\n")
seconds = int(years) * (365 * 24 * 60 * 60)
print(str(years) + " would give you " + str(seconds) + " seconds.")
return
def weightOnMoon():
"""
Calculate your weight on the moon
"""
weight = input("What is your weight (in kiloes)?\n")
moonGrav = float(weight) * .2
print(str(weight) + " kiloes would weigh be the same as " + str(moonGrav) + " kiloes on the moon.")
def minsToHours():
"""
Calculate hours from minutes
"""
minutes = input("How many minutes would you want to converted to hour(s)?\n")
hours = float(format(float(minutes) / 60, '.2f'))
print(str(minutes) + " hours is " + str(hours) + " hours")
def celToFahr():
"""
Calculate celcius to Fahrenheit
"""
cel = input("Please insert Celcius to be calculated to Fahrenheit.\n")
fah = float(format(float(cel) * 1.8 + 32, '.2f'))
print(str(cel) + " is " + str(fah) + " in Fahrenheit units.")
def multiplyWord():
"""
Multiply word n-times
"""
word = input("Please enter the word.\n")
factor = input("And please give me the product to multiply it by!")
word *= int(factor)
print("The word is:\n" + str(word))
def randNumber():
"""
Adds 10 random numbers (depending on user range)
to a string.
"""
rangeMin = input("What is the lower number in your range?\n")
rangeMax = input("What is the higher number in your range?\n")
sequence = ""
for num in range(0, 10):
sequence += str(randint(int(rangeMin), int(rangeMax))) + ", "
num = num
print("The random sequence is:\n" + sequence[:-2])
def sumAndAverage():
"""
Adds numbers to the sum and calculate the average value of the input(s)
"""
summa = 0
count = 0
temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n")
while True:
if temp == "q":
print("The sum of your numbers are: " + str(summa) + "\nAnd the average is: " + str(summa/count))
return
else:
try:
summa += int(temp)
count += 1
temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n")
except ValueError:
print("That's not an int! \nPlease try again!")
def gradeFromPoints():
"""
Shows the user's grade based on his / her points
"""
points = input("How many points did you score?\n")
if(float(points) >= 1 and float(points) <= 100):
points = float(points) / 100
if float(points) >= 0.9:
print("You got an A!")
elif float(points) >= 0.8 and float(points) < 0.9:
print("You got a B!")
elif float(points) >= 0.7 and float(points) < 0.8:
print("You got a C!")
elif float(points) >= 0.6 and float(points) < 0.7:
print("You got a D!")
else:
print("You failed the class")
def areaFromRadius():
"""
Calculates a circles area based on it's radius
"""
radius = input("What is the circle's radius?\n")
area = (float(radius) * float(radius)) * 3.1416
print("The area of the circle is: " + str(format(area, '.2f')))
print("This was calculated with this formula: (radius^2) * 3.1416")
def calcHypotenuse():
"""
Calculates a triangle's hypotenuse based on it's sides
"""
side1 = input("How long is the first side?\n")
side2 = input("How long is the second side?\n")
hypotenuse = math.sqrt((float(side1) * float(side1)) + (float(side2) * float(side2)))
print("The hypotenuse is: " + str(hypotenuse))
def compareNumbers(a, b):
"""
Compares two numbers
"""
if (a > b):
print("Your previous number was larger!")
return a
elif (a < b):
print("Your new number was larger!")
return b
else:
print("They were equal!")
return a
def validateInt(a):
"""
Validates that an input is an integer
"""
if a == 'q':
return a
else:
flag = False
while (flag == False):
try:
a = int(a)
flag = True
except ValueError:
print("That's not an int! \nPlease try again!")
a = input("Try again!\n")
return a
def checkNumber(prev="first"):
"""
Checks the number
"""
print("\n=================\n")
if prev == "first":
prev = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
print("\n=================\n")
new = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
if new == 'q' or prev == 'q':
print("You have exited the loop\n")
return
else:
compareNumbers(int(prev), int(new))
checkNumber(str(new))
else:
new = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
if new == 'q':
print("You have exited the loop!\n")
return
else:
compareNumbers(int(prev), int(new))
checkNumber(str(new))
FULL DISCLAIMER: I'm sure there are bunches of improvments I can do,
but I'm only interested in understanding why the files won't execute
even though they compile fine...
if __name__ == "__main__":
main()
should not be indented.
In your current code, the main() method is run in the else block, but you never get there because the program won't start because you just define the main() method but never execute it.
Unindent it and it will be executed as it won't be in a function definition anymore.
The functions defined in marvin.py are not globals in main.py; they are members of the marvin module object. So, this:
elif choice == "1": myNameIs()
should be changed to this:
elif choice == "1": marvin.myNameIs()
The same goes for the rest of the places where main.py is using functions from marvin.py.

Truncating ints without rounding?

I made this program that takes change and figures out how many full dollars, and leftover change. The way it is setup, it takes the amount of change, 495 for example, and then converts it to dollars, 4.95. Now I want to cut off the .95 and leave the 4, how do I do this without it rounding up to 5? Thanks!
def main():
pennies = int(input("Enter pennies : "))
nickels = int(input("Enter nickels : "))
dimes = int(input("Enter dimes : "))
quarters = int(input("Enter quarters : "))
computeValue(pennies, nickels, dimes, quarters)
def computeValue(p,n,d,q):
print("You entered : ")
print("\tPennies : " , p)
print("\tNickels : " , n)
print("\tDimes : " , d)
print("\tQuarters : " , q)
totalCents = p + n*5 + d*10 + q*25
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
print("Amount of Change = ", totalDollarsTrunc, "dollars and ", totalPennies ,"cents.")
if totalCents < 100:
print("Amount not = to $1")
elif totalCents == 100:
print("You have exactly $1.")
elif totalCents >100:
print("Amount not = to $1")
else:
print("Error")
In Python, int() truncates when converting from float:
>>> int(4.95)
4
That said, you can rewrite
totalDollars = totalCents / 100
totalDollarsTrunc = int(format(totalDollars, '.0f'))
totalPennies = totalCents - (totalDollarsTrunc * 100)
using the divmod function:
totalDollars, totalPennies = divmod(totalCents, 100)
You probably want to use math.ceil or math.floor to give you the rounding in the direction that you want.
Function int() will do just that

Categories