I'm so new to programming logic I'm not sure I can phrase this properly. I'm using Python 2.7 and am trying to write a script that will repeat until zero is entered. I've tried if, else, and while statements and have concluded that I don't know enough about logic to know anything about Python. For example...I'm so new that init means nothing to me. I've seen the phrase in almost every search result I've received, but I don't no what it means or is. The class I'm in is a LOGIC class not a Python class. I can write it in pseudocode but I would really like to see a working model. Please Help. This script runs through and will exit when zero is entered, but it will not prompt for miles driven again.
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
getMiles = float(input ('Enter Miles: '))
while getMiles == 0:
print "END OF PROGRAM"
exit
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
while costOfTrip == float:
getMiles
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
Something that I forgot to mention was the mandatory "END OF PROGRAM" statement. I used a combination of your answers and this works. Again, Thank you everyone. I can stop banging my head on the wall.
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or enter zero to quit"
getMiles = float(raw_input ('Enter Miles: '))
while getMiles >= 0:
if getMiles == 0:
print "END OF PROGRAM"
exit()
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
getMiles = float(raw_input ('Enter Miles: '))
Python is not really that far from pseudocode, and indeed the problem here is not the code but the logic.
To get the basic "loop until entering zero" you can have the following logic:
miles = -1
while miles != 0:
miles = float(raw_input ('Enter Miles: '))
As for your own code, you seem to be using 'while' when you mean 'if'
And in the second while you are actually just naming a variable (getMiles) which does nothing
The whole code could look like this:
miles = float(raw_input ('Enter Miles: '))
while miles != 0:
fuelEcon = miles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = miles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = miles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
miles = float(raw_input ('Enter Miles: '))
** no need to use "while true" as others suggested, it's never a nice thing to do.
A more advanced version would be to extract the part of the logic which is repeatable and standalone to a function
def trip_cost(miles):
if(miles == 0):
return False
fuelEcon = miles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = miles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = miles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
return True
while trip_cost(float(raw_input ('Enter Miles: '))):
pass
As for what init is, that's a much more advanced topic of Objects Orientation which you probably shouldn't worry about just yet
I'd just say as a matter of style that even your new loop condition / logic could be quickly tidied up to read
print "To Calculate the cost of your trip,"
print "enter the miles driven or enter zero to quit"
getMiles = float(raw_input ('Enter Miles: '))
while getMiles != 0:
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
getMiles = float(raw_input ('Enter Miles: '))
print "END OF PROGRAM"
# should be no need for exit() unless code is included in a subroutine
You were very close, here is the fixed version:
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
while True:
getMiles = float(input ('Enter Miles: '))
if getMiles == 0:
print "END OF PROGRAM"
exit()
fuelEcon = getMiles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = getMiles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = getMiles * fuelIncrease
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
I added a while True around the whole block of code, this will cause the question to be asked over and over again (forever) until the user enters 0 for miles.
The only other thing that needed to be fixed was that exit is a function call so it should be exit().
total_miles = 0
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
getMiles = float(input ('Enter Miles: '))
while getMiles != 0:
total_miles = getMiles + total_miles
getMiles = float(input ('Enter Miles: '))
else:
print "END OF PROGRAM"
exit
fuelEcon = total_miles / 20
fuelCost = float(input ('Enter Cost of Fuel: $'))
costOfTrip = total_miles * fuelCost
fuelIncrease = (fuelCost * .1) + fuelCost
futureTrip = total_miles * fuelIncrease
while costOfTrip == float:
getMiles
print "Cost of Trip: $", costOfTrip
print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip
You could do it like this
#Cost of Trip Ch2 Q8
print "To Calculate the cost of your trip,"
print "enter the miles driven or zero to quit"
while True:
getMiles = float(input ('Enter Miles: '))
if getMiles == 0:
print "END OF PROGRAM"
break
print 'Do the other calculations'
Go into an infinite loop until 0 is entered at which point you break out of the loop and the program ends.
You can use While 1: under python 2.7 to get faster performance, but I doubt this will be your concern at the moment.
Related
I have tried the following code to update the number of available cars based on the previous operations. So, for instance, if I have 3 available cars and the user rented one already, then the code should be updated to display 2 cars to the user. But whenever I ran my code, the number of available cars is always the same.
Here is my code:
if option_no==1:
print("Select one of the available cars: ")
print("--------------------------------------------------------------------------------------------------------------")
print("Model \t\tAvailable \tPrice/day \tLiability insurance/day \tComprehensive insurance/day")
print("--------------------------------------------------------------------------------------------------------------")
camery_price = 90
camery_availability = 3
camery_liability_insurance = 20
camery_comprhensive_insurance = 50
print("1. Camery \t\t\b\b\b\b",camery_availability, "\t\t\t\b\b\b\b\bQR90 \t\tQR20 \t\t\t\t\t\b\b\b\bQR50")
pajero_price = 150
pajero_liability_insurance = 30
pajero_comprhensive_insurance = 70
print("2. Pajero \t\t\b\b\b\b2 \t\t\t\b\b\b\b\bQR150 \t\tQR30 \t\t\t\t\t\b\b\b\bQR70")
altima = 70
altima_liability_insurance = 20
altima_comprhensive_insurance = 50
print("3. Altima \t\t\b\b\b\b2 \t\t\t\b\b\b\b\bQR70 \t\tQR20 \t\t\t\t\t\b\b\b\bQR50")
car_type = int(input("Enter car type: "))
No_of_days = int(input("Enter how many days: "))
insurance_type = input("Enter 'L' for Liability insurance and 'F' for full insurance: ")
if car_type==1:
if insurance_type=='L' or insurance_type=='l':
cost = No_of_days*camery_price
insurance_cost = No_of_days*camery_liability_insurance
tax = cost*0.05
total = cost+insurance_cost+tax
print("Cost: QR", format(cost, '.2f'))
print("Insurance: QR", format(insurance_cost, '.2f'))
print("Tax: QR", format(tax, '.2f'))
print("--------------------------------")
print("Total: ", format(total, '.2f'))
elif insurance_type=='F' or insurance_type=='f':
cost = No_of_days*camery_price
insurance_cost = No_of_days*camery_comprhensive_insurance
tax = cost*0.05
total = cost+insurance_cost+tax
print("Cost: QR", format(cost, '.2f'))
print("Insurance: QR", format(insurance_cost, '.2f'))
print("Tax: QR", format(tax, '.2f'))
print("--------------------------------")
print("Total: ", format(total, '.2f'))
else:
print("Error. Please enter the correct character")
operation = input("More operation? [Y/N] ")
if operation=='N' or operation=='n':
break
camery_availability = camery_availability - 1
I have the following code:
For some reason, the program ignores the 2nd 'if' statement.
Does anyone have any idea why, please?
#define function
def CalculateBasicPay (hours, rate):
pay = hours * rate
return pay
def CalculateOvertimePay (overtime_hours, overtime_rate):
overtime = overtime_hours * overtime_rate * 1.5
return overtime
#main program to get user input
hoursWorked = int()
if hoursWorked < 40:
converted_hours = float(input("Enter number of hours: "))
converted_rate = float(input("Enter your rate: "))
totalHours = CalculateBasicPay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours)
if hoursWorked > 40:
converted_hours = float(input("Enter number of hours: "))
converted_rate = float(input("Enter your rate: "))
totalHours2 = CalculateOvertimePay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours2)
----------
The output is only taking the 1st condition always:
Enter number of hours: 5
Enter your rate: 2
Your total pay is: £ 10.0
>>>
Enter number of hours: 50
Enter your rate: 2
Your total pay is: £ 100.0
-----------
I'm brand-new to python! So please be nice :)
Cheers :)
You should get the hours worked outside the if statement:
#define function
def CalculateBasicPay (hours, rate):
pay = hours * rate
return pay
def CalculateOvertimePay (overtime_hours, overtime_rate):
overtime = overtime_hours * overtime_rate * 1.5
return overtime
#main program to get user input
hoursWorked = float(input("Enter number of hours: "))
converted_rate = float(input("Enter your rate: "))
if hoursWorked < 40:
totalHours = CalculateBasicPay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours)
if hoursWorked > 40:
totalHours2 = CalculateOvertimePay(converted_hours,converted_rate)
print("Your total pay is: £", totalHours2)
Your line hoursWorked = int() doesn't get an input from the user, it just creates an integer with the value 0.
You should replace it with something like:
hoursWorked = int(input("How many hours have you worked: "))
user = str
end = False
hours = round(40,2)
print("How much do you make?")
while end == False:
user = input("\nPlease enter your name or type '0' to quit: ")
if user == "0":
print("End of Report")
break
else:
hours = (float(input("Please enter hours worked: ", )))
payrate =(float(input("Please enter your payrate: $", )))
taxrate = (float(input ("Please enter tax rate: ")))
if hours <= 40:
print(user)
print("Overtime hours: 0")
print("Overtime Pay: $0.00")
regularpay = round(hours * payrate, 2)
print("Gross Pay: $", regularpay)
elif hours > 40:
overtimehours = round(hours - 40.00,2)
print("Overtime hours: ", overtimehours)
print("Employee's name: ", user)
regularpay = round(hours * payrate,2)
overtimerate = round(payrate * 1.5, 2)
overtimepay = round(overtimehours * overtimerate)
if overtimepay == 0:
grosspay = round(regularpay,2)
else overtimepay > 0:
grosspay = round(regularpay+overtimepay,2)
income = (grosspay * taxrate)
print("Regular Pay: $", regularpay)
print("Overtime Pay: $",overtimepay)
print("Gross Pay: $", grosspay)
print ("Income: $", income)
I added that extra If/Else statement to hopefully force it it through but that still didnt seem to get it to work. Even if you remove the second else if statement it still does not get it to print, only when you do have over time then it factors in the tax rate.
You only set overtimepay when you actually process overtime. Undefined variables in python are not 0. They are a special value None. Therefore if no overtime was worked, neither of your ifs evaluates to True and neither branch gets executed.
def main():
def input_stocks():
tot_pr = 0
while True:
stock_name = input("\nEnter Stock Name: ")
shares_bought = float(input("\nNumber of Shares bought: "))
stock_pp = float(input("Enter stock purchasing price: "))
stock_sp = float(input("Enter stock selling price: "))
commision = float(input("Enter broker Commision: "))
peaceout = input("Continue or exit? (case sensitive):")
if peaceout == 'quit':
return stock_name,shares_bought,stock_pp,stock_sp,commision
def calc():
amount_paid = shares_bought * stock_pp
paid_commision_bought = amount_paid * commision
stock_sold = shares_bought * stock_sp
paid_commision_sold = stock_sold * commision
pl = (stock_sold - paid_commision_sold) - (amount_paid + paid_commision_bought)
tot_pr = tot_pr + pl
def output():
print("\nStock Name:", stock_name)
print("Amount paid: $", format(amount_paid,',.2f'))
print("Paid commision bought: $", format(paid_commision_bought,',.2f'))
print("Stock sold $", format(stock_sold,',.2f'))
print("Paid commision sold: $", format(paid_commision_sold,',.2f'))
print("Profit or Loss: $", format(pl,',.2f'))
print("Total Profit thus far: $", format(tot_pr,',.2f'))
return stock_name,amount_paid,paid_commision_bought,paid_commision_sold,pl,tot_pr
output()
main()
>
NameError: name 'stock_name' is not defined (I'd assume others won't be defined as well...
What can I do to fix this error, and how can I prevent this in the future? I am quite new to this so I want to learn from my mistakes
stock_name and the other variables in output() will not be defined until the input_stocks() function is actually run. Just defining a function does not actually run it.
def load():
tot_pr = 0
peaceout = ''
while peaceout != 'exit':
stock_name = input("\nEnter Stock Name: ")
shares_bought = float(input("\nNumber of Shares bought: "))
stock_pp = float(input("Enter stock purchasing price: "))
stock_sp = float(input("Enter stock selling price: "))
commision = float(input("Enter broker Commision: "))
peaceout = input("Continue or exit? (case sensitive):")
return stock_name,shares_bought,stock_pp,stock_sp,commision,tot_pr
def calc(shares_bought,stock_pp,stock_sp,commision,tot_pr):
amount_paid = shares_bought * stock_pp
paid_commision_bought = amount_paid * commision
stock_sold = shares_bought * stock_sp
paid_commision_sold = stock_sold * commision
pl = (stock_sold - paid_commision_sold) - (amount_paid + paid_commision_bought)
tot_pr = tot_pr + pl
return amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr
def output(stock_name,amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr):
print("\nStock Name:", stock_name)
print("Amount paid: $", format(amount_paid,',.2f'))
print("Paid commision bought: $", format(paid_commision_bought,',.2f'))
print("Stock sold $", format(stock_sold,',.2f'))
print("Paid commision sold: $", format(paid_commision_sold,',.2f'))
print("Profit or Loss: $", format(pl,',.2f'))
print("Total Profit thus far: $", format(tot_pr,',.2f'))
return stock_name,amount_paid,paid_commision_bought,paid_commision_sold,pl,tot_pr
def main():
stock_name,shares_bought,stock_pp,stock_sp,commision,tot_pr = load()
amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr = calc(shares_bought,stock_pp,stock_sp,commision,tot_pr)
output(stock_name,amount_paid,paid_commision_bought,stock_sold,paid_commision_sold,pl,tot_pr)
main()
I rewrote my program, and the only problem now is it won't loop if I type in continue?
#Joran Beasley
#MattDMo
I've been having some trouble with Else and Elif statements in Python 3.3.3 lately.
Here's my code:
# ATM was programmed by Jamie Mathieson
# introduction
sleep (1)
print ("-----------------------------------------------")
print ("\n ATM ")
print ("\n-----------------------------------------------")
sleep (3)
print ("\nWelcome to ATM. ATM is a mathematical system that handles data.")
sleep (5)
print ("\n Your ATM card has is being inserted. Please wait...")
sleep (3)
print ("Your ATM card has been inserted.")
sleep (5)
print ("Type 'options' to view available commands.")
# variables
balance = print("Balance £", money)
money = 200
options = ("Options: 1) Withdraw <amount> 2) Deposit <amount> 3) Balance 4) Exit")
# statements
option=int(input("Please enter an option: "))
if Option==1:
print("Balance £", money)
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif: Withdraw>money
print("No Balance Remaining")
else:
print("Withdraw canceled.")
if Option==3:
print("Balance £", money)
Deposit=float(input("Please enter the amount of money you would like to deposit: £ "))
if Deposit>0:
newbalance=(money+Deposit)
print("New Balance: £",newbalance)
else:
print("Deposit canceled.")
if Option==4:
print("ATM is ejecting your card. Please wait...")
sleep(5)
exit()
The error I'm getting is "invalid syntax" and it highlights both the Else and Elif statements. What is it that I'm doing wrong?
You have to put the : at the end, and correct the identation.
if Option==2:
print("Balance £", money)
Withdraw=float(input("Please enter the amount of money you would like to withdraw: £ "))
if Withdraw>0:
newbalance=(money-Withdraw)
print("New Balance: £",remainingbalance)
elif Withdraw>money:
print("No Balance Remaining")
else:
print("Withdraw canceled.")
There are several issues with the code. As #Daniel pointed out, your indentation must be corrected. Also, your condition for the elif block is placed after the colon.
Beyond that, you're assigning the user's response to a variable called option and then writing conditions on Option. Those are two different things.
Finally balance = print("Balance £", money) is going to throw an error. It looks like you're trying to define balance as a function that will print "Balance £" followed by the balance amount. If so, you could do something like this:
balance = lambda x: print("Balance £{}".format(x))
Edit: To answer your question re: sleep, use
from time import sleep
while True:
# Reading id from user
id = int(input("\nEnter account pin: "))
# Loop till id is valid
while id < 1000 or id > 9999:
id = int(input("\nInvalid Id.. Re-enter: "))
# Iterating over account session
while True:
# Printing menu
print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")
# Reading selection
selection = int(input("\nEnter your selection: "))
# Getting account object
for acc in accounts:
# Comparing account id
if acc.getId() == id:
accountObj = acc
break
# View Balance
if selection == 1:
# Printing balance
print(accountObj.getBalance())
# Withdraw
elif selection == 2:
# Reading amount
amt = float(input("\nEnter amount to withdraw: "))
ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ")
if ver_withdraw == "Yes":
print("Verify withdraw")
else:
break
if amt < accountObj.getBalance():
# Calling withdraw method
accountObj.withdraw(amt)
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n")
print("\nPlease make a deposit.");
# Deposit
elif selection == 3:
# Reading amount
amt = float(input("\nEnter amount to deposit: "))
ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ")
if ver_deposit == "Yes":
# Calling deposit method
accountObj.deposit(amt);
# Printing updated balance
print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")
else:
break
elif selection == 4:
print("nTransaction is now complete.")
print("Transaction number: ", random.randint(10000, 1000000))
print("Current Interest Rate: ", accountObj.annualInterestRate)
print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)
print("Thanks for choosing us as your bank")
exit()
# Any other choice
else:
print("That's an invalid choice.")
# Main function
main()