Creating Testcases for python Calculator - python

The Calculator is suppose to determine an equal amount for each guest to pay for the total bill
My code:
Total_Bill_Value=int(input("Enter your total cost of the Bill : "))
#Requests user to input the value of their bill
Num_of_Guests=int(input("Enter the total number of Guests : "))
#Requests users to input number of guests
Calc_Tip=(Total_Bill_Value/100)*15
#Calculates 15% of the bill as tip
Total=Total_Bill_Value+Calc_Tip
#total of the bill including tip
Total_Tip=Calc_Tip/Num_of_Guests
#Splits the tip equaly among all guests
Total_Pay=Total/Num_of_Guests
#Splits the total bill equaly among all guests
def main ():
print("The Tip(15% of bill) is =${}".format(Calc_Tip))
print("The Total cost of bill including Tip is = ${}".format(Total))
print("Required amount from each Guest for the Tip is:")
for i in range(1,Num_of_Guests+1):
print("Guest{} =${:.2f}".format(i,Total_Tip))
print("Required amount from each Guest for the Total bill is:")
for i in range(1,Num_of_Guests+1):
print("Guest{} =${:.2f}".format(i,Total_Pay))
if __name__ == '__main__':
main()
I need to create testcases but not entirely sure how to entirely do so everytime i run this code to test if it works or not it says the test failed and it also is requiring me to input the values aswell
TestCase code:
import unittest
import BillCalc
class Test(unittest.TestCase):
def test2(self): #it checks the main method
self.assertEqual(3.75, BillCalc.Total_Tip(100,4))
if __name__ == '__main__':
unittest.main()

It isn't working because the Total_tip variable is obtained as a result of other variables, that get values from user input. Just using a variable with brackets doesn't communicate the variable those values (to execute). Unless that variable has a function assigned, therefore you must store the most BillCalc inside a function, here's a sample:
def calculate(total_bill, guests_no):
Calc_Tip=(total_bill/100)*15
#Calculates 15% of the bill as tip
Total_Tip=Calc_Tip/guests_no
#Splits the tip equaly among all guests
return Total_Tip
And in the test file:
def test2(self): #it checks the main method
self.assertEqual(3.75, BillCalc.calculate(100,4))

Your test fails because you're running a test on a float as if it was a function. Total_Tip is not a function with the parameters (Calc_Tip,Num_of_Guest) but a float variable that stores the result for (Calc_Tip/Num_of_Guests).
For Total_Tip to pass the test it should look something like:
def Total_Tip(Total_Bill_Value, Num_of_Guests):
Calc_Tip = (Total_Bill_Value / 100) * 15
return Calc_Tip/Num_of_Guests

Related

Add more values in a list at once in Python

I'm a beginner in Python and I'm trying to solve this problem.
I'm trying to write a code where you can put your name and the amount that you want to donate.
The thing is, deppending on the amount of the donation you can have more chances to be the winner.
Eg. If you donate $10 (1 chance), $20(2 chances), $30(3 chances).
My biggest problem is because I can't figure out how to solve this problem when the person insert $30 its name goes to the list 3 times and so on. I tried to use "for..inrange():" but without any sucess. Can someone explain me how to do this?
from random import shuffle
from random import choice
list = []
while True:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
list.append(name)
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 1:
continue
else:
shuffle(list)
winner = choice(list)
break
print('The winner was: {}' .format(winner))
First do not use the name of a built-in type as a (meaningless) variable name. Change list to entry_list.
For the particular problem
compute the quantity of chances;
make a list of the person's name that many times;
extend the entry list with that list of repeated name.
Code:
entry_list = []
while ...
...
chances = int(donation) // 10
entry_list.extend( [name] * chances )
An alternative to adding another loop with additional control flow, you can use list.extend() with a list expression:
num_chances = donation // 10
chances = [name] * num_chances
all_chances.extend(chances)
Note that list is a built-in python identifier, and it's not a good idea to overwrite it. I've used all_chances instead.
Rather than adding extra names to the list to represent the higher chance, you could use the donations as weights in the random.choices function:
from random import choices
names, donations = [], []
while True:
names.append(input('Write your name: '))
donations.append(float(input('Enter the amount you want to donate.: $')))
print(f'You donated ${donations[-1]}. Thank you {names[-1]} for your donation!')
print('=-'*25)
print('[1] YES')
print('[2] NO')
if input('Would you like to make another donation? ') != '1':
break
winner = choices(names, donations)[0]
print(f'The winner was: {winner}')
This allows for non-integer donations to be counted fairly -- e.g. if Bob donates $0.25 and Fred donates $0.50, the drawing will still work in a reasonable way. It also allows very large donations to be handled without tanking the performance of the program -- if you have one list entry per dollar donated, what happens if Elon donates $20B and Jeff donates $30B? (The answer is that your fan spins really fast for a while and then the program crashes because you can't create a list with 50 billion elements -- but this is not a problem if you simply have a list of two elements with large int values.)
Note that shuffle is not necessary if you're using random.choices (or random.choice for that matter) because those functions will already make a random selection from the list.
You can use a for loop to append the name to the list more than one time :
for i in range(donation//10):
list.append(name)
This code should do the job. Please follow good naming conventions as pointed out by others. I have changed the list variable to donations as it is forbidden to use keywords as variables.
I have included the name in donations int(name) // 10 times using the extend function as pointed out by others. You may change the number of times as you wish.
from random import shuffle
from random import choice
donations = []
makeDonation = True
winner = "Unknown"
while makeDonation:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
donations.extend([name for i in range ( int(donation) // 10)])
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 2:
makeDonation = False
shuffle(donations)
winner = choice(donations)
print('The winner was: {}' .format(winner))

Printing, in a later function, the value returned in an earlier function

I've defined a function. I want that function to return a value. Then, later on in the script, I want to print that returned value inside of another defined function.
When I try to do this, I get the following error:
NameError: name 'variable_name' is not defined.
Here's the defined function:
def get_number_of_purchased_items():
item_quantity = input("Enter quantity purchased: ")
item_quantity = int(item_quantity)
return item_quantity
And here, later on in the script, is where I want to print "item_quantity":
def main():
print("Number of purchased items: ", item_quantity).
A little more information, in case it helps:
The above is one part of my overall script. I'm defining several functions -- to get input from the user on (a) the type of item they want to purchase, (b) the number of items they purchase, (c) the price per unit, and (d) the tax rate.
Then I've created three functions that take arguments, based on the returned values of the four above functions, to calculate (a) the subtotal, (b) the tax, and (c) the total cost.
Then I'm sticking all of these functions inside another function, main(), which, when printed, acts as a sales receipt -- see below. (I've included the "item_quantity" value I want returned, the one which results in a NameError.)
def main():
get_retail_item_description()
get_number_of_purchased_items()
get_price_per_unit()
get_tax_rate()
print("Sales receipt: ")
print("Number of purchased items: ", item_quantity)
print("Unit price: ", )
print("Tax Rate: ", )
print("Subtotal: ", )
print("Tax: ", )
print("Total: ", )
Thanks for your patience and support on this.
The problem is, you use return, but do not declare a variable to hold it.
item_quantity is a variable in the function, therefore main do not know what it is. You have two ways:
item_quantity = get_number_of_purchased_items()
or:
print("Number of purchased items: ", get_number_of_purchased_items())
But #2 will be awkward, so I suggest to go with #1.
Replace item_quantity with get_number_of_purchased_items().

Trying to figure out how to pass the function so then it can display the values

# Main to run
def main():
keyboardInput = int(input('Enter the price of the land: $')) # grab user input
calculate(keyboardInput) # function to calculate w/ kbInput parameter
display(assessmentValue, realTax) # display the values <- this one right here
# Calculate the assessment value and property tax. Display afterwards
def calculate(keyboardInput):
assesssmentValue = keyboardInput * 0.60 # 60% for property actual value
realTax = (assesssmentValue * .64) / 100 # calculate the tax
return assesssmentValue, realTax
# Display the prices
def display(assesssmentValue, realTax):
print('The assessment value is : $', format(assesssmentValue, '.2f'))
print('The property tax is: $', format(realTax, '.2f'))
# ^ display the values
# Call the main to run
main()
Overall things I've done so far:
tried to make variables for them, but I am also trying to figure out also how to grab the returning values from calculate function, if that was doable.
delete and revise the code, it works the method I tried, but I want to learn on this portion with which im stuck with.
everything so far from what I've seen works besides the option to display the function for additional info and context
Issue: display the "display" function from the main method
ps. sorry for the bad formatting of my post, new to here
EDIT: fixed typo in code
Just assign the value from the calculate() call to your variables, on the outside.
def main():
keyboardInput = int(input('Enter the price of the land: $'))
assesssmentValue, realTax = calculate(keyboardInput)
display(assesssmentValue, realTax)

How do you use a loop for a function?

I have written most of the codes already, but I am still having a hard time figuring out the code to loop the program (for a function) as many times the user desires until the user is done. Also, I am unable to use a For loop.
def load():
a=input("Name of the stock: ")
b=int(input("Number of shares Joe bought: "))
c=float(input("Stock purchase price: $"))
d=float(input("Stock selling price: $"))
e=float(input("Broker commission: "))
return a,b,c,d,e
def calc(b,c,d,e):
w=b*c
x=c*(e/100)
y=b*d
z=d*(e/100)
pl=(x+z)-(y-z)
return w,x,y,z,pl
def output(a,w,x,y,z,pl):
print("The Name of the Stock: ",a)
print("The amount of money Joe paid for the stock: $",format(w,'.2f'))
print("The amount of commission Joe paid his broker when he bought the stock: $",format(x,'.2f'))
print("The amount that Jim sold the stock for: $",format(y,'.2f'))
print("The amount of commission Joe paid his broker when he sold the stock: $",format(z,'.2f'))
print("The amount of money made or lost: $",format(pl,'.2f'))
def main():
a,b,c,d,e=load()
w,x,y,z,pl=calc(b,c,d,e)
output(a,w,x,y,z,pl)
main()
To let the user decide if they want to keep looping and not any fixed number of times, ask the user:
# in place of the call to main() above, put:
while input('Proceed? ') == 'y':
main()
So it keeps looping over main() as long as the user enters 'y'. You can change it to 'yes', 'Yes', etc. as needed.
Side note:
1. You should use more than 1 space for indent. Typically 4 spaces, or at least 2.
2. read up on if __name__ == "__main__".
Calling a function in a loop is fairly simple, you wrap in either in a while or a for loop and call it inside. The below code executes the brookerage function 10 times. I suppose you can use this as an example and customize the entire thing for your needs.
def brookerage():
a,b,c,d,e=load()
w,x,y,z,pl=calc(b,c,d,e)
output(a,w,x,y,z,pl)
def main():
for i in range(0,10):
brookerage()
main()

Coin-counting game for making change [duplicate]

This question already has answers here:
Assigning variables from inputs in FOR loop in python
(2 answers)
Closed 9 years ago.
I'm doing a Python programming course and I've been trying to wrap my head around how I can make it happen. I've written some code and I'm trying to fix any errors that pop up but I'm getting confused and not solving anything which is why I turn to you guys. I would appreciate any ideas and suggestions that pop up when you see what I've managed to write so far. I'm especially having trouble figuring out how to do the last part where I have to get the value that is above or below $2.
I'm doing this exercise:
Create a change-counting game that gets the user to enter the number of coins necessary to make exactly two dollars. Implement a Python program that prompts the user to enter a number of 5c coins, 10c coins, 20c coins, 50c coins, $1 coins and $2 coins. If the total value of those coins entered is equal to two dollars, then the program should congratulate the user for winning the game. Otherwise the program should display a message advising that the total was NOT exactly two dollars, and showing how much the value was above or below two dollars.
Update: I made a few changes to the last function and it worked perfectly fine.
#Global Variables
v_five = float(0.05)
v_ten = float(0.10)
v_twenty = float(0.20)
v_fifty = float(0.50)
v_one_dollar = int(1)
v_two_dollar = int(2)
dollar = 0
def main():
"""The main function defines the variables that are needed by taking input
from the user. The main() function is calling all the other functions one
by one to execute their intended commands and give the results"""
intro() #Displays the rules of the game
#Takes input from the user. One input per denomination
five=float(input(" Enter number of FIVE CENT coins: "))
ten=float(input(" Enter number of TEN CENT coins: "))
twenty=float(input(" Enter number of TWNETY CENT coins: "))
fifty=float(input(" Enter the number of FIFTY CENT coins: "))
one_dollar=int(input(" Enter the number of ONE DOLLAR coins: "))
two_dollar=int(input(" Enter the number of TWO DOLLAR coins: "))
#Shows what the user entered
show_change(five,ten,twenty,fifty,one_dollar,two_dollar)
#Converts the value of the total into dollars and cents from
#what the user has entered
calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar)
#Calculates and Prints the total along with what the final number
#was
#CalculateAndPrint(five,ten,twenty,fifty,one_dollar,two_dollar)
CalculateAndPrint(dollar)
def intro():
"""This function simply prints out the instructions for the user"""
print("")
print(" Welcome to the Coin Change game!")
print(" Enter a number for each denomination below")
print(" Your total should be $2 and no more.")
print(" Good Luck!\n")
def show_change(five,ten,twenty,fifty,one_dollar,two_dollar):
"""This function shows what the user has entered after taking input from
the user"""
print("")
print(" You entered: \n\n {} five cent(s) \n {} ten cent(s) \n {} twenty cent(s) \n {} fifty cent(s) \n {} one dollar \n {} two dollar coins".format(five,ten,twenty,fifty,one_dollar,two_dollar))
def calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar):
"""This function will convert the entered values into cents so that they
can be calculated and checked if they exceed the $2 amount."""
fiveAmount = v_five * five
tenAmount = v_ten * ten
twentyAmount = v_twenty * twenty
fiftyAmount = v_fifty * fifty
oneAmount = v_one_dollar * one_dollar
twoAmount = v_two_dollar * two_dollar
global dollar
dollar = fiveAmount + tenAmount + twentyAmount + fiftyAmount + oneAmount + twoAmount
"""This function checks whether the total was over or under $2 and displays a
win or loose message for the user. Also shows the total that the user entered"""
def CalculateAndPrint(dollar):
if dollar == 2.00:#Checks if the dollar value being passed from the previous function
#is 2 or not
print(" \n Congratulations! You've hit a perfect 2!")
print("")
else:
if dollar < 2.00:
print(" \n Oops! You were a little under 2!")
print("")
print(" Your total was: ", dollar)
else:
if dollar > 2.00:
print(" \n Oh no! You went over 2!")
print("")
print(" Your total was: ",dollar)
main()
well, actually there're a couple of errors:
the function calculate_value does return a value but it's not assigned at all
return_dollar = calculate_value(five,ten,twenty,fifty,one_dollar,two_dollar)
and you have to pass that value to CalculateAndPrint.
CalculateAndPrint(return_dollar)
you have also to change the definition of CalculateAndPrint:
def CalculateAndPrint(dollar):
i don't have python 3.0 installed on this PC so i cannot test all your program, but those are two problem i can see right now.
Just as a matter of style, why don't you put all your coins in a list:
coin_list = [five, ten, twenty, fifty, one_dollar, two_dollar]
show_change(coin_list)
calculate_value(coin_list)
CalculateAndPrint(coin_list)
Note: you'll need to change the def's of the above functions.

Categories