How can I fix the inputs? Because they do not show up when I run my program.
## Define the main module
def main():
## Initialize local Variables / Set Constant
homeValue = 0
propertyTaxRate = 0
bedrooms = 0
BEDROOMSURCHARGERATE = 0.0025
## Set initialized varialbes to user inputs
homeValue = float(input("How much is your home worth?"))
propertyTaxRate = float(input("What is your Property Tax Rate entered as a decimal?"))
bedrooms = int(input("How many bedrooms will your house have?"))
## Set Variables equal to results of module outputs
propertyTax = getPropertyTax(homeValue, propertyTaxRate)
bedroomSurcharge = getBedroomSurcharge(BEDROOMSURCHARGERATE, bedrooms, homeValue)
totalPropertyTax = getTotalPropertyTax(propertyTax, bedroomSurcharge)
## Report All information with a propertyTaxReport
propertyTaxReport(homeValue, propertyTaxRate, bedrooms, propertyTax, bedroomSurcharge, totalPropertyTax)
## Define getPropertyTax Module
def getPropertyTax(homeValue, propertyTaxRate):
## Calculate property tax
propertyTax = homeValue*propertyTaxRate
return propertyTax
## Define getBedroomSurcharge
def getBedroomSurcharge(BEDROOMSURCHARGERATE, bedrooms, homeValue):
## Calculate Bedroom Surcharge
bedroomSurcharge = BEDROOMSURCHARGERATE*bedrooms*homeValue
return bedroomSurcharge
## Define getTotalPropertyTax
def getTotalPropertyTax(propertyTax, bedroomSurcharge):
## Calculate totalProperty Tax
totalPropertyTax = propertyTax + bedroomSurcharge
return totalPropertyTax
## Define propertyTaxReport
def propertyTaxReport(homeValue, propertyTaxRate, bedrooms, propertyTax, bedroomSurcharge, totalPropertyTax):
## Output Variables
print("Your home costs ", homeValue, " dollars.")
print("Your property tax rate is ", propertyTaxRate)
print("Your house has ", bedrooms, "bedrooms")
print("Your property tax is equal to ", propertyTax, " dollars.")
print("Your bedroom surcharge is equal to ", bedroomSurchage, " dollars")
print("Your total property tax comes out to ", totalPropertyTax, " dollars")
return
I think you are drying a bit with your code.
A few suggestions:
You do not need to initialise a variable if this is an input from the user.
If you can simplify a calculation, just do it. Do not create many functions if they are not necessary.
You do not to print as output variables that the user gives as input. I guess the user already knows that. But if it is a serious report, maybe I can give you that.
Try this and let me know:
def main_function():
BEDROOMSURCHARGERATE = 0.0025
## Set initialized variables to user inputs
homeValue = float(input("How much is your home worth?"))
propertyTaxRate = float(input("What is your Property Tax Rate entered as a decimal?"))
bedrooms = int(input("How many bedrooms will your house have?"))
## Set Variables equal to results of module outputs
propertyTax = homeValue*propertyTaxRate
bedroomSurcharge = BEDROOMSURCHARGERATE*bedrooms*homeValue
totalPropertyTax = propertyTax + bedroomSurcharge
## Report all information with a propertyTaxReport
return (totalPropertyTax, f"bedroom Surcharge was {bedroomSurcharge}")
To call the function just do:
main_function()
You can return this tuple or print the whole thing you have at the end, up to you. I just point out that you can return just a value or a sentence.
Related
I want to store my data and add them after every command, but when I choose a new command again, the initial data will be disappeared.
How do I store my data and continue adding?
My code:
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
amount = initial_money #I don't know how to modify ...
amt = records[1]
amount += int(amt)
print('Total amount',amount)
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
The output:
How much money do you have? 1000
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tree 40
Total amount 1040
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
mouse 70
Total amount 1070
Output I want:
How much money do you have? 1000
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tree 40
Total amount 1040
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
mouse 70
Total amount 1110
You need to declare the initial_money variable a global inside the add function:
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and
amount:\n').split()
amt = records[1]
global initial_money
initial_money += int(amt)
print('Total amount', initial_money)
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
This should work.
Your amount variable is local and when the function exits it is not saved. You can use it as a global variable by putting it outside of the function and declaring global amount at the beginning and that way you can edit it during the run.
You just need to save it into your variable.
global initial_money # this will let you use it anywhere in the code
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
amount = initial_money #I don't know how to modify ...
amt = records[1]
amount += int(amt)
initial_money = amount #this saves it
print('Total amount',amount)
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
I completed an assignment for a scripting class I'm taking, and it worked fine, but I wanted to take it a step further, which has sent me down a rabbit hole. The script is for an ATM transaction.
I added a while loop to give the user additional options, instead of just ending the program. But I found the my account_balance variable remained equal to the default value set initially (in this case 500.25). I've been trying to find ways to make this update as the user goes through the program, in theory it should go as follows:
User checks balance = $500.25 --------------> balance(account_balance)
User makes deposit = $500.00 ---------------> deposit(account_balance, amount)
User checks balance again = $1,000.25 ---> program always returns with $500.25
To try and make this work, I made another function transactionGo(pin), and set all the other functions inside it, hoping this would update the variable account_balance, that didn't work either, and in fact caused more problems, I feel I'm going down a road I shouldn't.
import sys
# -------------------------- DECLARE variables for balance, deposit, and withdrawal --------------------------
account_balance = float(500.25) # Starting balance indicated by Codio
#balance = 100
amount = 0
#deposit_amount = 0 # Declare variable 'deposit_amount'
#withdrawal_amount = 0 # Declare variable 'withdrawal_amount'
pin = ''
# -------------------------- DEFINE FUNCTIONS - balance, withdrawal, and deposit -----------------------------
def transactionGo (pin):
pin = int(input("Please enter your 5 digit pin number:\n"))
def balance(account_balance): # Define balance function
print("Your current balance is $%.2f" % (account_balance)) # Prints the current available balance
def deposit(account_balance, amount): # Define DEPOSIT function with parameters account_balance and amount
amount = float(input("How much would you like to deposit today?\n")) # Accept user input for the deposit amount, in float format
balance = account_balance + amount # This addition assigns the updated value of the account balance, to the variable 'account_balance'
print("Deposit was $%.2f , your new current balance is $%.2f" % (amount, balance)) # Prints deposit amount and account balance
return balance # Return records the new value of account_balance to reflect accordingly in other transactions
def withdrawal(account_balance, amount): # Define WITHDRAWAL function with parameters account_balance and withdrawal_amount
amount = float(input("How much would you like to withdraw today?\n")) # Accept user input for the withdrawal amount, in float format
if amount > account_balance: # Checking to see if the amount requested, is greater than the amount available
print("Insufficient funds, $%.2f is greater than your account balance of $%.2f" % (amount, account_balance)) # If the amount requested is greater than the account balance, there are insufficient funds
else: # Sufficient amount of funds are available, the function continues
balance = account_balance - amount # Variable 'balance' is assigned to reflect the new available balance
print ("Withdrawal amount was $%.2f, your new current balance is $%.2f" % (amount, balance)) # Prints withdrawal amount and account balance
return balance # Return records the new value of balance to reflect accordingly in other transactions
# Lines 18 and 20 compose a conditional statement with the withdrawal function
# Line 18 => if the requested withdrawal amount is greater than the account balance, the conditional statement stops, and prints to the user there are insufficient funds
# Line 20 => if there are sufficient funds available, the conditional statement continues, updates the 'balance', and outputs to the user their withdrawal amount and new available balance
# ------------------------------------ ACCEPT USER INPUT - D, B, W, or Q -------------------------------------
userAccess = input ("Welcome to Tom & Kate Banking, if you would like to sign into your account, please press (C)ontinue, or (E)xit\n").upper()
if userAccess == 'C':
transactionGo (pin)
userChoice = 'go' # Setting the variable 'userChoice' to 'go', so we can implement a while loop
# Step ONE => Create a WHILE loop to offer the user additional options after they have completed a transaction
while userChoice != 'E': # As long as the user does not select 'E' (Exit), the program will keep looping with user choices
# Step TWO => Ask user what action they would like to proceed with, user input is accepted and assigned to the variable 'userchoice'
userChoice = input ("Would you like to check your (B)alance, make a (D)eposit, (W)ithdraw cash, or (E)xit?\n").upper()
# Step THREE => conditional statement begins based on the value of variable 'userchoice' from user input
# Four branches utilizing if / elif for DEPOSIT, BALANCE, WITHDRAWAL, EXIT
if (userChoice == 'D'): # Accepts input D and proceeds with function 'deposit'
deposit (account_balance, amount) # DEPOSIT function is called with parameters 'balance' and 'amount'
elif (userChoice == 'B'): # Accepts input B and proceeds with function 'balance'
balance (account_balance) # BALANCE function is called with parameter 'balance'
elif (userChoice == 'W'): # Accepts input D and proceeds with function 'withdrawal'
withdrawal (account_balance, amount) # WITHDRAWAL function is called with parameters 'balance' and 'amount'
elif (userChoice == 'E'): # Accepts input E for EXIT
print("Thank you for banking with us.") # There is no function for EXIT, and therefore the user has a printed message ending their session
else:
print("We hope to see you again soon, have a nice day!")
When I run this, the first function runs - transactionGo(pin), but when I go into the other transaction functions, IDLE tells me my variables are undefined.
PROBLEM: The scope of the account_balance variable and the functions within transactionGo are different to how you are using them. For example, if you wish to modify a variable outside of a function you need to declare it global at the top of your function definition.
Furthermore, the functions within transactionGo cannot be accessed anywhere in the file except for the transactionGo function itself as the scope of the functions is just within the transactionGo function and not anywhere else. This is why IDLE tells you the functions are undefined, because they are not a part of the file but a part of the transactionGo function and inside of that function only. So in your code those functions are never called
SOLUTIONS: You need to ensure you understand scope in python. The following link is an amazing explanation of what is meant by scope:
https://www.w3schools.com/python/python_scope.asp
In the following methods used to solve this issue, I will assume you want the functions themselves to change and modify the banking variables themselves.
Method #1: Using the 'global' keyword and fixing the functions scopes
# Describe the problem
# How to learn more about the problem
# Full solutions explained.
import sys
# -------------------------- DECLARE variables for balance, deposit, and withdrawal --------------------------
account_balance = float(500.25) # Starting balance indicated by Codio
#balance = 100
amount = 0
#deposit_amount = 0 # Declare variable 'deposit_amount'
#withdrawal_amount = 0 # Declare variable 'withdrawal_amount'
pin = ''
# -------------------------- DEFINE FUNCTIONS - balance, withdrawal, and deposit -----------------------------
def transactionGo (pin):
pin = int(input("Please enter your 5 digit pin number:\n"))
def balance(account_balance): # Define balance function
print("Your current balance is $%.2f" % (account_balance)) # Prints the current available balance
def deposit(): # Define DEPOSIT function with parameters account_balance and amount
global account_balance # Using the 'global' keyword allows you to edit and modify the value of account_balance
amount = float(input("How much would you like to deposit today?\n")) # Accept user input for the deposit amount, in float format
account_balance += amount # This addition assigns the updated value of the account balance, to the variable 'account_balance'
print("Deposit was $%.2f , your new current balance is $%.2f" % (amount, account_balance)) # Prints deposit amount and account balance # Return records the new value of account_balance to reflect accordingly in other transactions
def withdrawal(): # Define WITHDRAWAL function with parameters account_balance and withdrawal_amount
global account_balance
amount = float(input("How much would you like to withdraw today?\n")) # Accept user input for the withdrawal amount, in float format
if amount > account_balance: # Checking to see if the amount requested, is greater than the amount available
print("Insufficient funds, $%.2f is greater than your account balance of $%.2f" % (amount, account_balance)) # If the amount requested is greater than the account balance, there are insufficient funds
else: # Sufficient amount of funds are available, the function continues
account_balance -= amount # Variable 'balance' is assigned to reflect the new available balance
print ("Withdrawal amount was $%.2f, your new current balance is $%.2f" % (amount, account_balance)) # Prints withdrawal amount and account balance
return balance # Return records the new value of balance to reflect accordingly in other transactions
# Lines 18 and 20 compose a conditional statement with the withdrawal function
# Line 18 => if the requested withdrawal amount is greater than the account balance, the conditional statement stops, and prints to the user there are insufficient funds
# Line 20 => if there are sufficient funds available, the conditional statement continues, updates the 'balance', and outputs to the user their withdrawal amount and new available balance
# ------------------------------------ ACCEPT USER INPUT - D, B, W, or Q -------------------------------------
userAccess = input ("Welcome to Tom & Kate Banking, if you would like to sign into your account, please press (C)ontinue, or (E)xit\n").upper()
if userAccess == 'C':
transactionGo (pin)
userChoice = 'go' # Setting the variable 'userChoice' to 'go', so we can implement a while loop
# Step ONE => Create a WHILE loop to offer the user additional options after they have completed a transaction
while userChoice != 'E': # As long as the user does not select 'E' (Exit), the program will keep looping with user choices
# Step TWO => Ask user what action they would like to proceed with, user input is accepted and assigned to the variable 'userchoice'
userChoice = input ("Would you like to check your (B)alance, make a (D)eposit, (W)ithdraw cash, or (E)xit?\n").upper()
# Step THREE => conditional statement begins based on the value of variable 'userchoice' from user input
# Four branches utilizing if / elif for DEPOSIT, BALANCE, WITHDRAWAL, EXIT
if (userChoice == 'D'): # Accepts input D and proceeds with function 'deposit'
deposit () # DEPOSIT function is called with parameters 'balance' and 'amount'
elif (userChoice == 'B'): # Accepts input B and proceeds with function 'balance'
balance (account_balance) # BALANCE function is called with parameter 'balance'
elif (userChoice == 'W'): # Accepts input D and proceeds with function 'withdrawal'
withdrawal () # WITHDRAWAL function is called with parameters 'balance' and 'amount'
elif (userChoice == 'E'): # Accepts input E for EXIT
print("Thank you for banking with us.") # There is no function for EXIT, and therefore the user has a printed message ending their session
else:
print("We hope to see you again soon, have a nice day!")
Method #2: Making a BankAccount class to store these methods and attributes
BankAccount.py
# This file will contain the class, to keep our project organised
class BankAccount:
def __init__(self, account_balance, pin):
self.account_balance = account_balance # The account_balance is a class attribute
self.pin = pin # Class attribute
def __repr__(self):
return f'Account Balance: {self.account_balance}, Pin: {pin}'
def check_pin(self):
number_of_tries = 3 # Number of pin tries the user gets
for i in range(number_of_tries, 0, -1): # Counts backwards from the number_of_tries to the last digit 0
print(f'Number of attempts remaining: {i}')
while True:
try:
inputted_pin = input('Please enter your 5 digit pin number:\n')
if len(inputted_pin) != 5: # Checks and then handles whether or not the pin is 5 digits
incorrect_pin_length_error_message = 'Please ensure the pin you enter is 5 digits long\n\n'
print(incorrect_pin_length_error_message)
inputted_pin = int(inputted_pin)
if inputted_pin == self.pin: # If the valid pin is the actual pin of this bank account
return True # Allows the user to enter
else:
break # Breaks out of the while loop making onto the next iteration of the for loop
except ValueError: # If the pin entered contains any character that is not a number then this except block will be hit when int(inputted_pin) is called
did_not_enter_all_numbers_error_message = 'Please ensure that you have entered pin number.\n\n'
print(did_not_enter_all_numbers_error_message)
# If there is an error in the way a pin was entered it does not count as an attempt
# Only when the pin is valid does it use up an attempt
return False # Returns False if the user fails to input the correct pin in the number of tries given
def check_balance(self):
"""
Prints the balance of the bank account.
"""
print('Your current balance is $%.2f\n' % self.account_balance)
def make_deposit(self):
try:
amount_to_deposit = input('How much would you like to deposit today?\n')
try:
if len(amount_to_deposit.split('.')[1]) != 2: # Checks whether or not the user inputted two decimal places and two decimals only
more_than_two_decimal_place_error_message = 'Please ensure that your deposit is to two decimal places only.\n\n'
print(more_than_two_decimal_place_error_message)
else:
if amount_to_deposit.count('.') > 1: # Ensures that there is not more than one decimal point in the given input
multiple_decimal_points_error_message = 'Please ensure that the amount you wish to withdraw does not have multiple decimal points.\n\n'
print(multiple_decimal_points_error_message)
else:
self.account_balance += float(amount_to_deposit) # Adds the amount once validated
self.check_balance() # Prints out the current balance of the user
except IndexError: # Occurs if the user does not enter a decimal point
did_not_enter_two_decimal_places_error_message = 'Please ensure that you enter exactly two decimal places in your deposit.\n\n'
print(did_not_enter_two_decimal_places_error_message)
except ValueError: # Ensures that the input are all numbers
did_not_enter_number_error_message = 'Please ensure that you enter a numerical amount.\n\n'
def make_withdrawal(self):
try:
amount_to_withdraw = input('How much would you like to withdraw today?\n')
if len(amount_to_withdraw.split('.')[1]) != 2: # Ensures that there are two decimal places inputted and hta
more_than_two_decimal_place_error_message = 'Please ensure that your withdrawal is to two decimal places only.\n\n'
print(more_than_two_decimal_place_error_message)
else:
if amount_to_withdraw.count('.') > 1: # Ensures that there is not more than one decimal point in the given input
multiple_decimal_points_error_message = 'Please ensure that the amount you wish to withdraw does not have multiple decimal points.\n\n'
print(multiple_decimal_points_error_message)
else:
amount_to_withdraw = float(amount_to_withdraw)
if amount_to_withdraw > self.account_balance: # Ensures that the user has enough funds to withdraw money from
insufficient_funds_message = 'Insufficient funds, $%.2f is greater than your account balance of $%.2f' % (amount_to_withdraw, self.account_balance)
else:
self.account_balance -= amount_to_withdraw # Once validated withdraws the amount from the account
self.check_balance() # Prints the user's balance
except ValueError: # Ensures that the input is only numbers
did_not_enter_number_error_message = 'Please ensure that you enter a numerical amount.\n\n'
def exit_transaction():
exit_message = 'Thank you for banking with us.'
print(exit_message)
def do_transaction():
# The main loop that you defined in your original code.
if self.check_pin():
while True:
user_choice = input('Would you like to check your (B)alance, make a (D)eposit, (W)ithdraw cash, or (E)xit?\n').upper()
if user_choice == 'B':
self.check_balance()
elif user_choice == 'D':
self.make_deposit()
elif user_choice == 'W':
self.make_withdrawal()
elif user_choice == 'E':
self.exit_transaction()
else:
unsuccessful_pin_error_message = 'It seems like you ran out of pin tries, please try again later.'
print(unsuccessful_pin_error_message)
main.py
from BankAccount import BankAccount
person1_bank_account = BankAccount(account_balance=500.25, pin=12345)
person2_bank_account = BankAccount(account_balance=1100.00, pin=54321)
# As many as you want
# Perform any functions on them
person1_bank_account.make_deposit()
person2_bank_account.make_withdrawal()
# Print values
print(person1_bank_account.account_balance)
print(person2_bank_account.pin)
This way your code is more flexible, clean, and scalable. For example in your class you can add ass many methods as you want in whatever way you want, and every instance of that class gains that functionality on top of being easy to manage. You can handle any exception you want in whatever way you want. So this is what I would suggest.
As mentioned in the title I am getting a TypeError: 'float' object is not callable when using my code.
The code runs once correctly with the information that I want but fails to run the second time using for fare in fares.
Error message is here:
File "/Users/dty2004/Desktop/AS 91373.py", line 71, in <module>
discounted_price(destination_fare)
TypeError: 'float' object is not callable
Code is here:
# Define the lists required for storing discount and discount_price
fare_auck = ["Auckland"]
fare_well = ["Wellington"]
fare_roto = ["Rotorua"]
# Make the lists into a 2D list
fares = [fare_auck, fare_well, fare_roto]
# Define the menu() function, which gives us the basic interface for
launching functions
def menu(destination, discounted_price, discount, saver_type,
original_price):
print("***** Waikato Air *****")
print("These saver fares for tomorrow only!")
print("Destination: {}".format(destination))
print("Discounted Price: ${:.2f}".format(discounted_price))
print("Percentage Discount: {:.2f}%".format(discount))
print("This fare is a: {}".format(saver_type))
print("Original Price: ${:.2f}".format(original_price))
print("") # Added an empty string to format the function to look nice
consecutively
# Define the function for destination determination
def destination_determiner():
if fares[0][0] == "Auckland":
travel_location = "Auckland"
fares[0].insert(0, "placeholder")
return travel_location
elif fares[1][0] == "Wellington":
travel_location = "Wellington"
fares[1].insert(0, "placeholder")
return travel_location
elif fares[2][0] == "Rotorua":
travel_location = "Rotorua"
fares[2].insert(0, "placeholder")
return travel_location
# Define the function for determining the type of saver fare this is
def saver_type(discount):
if discount < 20 and discount > -1:
saver_type = "Quick Saver"
return saver_type
elif discount >= 20 and discount <= 50:
saver_type = "Smart Saver"
return saver_type
elif discount > 50 and discount < 101:
saver_type = "Super Saver"
return saver_type
else:
print("Sorry that input is invalid")
# Define the function for determining the original_price
def original_price_calc(discount, discounted_price):
original_price = discounted_price * (discount / 100 + 1)
return original_price
# Define the function for getting discounted_price from user input
def discounted_price(destination):
discounted_price = float(input("Please input the discounted price to
{}".format(destination_fare)))
fare.append(discounted_price)
# Define the same function for getting discount from user input
def discount(destination):
discount = float(input("Please input the discount in percentage to
{}".format(destination_fare)))
fare.append(discount)
# Run the entire code, formatted into a print statement
for fare in fares:
destination_fare = destination_determiner()
discounted_price(destination_fare)
discount(destination_fare)
discounted_price = fare[2]
discount = fare[3]
menu(destination_fare, discounted_price, discount, saver_type(discount),
original_price_calc(discount, discounted_price))
This runs once using accepted values in this example of 100 and 30:
Please input the discounted price to Auckland100
Please input the discount in percentage to Auckland30
***** Waikato Air *****
These saver fares for tomorrow only!
Destination: Auckland
Discounted Price: $100.00
Percentage Discount: 30.00%
This fare is a: Smart Saver
Original Price: $130.00
I'm unsure as to why this works the first time but not the second.
Also bear in mind I am a student and so may not have much knowledge on more advanced python commands.
Thanks in advance.
You're reassigning discounted_price to a variable here:
# Run the entire code, formatted into a print statement
for fare in fares:
destination_fare = destination_determiner()
discounted_price(destination_fare) # still a function
discount(destination_fare)
discounted_price = fare[2] # now a float!!!!
discount = fare[3] # same with this (overrides discount from earlier)
menu(destination_fare, discounted_price, discount, saver_type(discount),
original_price_calc(discount, discounted_price))
Rename the variable to something else
for fare in fares:
destination_fare = destination_determiner()
discounted_price(destination_fare)
discount(destination_fare)
discounted_price_value = fare[2]
discount_value = fare[3]
menu(destination_fare, discounted_price_value, discount_value,
saver_type(discount_value),
original_price_calc(discount_value, discounted_price_value))
OK - I am trying to get a Python function to accept variables from two other functions. Is this possible ?
A sample of what I am trying to do it below (I have simmed down the original code - for input here). Hopefully you get theidea of what I am trying to do. In a nutshell, I have Rectangle () which calls Extras() and the I want the output from Rectangle and Extras to be sent to the Calculate_Deposit ().
Is this possible ?
def calculate_deposit(total_cost, extras):
deposit_percent = float(raw_input("Enter Deposit % (as a decimal) of Total Cost: "))
months_duration = float(raw_input("Enter the number of months client requires: "))
if deposit_percent >0:
IN HERE JUST SOME CALCULATIONS
else:
print "The total amount required is: ", total_cost
def rectangle(width, height, depth, thickness):
type = raw_input("Enter lowercase c for concrete: ")
if type == 'c':
output = IN HERE JUST COME CALCULATIONS
else:
return raw_input("Oops!, something went wrong")
print output + extras()
total_cost = calculate_deposit(output, extras)
def extras():
type = float(raw_input("Enter 1 for lights: "))
if type == 1:
light = 200
print "The cost of lights are: ", light
return light
else:
return raw_input("No extras entered")
In rectangle, you call extras(), then you send just the function extras to calculate_deposit(). You want to send the result of the extras() call, not a reference to the function itself. You can make a minor change and save that value, referring to it when you print and when you go into calculate_deposit.
Change this:
print output + extras()
total_cost = calculate_deposit(output, extras)
To this:
extra = extras()
print output + extra
total_cost = calculate_deposit(output, extra)
def main():
totalprofit = 0
stockname = input("Enter the name of the stock or -999 to quit: ")
while stockname != "-999":
sharesbought, purchasingprice, sellingprice, brokercommission = load()
amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss = calc(sharesbought, purchasingprice, sellingprice, brokercommission)
output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofpaidcommission, profitorloss)
stockname = input("Enter the name of the next stock (or -999 to quit): ")
totalprofit += profitorloss
print("\n Total profit is: ", format(totalprofit, '.2f'))
def load():
sharesbought = int(input("Number of shares bought: "))
purchasingprice = float(input("Purchasing price: "))
sellingprice = float(input("Selling price: "))
brokercommission = float(input("Broker commission: "))
return sharesbought, purchasingprice, sellingprice, brokercommission
def calc(sharesbought, purchasingprice, sellingprice, brokercommission):
amountpaid = sharesbought * purchasingprice
amountofpaidcommission = amountpaid * (brokercommission/100)
amountstocksoldfor = sharesbought * sellingprice
amountofsoldcommission = amountstocksoldfor * (brokercommission/100)
profitorloss = (amountpaid + amountofpaidcommission) - (amountstocksoldfor - amountofsoldcommission)
return amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss
def output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss,):
print("\n Stock name: ", stockname, sep = '')
print("Amount paid for the stock: ", format(amountpaid, '.2f'))
print("Commission paid to broker when the stock was bought: ", format(amountofpaidcommission, '.2f'))
print("Amount the stock sold for: ", format(amountstocksoldfor, '.2f'))
print("Commission paid to broker when the stock was sold: ", format(amountofsoldcommission, '.2f'))
print("Profit or loss: ", format(profitorloss, '.2f'))
main ()
The objective of the first function is to allow a user to input the followings as many times as she or he wants until the user decides is done:
Stock name
Shares bought
Selling price
Broker commission
My main problem is then in the main function. I am skeptical whether I am using the while loop correctly or if it's correct at all. I tried to run the program but it won't output anything.
Also, shouldn't I add this at the end of the program with the values inputted to call all the functions above:
def main()
load()
calc()
output()
Or is it fine within the while loop?
I think a while loop is perfectly appropriate for this use case, where you want to loop an indeterminate number of times, stopping when some condition is not met.
There is one obvious problem, on this line:
stockname +=1
This doesn't make any sense. Since stockname is a string, you can't add one to it. Instead, you should be asking the user for the next stock name (or a "special" value to signal they're done). Try replacing that line with something like:
stockname = input("Enter the name of the next stock (or -999 to quit): ")
The rest of your code appears correct, if rather verbose. Unless you think it's likely you'll call some of your other functions in some other place in your code, it might be simpler and cleaner to include all the logic in one function. Functions are nice, but you should balance the benefits of isolating each part of your code in its own function against the effort of passing lots of values between them.