Function is repeating when I don't want it to - python

The input function of my code is repeating 3 times before going onto the next function. I have tried using while true and break and return None but none of that helps.
def welcome():
print("Welcome to the Interest Loan Calculator")
def inp():
loan = input("Enter loan amount: ")
rate = input("Enter interest rate: ")
return loan, rate
def conv():
loan, rate=inp()
if loan.endswith('K'):
multiplier = 1000
loan = loan[0:len(loan)-1]
elif loan.endswith('M'):
multiplier = 1000000
loan = loan[0:len(loan)-1]
return int(float(loan) * multiplier)
def calc():
loan = conv()
print (loan)
def close():
print ("close placeholder")
def main():
welcome()
inp()
conv()
calc()
close()
if __name__ == "__main__":
main()
When running the code it asks me to input both loan and rate 3 times before moving to the calc function.

If you don't want to call inp three times, then don't. You call it once directly from the main program; you call it a second time through the sequence main => conv => inp, and a third time through main => calc => conv => inp.
I think you need to draw out the call tree of your program, and then alter it to match the design you actually want.

Related

not sure what exactly is wrong

I am new at python, probably as new as it gets. I am working on a simple python code for mpg and refactoring. I am not sure exactly what I am doing wrong. Its giving me a error on line 65, "in goodbye print("your miles per gallon:", mpg) name error name 'mpg' is not defined. any help would be appreciated.
def main():
miles_driven = 0.0
gallons_of_gas_used = 0.0
mpg = 0.0
print_welcome()
print_encouragement()
goodbye()
# imput
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
# Calculation
mpg = your_mpg(miles_driven, gallons_of_gas_used)
print("Your miles per gallon:", mpg)
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
def print_welcome():
print("Welcome to Ray's trip calculator!\n")
def print_encouragement():
print("Let's figure out your miles per gallon!")
def your_miles_driven():
your_miles_driven = 0.0
your_miles_driven = float(input("Enter number of miles driven:"))
return your_miles_driven
def gas_used():
gas_used = 0.0
gas_used = float(input("Enter the gallons of gas you used:"))
return gas_used
def your_mpg(your_miles_driven, gas_used):
mpg = 0.0
your_mpg = your_miles_driven / gas_used
return your_mpg
def goodbye():
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
print("Your miles per gallon:" , mpg)
main()
Your code has 2 problems.
the goodbye function needs to receive mpg as an argument
you need to do the inputs before calling goodbye(), and pass the function the mpg
the following lines of code should be before calling goodbye().
# input
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
Your code should look like this:
def main():
print_welcome()
print_encouragement()
# input before goodbye()
# input
miles_driven = your_miles_driven()
gallons_of_gas_used = gas_used()
# after input calc the mpg
# Calculation
mpg = your_mpg(miles_driven, gallons_of_gas_used)
# and then call the goodbye function and pass mpg
goodbye(mpg)
def print_welcome():
print("Welcome to Ray's trip calculator!\n")
def print_encouragement():
print("Let's figure out your miles per gallon!")
def your_miles_driven():
your_miles_driven = float(input("Enter number of miles driven:"))
return your_miles_driven
def gas_used():
gas_used = float(input("Enter the gallons of gas you used:"))
return gas_used
def your_mpg(your_miles_driven, gas_used):
your_mpg = your_miles_driven / gas_used
return your_mpg
# goodbye function also needs to receive mpg
def goodbye(mpg):
print("Your miles per gallon:", mpg)
print("\nThanks for using my mpg calculator, I will be adding additional functions soon!")
if __name__ == '__main__':
main()
mpg is defined in your main function and is not passed to your goodbye function. If you add it as a parameter, it becomes available in that function with whatever value is passed as an argument:
def goodbye(mpg):
print("\nThanks for using my mpg calculator, I will be adding additional "
"functions soon!")
print("Your miles per gallon:" , mpg)
Now in your main function you can do:
mpg = your_mpg(miles_driven, gallons_of_gas_used)
goodbye(mpg)
and goodbye() will receive the value of mpg that was returned by your_mpg().

How to ask for two inputs in Python?

# Profit and Loss
# Function to calculate Profit.
def Profit(costPrice, sellingPrice):
profit = (sellingPrice - costPrice)
return profit
# Function to calculate Loss.
def Loss(costPrice, sellingPrice):
Loss = (costPrice - sellingPrice)
return Loss
if __name__ == "__main__":
input(costPrice, sellingPrice)
if sellingPrice == costPrice:
print("No profit nor Loss")
elif sellingPrice > costPrice:
print(Profit(costPrice,
sellingPrice), "Profit")
else:
print(Loss(costPrice,
sellingPrice), "Loss")
The error code:
Traceback (most recent call last): File "C:/Users/sharv/PycharmProjects/FInal Robotic/Finals.py", line 18, in <module>
input(costPrice, sellingPrice) NameError: name 'costPrice' is not defined
Process finished with exit code 1
If you would like to input 2 values from the user, you will have to do it like that:
cost_price = input("Enter Cost Price: ")
sell_price = input("Enter Selling Price: ")
The input function in python takes as argument a string text to display to the user (An optional argument) and returns the inputed value from the user (as a str object). If you would like to convert those values into numbers, you will have to do something like:
# integer values
cost_price = int(input("Enter Cost Price: "))
sell_price = int(input("Enter Selling Price: "))
# OR:
# Floating point values
cost_price = float(input("Enter Cost Price: "))
sell_price = float(input("Enter Selling Price: "))
input(costPrice, sellingPrice)
Whoever told you input takes output variables as arguments is mistaken. If you want to input into the two variables, you'll do so as follows
costPrice = input()
sellingPrice = input()
You'll also likely want to convert them to numbers.
costPrice = float(input())
sellingPrice = float(input())

How to print a value in main function?

My goal is to:
take an input (until user enters 0) or quit (if a letter is entered),
run a few checks to throw out non-integers,
add those values to a list, and
then print the sum of list.
I'm trying to capture the boolean value for variable close in main but I'm getting an error.
Error: "close = addToList() TypeError: addToList() missing 1 required
positional argument: 'numberList'."
#function to create a list
def createList():
numberList = []
return numberList
#function to add integers from user to list
def addToList(numberList):
stopAdding = False
close = False
while stopAdding == False:
integerInput = input("Please enter a number [1-9] or '0' to stop: ")
if integerInput.isalpha():
badInput()
close = True
break
elif integerInput == '0':
stopAdding = True
else:
numberList.append(int(integerInput))
if close == True:
return close
else:
return numberList
#function for when invalid number entered
def badInput():
print("Invalid number entered.")
#function to sum the numbers in list
def sumList(numberList):
sumTotal = 0
for number in numberList:
sumTotal = sumTotal + number
return sumTotal
#function to print the list sum
def printSum(sumTotal):
print("The sum is: ", sumTotal)
#the main function
def main():
numberList = createList()
addToList(numberList)
sumTotal = sumList(numberList)
close = addToList()
if close == True:
pass
else:
printSum(sumTotal)
#call main
main()
What would be a better way to exit gracefully if a non-integer was entered? Thanks.
Change you main function to look like this;
def main():
numberList = createList()
close = addToList(numberList)
sumTotal = sumList(numberList)
if not close:
printSum(sumTotal)
Other things you can do to make your code cleaner is to remove the sumList function and just use the builtin sum function, and remove the createList since it really doesn't need to be it's own function. Then your main would look like this;
def main():
numberList = []
close = addToList(numberList)
if not close:
printSum(sum(sumTotal))
You forgot your argument in the second call:
close = addToList(sumTotal)
Thanks guys/gals.
I got rid of my if else at the end of addToList function and returned both close value and numberList value: return (close,numberList)
And then for main use builtin sum function:
close, numberList = addToList(numberList)
#the main function
def main():
numberList = createList()
close, numberList = addToList(numberList)
if not close:
printSum(sum(numberList))
Lastly, for throwing out all non-integer inputs entered, I used:
if not stringname.isdigit():
Works well now.

Why is my function paramter returning an error of not being defined

I'm new to functions, so I'm not quite sure how or why this is happening and I do not know how t fix it. Can someone explain why this error keeps occuring?
def loan_payment(l):
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost(i):
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost(g):
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost(m):
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost(l, i, g, m):
monthly_expenses = float(l + i + g + m)
print("You expend $"+format(monthly_expenses, '.2f')+" in a month.")
return float(monthly_expenses)
def yearly_cost(monthly_cost):
yearly_expenses = 12 * monthly_cost
print("At your current monthly expenses, in a year you will have paid $"+format(yearly_expenses, '.2f')+".")
return yearly_expenses
def main():
loan_payment(l)
insurance_cost(i)
gas_cost(g)
maitanence_cost(m)
monthly_cost(l, i, g, m)
yearly_cost(monthly_cost)
main()
This code returns the error:
line 24, in main
loan_payment(l) NameError: name 'l' is not defined
I think you may have gotten your wires a bit crossed on how python passes by assignment, you wouldn't be the first, and here's a great question to help, as well as how to assign values and defining methods. As best as I can tell, your main method should look more like:
def main():
l = user_in_loan_payment()
i = user_in_insurance_cost()
g = user_in_gas_cost()
m = user_in_maintanence_cost()
monthly_cost = calculate_monthly_cost(l, i, g, m)
yearly_cost = calculate_yearly_cost(monthly_cost)
I changed the method names to start with "calculate" or "user_in" to make it a little more readable.
That's exactly what the error says: l is not defined, like any other variable. If I get it right you are trying to enter values in first 4 functions and then use them in the next two functions for calculations.
If that's true, your code should be as following:
def loan_payment():
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost():
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost():
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost():
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost(l, i, g, m):
monthly_expenses = float(l + i + g + m)
print("You expend $"+format(monthly_expenses, '.2f')+" in a month.")
return float(monthly_expenses)
def yearly_cost(monthly_cost):
yearly_expenses = 12 * monthly_cost
print("At your current monthly expenses, in a year you will have paid $"+format(yearly_expenses, '.2f')+".")
return yearly_expenses
def main():
l = loan_payment()
i = insurance_cost()
g = gas_cost()
m = maitanence_cost()
mc = monthly_cost(l, i, g, m)
yearly_cost(mc)
main()

While Loop in function ( Python )

So I basically created my functions ( def main(), load(), calc(), and print().
But I do not know how I can allow the user to input the information as many times as he/she wants until they want to stop. Like I they input 5 times, it would also output 5 times. I have tried putting the while loop in the def main() function and the load function but it won't stop when I want it to. Can someone help? Thanks!
def load():
stock_name=input("Enter Stock Name:")
num_share=int(input("Enter Number of shares:"))
purchase=float(input("Enter Purchase Price:"))
selling_price=float(input("Enter selling price:"))
commission=float(input("Enter Commission:"))
return stock_name,num_share,purchase,selling_price,commission
def calc(num_share, purchase, selling_price, commission):
paid_stock = num_share * purchase
commission_purchase = paid_stock * commission
stock_sold = num_share * selling_price
commission_sale = stock_sold * commission
profit = (stock_sold - commission_sale) - ( paid_stock + commission_purchase)
return paid_stock, commission_purchase, stock_sold, commission_sale, profit
def Print(stock_name,paid_stock, commission_purchase, stock_sold, commission_sale, profit):
print("Stock Name:",stock_name)
print("Amount paid for the stock:\t$",format(paid_stock,'10,.2f'))
print("Commission paid on the purchase:$", format(commission_purchase,'10,.2f'))
print("Amount the stock sold for:\t$", format(stock_sold,'10,.2f'))
print("Commission paid on the sale:\t$", format(commission_sale,'10,.2f'))
print("Profit(or loss if negative):\t$", format(profit,'10,.2f'))
def main():
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
main()
You have to give the user some kind of way to declare their wish to stop the input. A very simple way for your code would be to include the whole body of the main() function in a while loop:
response = "y"
while response == "y":
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
response = input("Continue input? (y/n):")
an even simpler way would be two do the following....
while True:
<do body>
answer = input("press enter to quit ")
if not answer: break
alternatively
initialize a variable and avoid the inner if statement
sentinel = True
while sentinel:
<do body>
sentinel = input("Press enter to quit")
if enter is pressed sentinel is set to the empty str, which will evaluate to False ending the while loop.

Categories