I am writing this python program and everything works but when I run it, I get stuck in an infinite loop. How do I fix it? thanks.
import sys
def main():
name = input("Enter your name:")
ssn = input("Enter your Social Security Number:")
income = eval(input("Enter your net income:"))
while income <= 0:
print("Error, then net income you entered is less than zero! Try again.")
income = eval(input("Enter your net income again:"))
while income > 0:
net = calc(income, name, ssn)
def calc(income, name, ssn):
if income > 15000.00:
tax = .05 * (income - 15000.00)
print(tax)
print(name)
print(ssn)
sys.exit
elif income > 30000.00:
tax = .1 * (income - 30000.00)
print(tax)
print(name)
print(ssn)
sys.exit
else:
print("There is no tax to be paid, income is in the first $15000.00")
print(name)
print(ssn)
sys.exit
main()
sys.exit is a function. You need to call it (sys.exit()) to exit the script.
The second while in your main() is not needed.
The next thing is that "sys.exit" is not right, you have to write "sys.exit()".
In your calc() function you should replace if "if income > 15000.00:" with "if income > 15000.00 and income <= 30000:" or the elif case will never get considered.
Here the correct code:
import sys
def main():
name = input("Enter your name:")
ssn = input("Enter your Social Security Number:")
income = eval(input("Enter your net income:"))
while income <= 0:
print("Error, then net income you entered is less than zero! Try again.")
income = eval(input("Enter your net income again:"))
net = calc(income, name, ssn)
def calc(income, name, ssn):
if income > 15000.00 and income <= 30000:
tax = .05 * (income - 15000.00)
print(tax)
print(name)
print(ssn)
sys.exit()
elif income > 30000.00:
tax = .1 * (income - 30000.00)
print(tax)
print(name)
print(ssn)
sys.exit()
else:
print("There is no tax to be paid, income is in the first $15000.00")
print(name)
print(ssn)
sys.exit()
main()
Related
I was following along with a youtube video to a ATM using python and I got expected expression. I dont know how to fix it. line 32, 37 and 40.
enter image description here
You can't have an elif after an else. This is because else will capture all the remaining cases. Indentation, meaning spaces or tabs before the line is very important in Python.
Here is what I think you meant to write:
balance = 1000
print("""
Welcome to Dutch Bank
Choose Transaction
1) BALANCE
2) WITHDRAW
3) DEPOSIT
4) EXIT
""")
while True:
option = int(input("Enter Transaction"))
if option == 1:
print ("Your Balance is", balance)
anothertrans = input("Do You Want to make another Transaction? Yes/No: ")
if anothertrans == "YES":
continue
else:
break
elif option == 2:
withdraw = float(input("Enter Amount To Withdraw"))
if (balance > withdraw):
total = balance - withdraw
print("Success")
print("Your New Balance is: ",total)
else:
print("Insufficient Balance")
elif option == 3:
deposit = float(input("Enter Amount To Deposit"))
totalbalance = balance + deposit
print("Sucess")
print("Total Balance Now is: ", totalbalance)
elif option == 4:
print("Thank You ForBanking With Dutch Bank")
exit()
else:
print ("No selected Transaction")
I am trying to add exception handling to the cost and company variables.
I need an exception to make sure my cost variable is greater than $0.
And an exception on the company variable so the input is not empty. The exception on the company variable works but I am having trouble figuring out how to separate the if-else statement. I am still very new to programming.
def main():
print("This program will calculate the shipping cost based on "
"the total purchase price,\n")
while True:
try:
company = input('Please enter the company name: ')
if company == "":
raise ValueError("Please provide a valid company name.")
break
except ValueError as excpt:
print(excpt)
while True:
try:
cost = float(input("Please enter in the purchase price: "))
if cost <= 0:
raise ValueError("Please enter a value greater than $0.00.")
break
except ValueError as excpt:
print(excpt)
if cost <= 100.00:
shipping = 10.0
elif cost <= 300.00:
shipping = 8.0
elif cost <= 500.00:
shipping = 5.0
else:
shipping = 0.0
total = cost + shipping
print("At a purchase price of ${:.2f}, the shipping cost will be ${:.2f},"
" with a final total of ${:.2f}.".format(cost, shipping, total))
print('{}, thank you for shopping with us!'.format(company))
main()
This is the output:
Please enter the company name:
Please provide a valid company name.
Please enter the company name: ASX
Please enter in the purchase price: -5.99
Please enter a value greater than $0.00.
At a purchase price of $-5.99, the shipping cost will be $10.00, with a final total of $4.01.
ASX, thank you for shopping with us!
Please enter in the purchase price:
You need to fix your second indentation after the second while loop. You are breaking into emptiness.
newcode
def main():
print("This program will calculate the shipping cost based on " "the total purchase price,\n")
while True:
try:
company = input('Please enter the company name: ')
if company == "":
raise ValueError("Please provide a valid company name.")
break
except ValueError as excpt:
print(excpt)
while True:
try:
cost = float(input("Please enter in the purchase price: "))
if cost <= 0:
raise ValueError("Please enter a value greater than $0.00.")
break
except ValueError as excpt:
print(excpt)
if cost <= 100.00:
shipping = 10.0
elif cost <= 300.00:
shipping = 8.0
elif cost <= 500.00:
shipping = 5.0
else:
shipping = 0.0
total = cost + shipping
print("At a purchase price of ${:.2f}, the shipping cost will be ${:.2f},"
" with a final total of ${:.2f}.".format(cost, shipping, total))
print('{}, thank you for shopping with us!'.format(company))
if __name__ == '__main__':
main()
output
This program will calculate the shipping cost based on the total purchase price,
Please enter the company name: apple
Please enter in the purchase price: -100
Please enter a value greater than $0.00.
Please enter in the purchase price: 100
At a purchase price of $100.00, the shipping cost will be $10.00, with a final total of $110.00.
apple, thank you for shopping with us!
use assert statement instead then catch AssertionError instead of ValueError, here is how it will look like:
try:
cost = float(input())
assert cost > 0, "Cost must be greater than 0"
except AssertionError as e:
print(e)
and do the same with other inputs
Solution
# error handling made by yourself
class NoCompanyName(Exception):
pass
class CostError(Exception):
pass
# new code
def main_new():
from time import sleep
print("This program will calculate the shipping cost based on \" the totalprice\"\n")
while True:
company = input("Please enter company name.\n")
if company == None:
raise NoCompanyName("Please enter company name!")
else:
pass
while True:
cost = int(input("Please enter purchase price."))
if cost == None:
raise CostError("You should specify cost that wasn\'t lower than 0 or None!")
else:
if cost <= 0:
raise CostError("You should specify cost that wasn\'t lower than 0!")
else:
pass
if cost <= 100.00:
shipping = 10.0
elif cost <= 300.00:
shipping = 8.0
elif cost <= 500.00:
shipping = 5.0
else:
shipping = 0.0
total = cost + shipping
print(f"At purchase price of ${cost}, the shipping will cost ${shipping}. With final total is ${total}")
print(f"{company}, Thank you for shipping with us!")
sleep(5)
main_new()
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()