How do format my output to 2 decimal places in Python? - python

I'm trying to format my output into 2 decimal places in Python..This is my code
def introduction():
print("This calculator calculates either the Simple or Compound interest of an given amount")
print("Please enter the values for principal, annual percentage, number of years, and number of times compounded per year")
print("With this information, we can provide the Simple or Compound interest as well as your future amount")
def validateInput(principal, annualPercntageRate, numberOfYears,userCompound):
if principal < 100.00:
valid = False
elif annualPercntageRate < 0.001 or annualPercntageRate > .15:
valid = False
elif numberOfYears < 1:
valid = False
elif userCompound != 1 and userCompound != 2 and userCompound != 4 and userCompound != 6 and userCompound != 12:
valid = False
else:
valid = True
return valid
def simpleInterest(principal, annualPercentageRate, numberOfYears):
return (principal * annualPercentageRate * numberOfYears)
def compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound):
return principal * ((1 + (annualPercentageRate / userCompound))**(numberOfYears * userCompound) - 1)
def outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount):
print("Simple interest earned in", numberOfYears, "will be $",simpleAmount,"making your future amount $",(principal + simpleAmount)
print("Interest compounded", userCompound, "in",numberOfYears, "will earn $",compoundAmount,"making your future amount",(principal + compoundAmount)
def main():
introduction()
principal = float(input("Enter principal: "))
annualPercentageRate = float(input("Enter rate: "))
numberOfYears = int(input("Enter years: "))
userCompound = int(input("Enter compounding periods: "))
if validateInput(principal, annualPercentageRate, numberOfYears, userCompound):
simpleAmount = simpleInterest(principal, annualPercentageRate, numberOfYears)
compoundAmount = compoundInterest(principal, annualPercentageRate, numberOfYears, userCompound)
outputAmounts(principal, annualPercentageRate, numberOfYears, userCompound, simpleAmount,compoundAmount)
else:
print("Error with input, try again")
main()
So for my output, I want to format the ending to 2 decimal places. Namely, these 2 variables
-(principal + compoundAmount)
-(principal + simpleAmount)
I know I need to use %.2, but Im not sure how to add that into a print statement so that it would output into 2 decimal places...How do I do this?

try this
print('pi is {:.2f}'.format(your_variable))

You just need simple formatting string, like:
print('pi is %.2f' % 3.14159)
which output is pi is 3.14
You might wanna read https://docs.python.org/2.7/library/string.html#formatspec

Related

loop through multiple questions each with a condition in Python

I am creating a program where you will have to loop through multiple questions each with a condition. If user input for the question does not meet the requirement, it will print out the error and prompt user to re-enter. Else, it will continue with the next question. And not only prompting user to re-enter after all 3 questions are answered.
This it the output I am getting now:
while True:
amount = int(input("Enter amount: "))
rate = int(input("Enter rate: "))
year = float(input("Enter year: "))
if amount<4000:
print("Invalid amount")
continue
elif rate<0:
print("invalid rate")
continue
elif year<0:
print("invalid year")
break
Output:
Enter amount: 1
Enter rate: 3
Enter year: 4
Invalid amount
Enter amount:
Expected output:
Enter amount: 4
Invalid amount
Enter amount:
It's not very clear what are you trying to achieve, but I think you want this:
while True:
amount = int(input("Enter amount: "))
if amount < 4000:
print("Invalid amount")
continue
break
while True:
rate = int(input("Enter rate: "))
if rate < 0:
print("invalid rate")
continue
break
while True:
year = float(input("Enter year: "))
if year < 0:
print("invalid year")
continue
break
This will only ask to re-enter the invalid values.
Another more reusable method would be:
def loop_user_input(input_name, meets_condition):
while True:
value = int(input(f"Enter {input_name}: "))
if not meets_condition(value):
print(f"Invalid {input_name}")
else:
return value
loop_user_input('amount', lambda val: val < 4000)
loop_user_input('rate', lambda val: val < 0)
loop_user_input('year', lambda val: val < 0)
Here you have a loop that only returns when the input value meets the condition, that you pass in. I recommend you check your conditions, because a year normally shouldn't be negative (rate < 0). Also your solution throws an exception, if the user enters something else then an int. Maybe add a try-catch to your solution:
try:
value = int(input(f"Enter {input_name}: "))
except:
print(f"Invalid {input_name}")
continue

if statement ignored in python

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: "))

Question regarding my program being tedious

I just started learning python 3 recently and i have a problem of my code being too repetitive and lengthy.
i wrote a code to calculate the interest earned.
I have read about using functions to simplify my code but i am not sure how to go about doing this.
Thanks for anyone who is willing to help me out! The code i have written is as follows:
print("Welcome to the monthly interest rate calculator")
original_interest = 0.0005/12
additional_food_interest_1 = 0.0055/12
additional_food_interest_2 = 0.0085/12
additional_interest_3 = 0.0090/12
additional_interest_4 = 0.0015/12
additional_interest_5 = 0.0095/12
additional_interest_6 = 0.0035/12
interest = [original_interest]
#asks user for the amount of money they have in the bank
while True:
try:
account = float(input("Enter your account balance: "))
except ValueError:
print("Try Again.")
continue
else:
break
# checks if condition 1 is met before adding either food_interest_1 or food_interest_2 variable to the list
while True:
try:
food_spending = float(input("How much did you spend on food?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if food_spending >= 100 and food_spending < 200:
interest.append(additional_food_interest_1)
elif food_spending >= 200:
interest.append(additional_food_interest_2)
else:
pass
# checks if condition 2 is and if so adds additional_interest_3 to the list
while True:
try:
drinks_spending = float(input("How much did you spend on drinks?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if drinks_spending >= 100:
interest.append(additional_interest_3)
else:
pass
# checks if condition 3 is met and if so adds additional_interest_4 to the list
while True:
try:
insurance_spending = float(input("How much did you spend on insurance?: "))
except ValueError:
print("Try Again.")
continue
else:
break
if insurance_spending >= 100:
interest.append(additional_interest_4)
else:
pass
# checks if condition 4 is met and if so adds additional_interest_5 to the list
while True:
try:
debitcard_spending = float(input("How much did you spend on your debit card??: "))
except ValueError:
print("Try Again.")
continue
else:
break
if debitcard_spending >= 100:
interest.append(additional_interest_5)
else:
pass
# This checks for 4 inputs from the user and if satisfies the condition, adds additional_interest_6 to the list
while True:
try:
first_receipt = float(input("Enter the amount on your first receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
second_receipt = float(input("Enter the amount on your second receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
third_receipt = float(input("Enter the amount on your third receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
while True:
try:
four_receipt = float(input("Enter the amount on your fourth receipt: "))
except ValueError:
print("Try Again.")
continue
else:
break
if first_receipt > 20 and second_receipt > 20 and third_receipt >20 and four_receipt > 20:
interest.append(additional_interest_6)
#calculates the total interest earned
if account <= 20000:
print("your monthly interest earned is", round(account*(sum(interest)),2))
else:
print(20000*sum(interest) + (account-20000)*original_interest)
This is about as concise as I can make it with a quick pass.
I refactored things so all inputs are requested first, all computation done second. Should you refactor the calculation bits into a function, that'd make the function easier to test. I also refactored the computation into a function of its own.
def prompt_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Try Again.")
def prompt_receipts():
receipts = []
while True:
receipt_value = prompt_float(
f"Enter the amount on receipt {len(receipts) + 1}, or <= 0 for no more receipts."
)
if receipt_value <= 0:
break
receipts.append(receipt_value)
if len(receipts) >= 4:
break
return receipts
def compute_interest(
*,
original_interest,
receipts,
debitcard_spending,
drinks_spending,
food_spending,
insurance_spending,
):
additional_food_interest_1 = 0.0055 / 12
additional_food_interest_2 = 0.0085 / 12
additional_interest_3 = 0.0090 / 12
additional_interest_4 = 0.0015 / 12
additional_interest_5 = 0.0095 / 12
interest = [original_interest]
if 100 <= food_spending < 200:
interest.append(additional_food_interest_1)
elif food_spending >= 200:
interest.append(additional_food_interest_2)
if drinks_spending >= 100:
interest.append(additional_interest_3)
if insurance_spending >= 100:
interest.append(additional_interest_3)
if debitcard_spending >= 100:
interest.append(additional_interest_4)
if all(receipt_value > 20 for receipt_value in receipts):
interest.append(additional_interest_5)
return interest
def main():
print("Welcome to the monthly interest rate calculator")
# Get user inputs.
account = prompt_float("Enter your account balance: ")
food_spending = prompt_float("How much did you spend on food?: ")
drinks_spending = prompt_float("How much did you spend on drinks?: ")
insurance_spending = prompt_float("How much did you spend on insurance?: ")
debitcard_spending = prompt_float(
"How much did you spend on your debit card??: "
)
receipts = prompt_receipts()
# Compute things.
original_interest = 0.0005 / 12
interest = compute_interest(
original_interest=original_interest,
receipts=receipts,
debitcard_spending=debitcard_spending,
drinks_spending=drinks_spending,
food_spending=food_spending,
insurance_spending=insurance_spending,
)
# Output things.
if account <= 20000:
print(
"your monthly interest earned is",
round(account * (sum(interest)), 2),
)
else:
print(20000 * sum(interest) + (account - 20000) * original_interest)
if __name__ == "__main__":
main()
You can wrap you try/except approach as:
def get_input(text)
while True:
try:
return float(input(text))
except ValueError:
print("Try Again.")
account = get_input("Enter your account balance: ")
food_spending = get_input("How much did you spend on food?: ")
....

Python: Unknown Syntax Error (easy)

I'm getting a syntax error around the word rental and I just have no clue what I've done wrong. This is like my 6th program. Any and all suggestions are helpful.
#Computes Cable Bill
print("Welcome to cable customer billing calculator")
acct = int(input("Enter an account number"))
cust_type = input("Enter customer type: (R) Residential or (B) Business: ")
def residential():
processing = 4.50
basic_service = 20.50
daily_rental = 2.99
prem_channel_fee = 7.50
prem_channels = int(input("Enter the number of premium channels used: ")
rental = int(input("Were movies rented (Y or N): ")
if rental == Y or y:
rental_days = int(input("Enter the total number of rental days (one day for each movie, each day): ")
else:
rental_days = 0
bill_amt = processing + basic_service + (rental_days * daily_rental) + (prem_channels * prem_channel_fee)
return (bill_amt)
def business():
processing = 15
basic_service = 75
prem_channel_fee = 50
connections = int(input("Enter the number of basic service connections: ")
prem_channels = int(input("Enter the number of premium channels used: ")
if (connections <= 10):
bill_amt = processing + basic_service + (prem_channel * prem_channel_fee)
else:
bill_amt = processing + basic_service + ((connections - 10) * 5) + (prem_channel * prem_channel_fee)
return (bill_amt)
if (cust_type == "R" or "r"):
bill_total = residential()
else:
bill_total = business()
print("Account number: ", acct)
print("Amount due: ",bill_total)
You need to add closing parentheses as depicted in the snippet below and ensure that the first line of your conditionals line up with the previous line. Also, consider matching the value of rental against a list of valid responses – it's more Pythonic way of writing the logic you're proposing:
prem_channels = int(input("Enter the number of premium channels used: "))
rental = int(input("Were movies rented (Y or N): "))
if rental in ['Y', 'y']:
rental_days = input("Enter the total number of rental days (one day for each movie, each day): ")
Similarly, the following lines need closing parentheses:
connections = int(input("Enter the number of basic service connections: "))
prem_channels = int(input("Enter the number of premium channels used: "))
Replace the logic of your final conditional as above:
if (cust_type in ["R", "r"]):
Or, alternatively (but less Pythonic):
if (cust_type == "R" or cust_type == "r"):
Finally, note that input("Were movies rented (Y or N): ") returns a string and thus should not be cast to an integer. If you cast it using int(), you'll receive a type error and if rental in ['Y', 'y']: will never evaluate to true.
if rental == 'Y' or rental == 'y':
Should solve this
Following should help you.
rental = str(input("Were movies rented (Y or N): "))
if rental == "Y" or rental == "y":
Points raised by zeantsoi are also valid. Please consider them too.
There are a number of errors:
prem_channels = int(input("Enter the number of premium channels used: ") needs closing parenthesis.
rental = int(input("Were movies rented (Y or N): ") remove int(. The input is a string.
if rental == Y or y: should be if rental == 'Y' or rental == 'y':.
The whole if rental block needs unindented to line up with the previous line.
The two lines below need trailing ):
connections = int(input("Enter the number of basic service connections: ")
prem_channels = int(input("Enter the number of premium channels used: ")
The if (connections block needs unindented to line up with the previous line.
if (cust_type == "R" or "r"): should be if cust_type == 'R' or cust_type == 'r':
The bill_amt calculations both need to use prem_channels not prem_channel.
In addition, parentheses around if statements and return values are unnecessary.
Here's your code with the above fixes:
#Computes Cable Bill
print("Welcome to cable customer billing calculator")
acct = int(input("Enter an account number"))
cust_type = input("Enter customer type: (R) Residential or (B) Business: ")
def residential():
processing = 4.50
basic_service = 20.50
daily_rental = 2.99
prem_channel_fee = 7.50
prem_channels = int(input("Enter the number of premium channels used: "))
rental = input("Were movies rented (Y or N): ")
if rental == 'Y' or rental == 'y':
rental_days = int(input("Enter the total number of rental days (one day for each movie, each day): "))
else:
rental_days = 0
bill_amt = processing + basic_service + (rental_days * daily_rental) + (prem_channels * prem_channel_fee)
return bill_amt
def business():
processing = 15
basic_service = 75
prem_channel_fee = 50
connections = int(input("Enter the number of basic service connections: "))
prem_channels = int(input("Enter the number of premium channels used: "))
if connections <= 10:
bill_amt = processing + basic_service + (prem_channels * prem_channel_fee)
else:
bill_amt = processing + basic_service + ((connections - 10) * 5) + (prem_channels * prem_channel_fee)
return bill_amt
if cust_type == "R" or cust_type == "r":
bill_total = residential()
else:
bill_total = business()
print("Account number: ", acct)
print("Amount due: ",bill_total)

Python print out float or integer

How can i print out float if the result have decimal or print out integer if the result have no decimal?
c = input("Enter the total cost of purchase: ")
bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
dbs1 = ((c/float(100))*10)
dbs2 = c-dbs1
ocbc1 = ((c/float(100))*15)
ocbc2 = c-ocbc1
if (c > 200):
if (bank == 'DBS'):
print('Please pay $'+str(dbs2))
elif (bank == 'OCBC'):
print('Please pay $'+str(ocbc2))
else:
print('Please pay $'+str(c))
else:
print('Please pay $'+str(c))
exit = raw_input("Enter to exit")
Example-Result
Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): OCBC
Please pay $212.5
Enter the total cost of purchase: 250
Enter the bank of your credit card (DBS, OCBC, etc.): DBS
Please pay $225.0
You can try this, which simply uses Python's string formatting method:
if int(c) == float(c):
decimals = 0
else:
decimals = 2 # Assumes 2 decimal places for money
print('Please pay: ${0:.{1}f}'.format(c, decimals))
This will give you the following output if c == 1.00:
Please pay: $1
Or this output if c == 20.56:
Please pay: $20.56
Python floats have a built-in method to determine whether they're an integer:
x = 212.50
y = 212.0
f = lambda x: int(x) if x.is_integer() else x
print(x, f(x), y, f(y), sep='\t')
>> 212.5 212.5 212.0 212
Since there is a much simpler way now and this post is the first result, people should now about it:
print(f"{3.0:g}") # 3
print(f"{3.14:g}") # 3.14
def nice_print(i):
print '%.2f' % i if i - int(i) != 0 else '%d' % i
nice_print(44)
44
nice_print(44.345)
44.34
in Your code:
def nice_number(i):
return '%.2f' % i if i - int(i) != 0 else '%d' % i
c = input("Enter the total cost of purchase: ")
bank = raw_input("Enter the bank of your credit card (DBS, OCBC, etc.): ")
dbs1 = ((c/float(100))*10)
dbs2 = c-dbs1
ocbc1 = ((c/float(100))*15)
ocbc2 = c-ocbc1
if (c > 200):
if (bank == 'DBS'):
print('Please pay $'+nice_number(dbs2))
elif (bank == 'OCBC'):
print('Please pay $'+nice_number(ocbc2))
else:
print('Please pay $'+nice_number(c))
else:
print('Please pay $'+nice_number(c))

Categories