Python print out float or integer - python

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

Related

Expected expression ATM

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

How to print Congrats with out the error in python

The program goes as follows, asks to choose a product, then asks for the amount of the choice, then the user inputs the amount, but if the amount is different from the declared values (mo), the program prints "wrong coins", but when the user inputs the correct coin and amount, it should print only the "change" part of the code. In my program, it prints "change" and then wrong coin value
prod = ["Coffe", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
mo = [0.1, 0.2, 0.5, 1, 2, 5, 10]
item_number = len(prod)
print("\nPick an item:")
for number in range(0, item_number, 1):
print(number + 1,
prod [number],
'{0:.2f}€'.format(cost[number]))
print ("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) -1
if choice < item_number and choice >= 0:
print("You should input", "{0:.2f}€".format(cost[choice]), 'in total')
else:
print("Exiting the program")
exit(0)
money = float(input("How much do you enter?; "))
while money < cost[choice]:
money += float(input("You should insert "+str("{:.2f}".format(cost[choice] - money))))
if money != mo:
print("Invalid amount.\nPlease enter a valid coin: 0.1 / 0.2 / 0.5 / 1 / 2 / 5 / 10")
else:
print("Try again")
change = money - cost[choice]
print("Change {0:.2f}€".format(change))
The logic may be different
continuously ask for money (a while True allow to write the input once)
verify if the choosen is in the list not equal (a float can't be equal to a list)
increment your total money
stop if you have enough
money = 0
while True:
new_money = float(input(f"You should insert {cost[choice] - money:.2f}: "))
if new_money not in mo:
print("Invalid amount.\nPlease enter a valid coin: " + "/".join(map(str, mo)))
continue
money += new_money
if money >= cost[choice]:
break
change = money - cost[choice]
print(f"Change {change:.2f}€")
The other code, with some improvments
print("\nPick an item:")
for number in range(item_number, ):
print(f'{number + 1} {prod[number]} {cost[number]:.2f}€')
print("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) - 1
if 0 < choice <= item_number:
print(f"You should input {cost[choice]:.2f}€", 'in total')
else:
print("Exiting the program")
exit(0)

Nested loop code error free, not executing

I have this code and it doesn't run at all. It is a list of objects, and each object has a two dimensional list in it. It is not executing the code to even display just the flightNo element. I've made a method to display the 2d list in the object, but nothing happens. I tested with a simple print('Hello') at the end and that does work. Can someone tell me what could be wrong here?
EDIT: Full code at: https://onlinegdb.com/HJPqXWXWU
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
I have also tried a different method to display flightNo, no execution again:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()
Here is the working code that I modified the location of calling the method and assigning to the variable because every time we have to create a new instance of the class to save data properly and we should not clear the list that's why I changed the position outside of the loop. And this I working properly. for my basic testing. I can improve if you need. and kept your code in the comment's so you can see the change.
import sys
class Flight:
def __init__(self):
self.flightNo = "None"
self.planeType = "None"
self.destination = "None"
self.w = self.h = 0
self.seats = [["None" for x in range(self.w)] for y in range(self.h)]
self.depDate = "None"
self.depTime = "None"
self.eta = "None"
self.ticketsSold = 0
self.pricePerTicket = 0.0
def displayDetails(self):
print('Flight No: ', self.flightNo,
'\nPlane Type: ', self.planeType,
'\nDestination: ', self.destination,
'\nDeparture Date: ', self.depDate,
'\nDeparture Time: ', self.depTime,
'\nETA: ', self.eta,
'\nTickets Sold: ', self.ticketsSold,
'\nPrice: ', self.pricePerTicket, '\n\n')
def totalSales(self):
return print("Total number of tickets sold: ", self.ticketsSold,
"\nTotal sales: ", (self.ticketsSold * self.pricePerTicket))
def buyTicket(self, quantity):
quantity = int(input("Enter number of tickets required: "))
cost = quantity * self.pricePerTicket
for v in range(len(self.seats)):
for j in range(len(self.seats[v])):
if quantity > len(self.seats) * len(self.seats[v]):
print("Lessen the number of tickets")
break
if self.seats[v][j] == "\\__/":
self.seats[v][j] = "\\AA/"
quantity -= 1
if quantity == 0:
break
if quantity == 0:
break
print(quantity, "tickets bought for $", cost,
"\nSeats assigned", )
self.ticketsSold += quantity
# one = Flight()
ans = True
FlightList = []
while ans:
print("----------------------------- \n1. Add a flight \n2. Remove a flight \n3. Sell Tickets",
"\n4. Display seat info \n5. Display total sales for flight \n6. Display flight info",
"\n7. Display all flight's info \n0. Quit")
a = int(input("Enter number: "))
#FlightList = []
if a == 1:
one = Flight()
one.flightNo = input('Enter flight number: ')
one.planeType = input('Enter plane type: ')
one.destination = input('Enter destination: ')
one.w = int(input('Enter number of columns in flight: '))
one.h = int(input('Enter number of rows in flight: '))
one.seats = [["\\__/" for x in range(one.w)]
for y in range(one.h)]
one.depDate = input('Enter departure date: ')
one.depTime = input('Enter departure time: ')
one.eta = input('Enter ETA: ')
one.ticketsSold = int(input('Enter number of tickets sold: '))
one.pricePerTicket = float(input('Price: '))
FlightList.append(one)
elif a == 2:
rem = input('Enter flight number to remove: ')
for i in FlightList:
if i.flightNo == rem:
del FlightList[FlightList.index(i)]
elif a == 3:
for i in range(len(FlightList)):
print(FlightList[i].flightNo)
req = input('Enter flight number to buy tickets: ')
for Flight in FlightList:
if Flight.flightNo == req:
for a in range(len(Flight.seats)):
for b in range(len(Flight.seats[a])):
print(Flight.seats[a][b], end=" ")
print()
qty = int(input('Enter number of tickets'))
Flight.buyTicket(one, qty)
print("Hello")
elif a == 4:
for Flight in FlightList:
print(Flight.flightNo)
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
for a in range(len(i.seats)):
for b in range(len(i.seats[a])):
print(i.seats[a][b], end=" ")
print()
elif a == 5:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.totalSales()
elif a == 6:
re4 = input('Enter flight number to view seats: ')
for i in FlightList:
if i.flightNo == re4:
i.displayDetails()
elif a == 7:
for item in FlightList:
item.displayDetails()
elif a == 0:
sys.exit(0)

How do format my output to 2 decimal places in 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

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)

Categories