Im trying to use short circuit in Python to print some data but my float didnt appear with 2 number after the dot despite i wrote .2f
((DidHourPlus == 1) and (StartWeek == 1) and (post == "r") and print("The daily salary is %2.f" % ((hours - 8) * 35 + 8 * 30)))
((DidHourPlus == 1) and (StartWeek == 1) and (post == "s") and print("The daily salary is %2.f" % (1.20*((hours - 8) * 35 + 8 * 30))))
((DidHourPlus == 1) and (StartWeek == 1) and (post == "m") and print("The daily salary is %2.f" % (1.50*((hours - 8) * 35 + 8 * 30))))
This is a misuse of short-circuiting. Don't use and
this way. Use if
statements.
For two decimal places put the 2
after the decimal place: %.2f
not %2.f
.
if DidHourPlus == 1 and StartWeek == 1 and post == "r": print("The daily salary is %.2f" % ((hours - 8) * 35 + 8 * 30)))
if DidHourPlus == 1 and StartWeek == 1 and post == "s": print("The daily salary is %.2f" % (1.20*((hours - 8) * 35 + 8 * 30)))
if DidHourPlus == 1 and StartWeek == 1 and post == "m": print("The daily salary is %.2f" % (1.50*((hours - 8) * 35 + 8 * 30)))
You can extract the repeated tests into a single if
:
if DidHourPlus == 1 and StartWeek == 1:
if post == "r": print("The daily salary is %.2f" % ((hours - 8) * 35 + 8 * 30)))
if post == "s": print("The daily salary is %.2f" % (1.20*((hours - 8) * 35 + 8 * 30)))
if post == "m": print("The daily salary is %.2f" % (1.50*((hours - 8) * 35 + 8 * 30)))
Then extract the printout:
if DidHourPlus == 1 and StartWeek == 1:
salary = None
if post == "r": salary = (hours - 8) * 35 + 8 * 30
if post == "s": salary = 1.20*((hours - 8) * 35 + 8 * 30)
if post == "m": salary = 1.50*((hours - 8) * 35 + 8 * 30)
if salary:
print("The daily salary is %.2f" % salary)
Then extract the salary calculation:
if DidHourPlus == 1 and StartWeek == 1:
rate = None
if post == "r": rate = 1.00
if post == "s": rate = 1.20
if post == "m": rate = 1.50
if rate:
salary = rate * ((hours - 8) * 35 + 8 * 30)
print("The daily salary is %.2f" % salary)
You could stop there, but if you want to get even fancier you could lookup the rates in a dictionary.
if DidHourPlus == 1 and StartWeek == 1:
rates = {"r": 1.00, "s": 1.20, "m": 1.50}
rate = rates.get(post)
if rate:
salary = rate * ((hours - 8) * 35 + 8 * 30)
print("The daily salary is %.2f" % salary)
In Python 3.8 you can tighten it up even further with an assignment expression.
if DidHourPlus == 1 and StartWeek == 1:
rates = {"r": 1.00, "s": 1.20, "m": 1.50}
if rate := rates.get(post):
salary = rate * ((hours - 8) * 35 + 8 * 30)
print("The daily salary is %.2f" % salary)