How do you use a loop for a function? - python

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()

Related

in range loop skipping through

salary=0
salaryArray=[]
loop=0
noYears=int(input("How many years do you want to do salaries for? "))
for i in range(0,noYears):
while loop==0:
print()
print("You can add multiple sources of income, one at a time")
salaryType=input("Do you want to put in your salary hourly or yearly? (h/y) ")
if salaryType=="y":
salarySection=float(input("What is your salary? "))
salary=salarySection+salary
else:
salaryHourly=float(input("What are you payed per hour? "))
salaryWeekly=float(input("How many hours per week will you work? "))
salaryYearly=float(input("How many weeks per year will you work? "))
print()
salarySection=salaryHourly*salaryWeekly*salaryYearly
salary=salary+salarySection
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
loop=1
For some reason the for i in range(0,noYears) isn't working?
It just moves on to the next line of code after doing it through once - even though I put the answer to noYears as 3.
Anyone know why this might be as I cannot see what is wrong?
:)
The code isn't working because the while loop never executes. You could solve this two ways.
Use a break statement instead of setting loop to 1:
#previous code
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
break
Reset the variable loop to 0 inside of the for loop:
for i in range(0,noYears):
loop = 0
while loop==0:
# remaining code

Creating Testcases for python Calculator

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

I'm writing a fuel conversion program and its not working :(

I am a novice python code writer and i am starting small with a fuel conversion program. The program asks for your name and then converts a miles per gallon rate or a kilometers per litre rate. Currently, the program runs fine until it gets to the convert to MPG line. then once you press y, it does nothing. funny thing is, no syntax error has been returned. please help as i cannot find anything on it :(
import time
y = 'y', 'yes', 'yep', 'yea', 'ye'
n = 'n', 'no', 'nup', 'nay'
name = str(input("Hey, User, whats your name? "))
time.sleep(1.5)
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
time.sleep(1.5)
str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if y is True:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = (galls/miles)
print("The MPG Rate is: ", int(mpgc))
time.sleep(2)
print("test print")
if y is (not True):
input(str("Would you like to convert KPL instead? (y/n): "))
time.sleep(1.5)
if y is True:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = ( litres / kilometers )
print("The KPL Rate is: ", int(kplc))
time.sleep(3)
exit()
if y is not True:
print("No worries")
time.sleep(1.5)
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
time.sleep(1.5)
print("Have a good day!")
time.sleep(1.5)
exit()
else :
print("Sorry, invalid response. Try again")
exit()
elif not y:
print("Please use y/n to answer" )
time.sleep(2)
elif not n:
print("Please use y/n to answer" )
time.sleep(2)
sorry if you think that is bad but i just started python and i need some help :)
Severely trimmed down and indentation fixed (I think....)
if y is True and similarly if y is not True make no sense here.
Also, speaking of is.. is and == may be work as equivalent expressions sometimes for checking for "equality", but not necessarily. == checks for equality whereas is checks for object identity. You should use == for checking for equality between two objects. Except for None in which case it's generally preferred to use is instead of == for this.
You're converting to str in a bunch of places unnecessarily. They're already strings.
In your mpg conversion you already have a floating point number (possibly an int). There's no need to convert to an int here. Suppose mpg is < 1. Then int casting will make this return zero
Your math is also backwards. miles per gallon. Similarly, kilometers per gallon.
name = input("Hey, User, whats your name? ")
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
mpg = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if mpg in y:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = miles / galls
print("The MPG Rate is: ", mpgc)
else:
kpl = input("Would you like to convert KPL instead? (y/n): ")
if kpl in y:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = kilometers / litres
print("The KPL Rate is: ", kplc)
else:
print("No worries")
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
print("Have a good day!")
The is keyword in python checks if two variables point to the same location in memory. y will never point to the same memory location as the singleton True because it's value is a string. I suspect what you mean to do is something like
inp = str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if inp in y:
...
You cannot directly take y as pressed from the keyboard, you have to take it as an input(Pressing enter would be required), store it, check if it satisfies the conditions, then apply the logic.
I see you tried to define y and n as a tuple (deliberately or not), In that case I assume you also want to take those other words as yes or or too.
In that case you can apply this logic;
inp = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if inp in y: # Check if inp corresponds any of the words defined in y
# Things to do if `yes` or anything similar entered.
Some notes:
You don't need to use str() after you take input if you are using
Python3 (Which seems you are). Because input() returns string.
In somewhere you did something like this:
input(str("Would you like to convert KPL instead? (y/n): "))
Which is even more reduntant because the value you entered is already
a string.
You also didn't assign some inputs to any variable throughout the
code. You should assign them If you are to use them later.
Please take care of these issues.

Python car sales code issue

Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))

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