![](/img/trans.png)
[英]If and elif statement are being ignored. Goes straight to the else statement Python
[英]First if statement being ignored by python but not elif's
python 的初学者在这里。 我正在尝试创建一个程序,该程序可以获取许多事物的总价格,并根据它们的最后一位数字将它们向上或向下舍入。 我的问题是我的第一个“if”语句总是被忽略,但我所有其他“elif”语句都可以正常工作
代码:
if str(finalTotalPrice).endswith("1" or "2") :
roundedDown = round(finalTotalPrice, 1)
print("Final Total = $" + str(roundedDown) + str(0))
print()
cashPayment = float( input("How much cash will you pay with? $"))
change = (cashPayment - roundedDown)
change = round(change, 3)
print("Your change is $" + str(change))
elif str(finalTotalPrice).endswith("8" or "9") :
roundedUp = round(finalTotalPrice, 1)
print("Final Total = $" + str(roundedUp) + str(0))
print()
cashPayment = float( input("How much cash will you pay with? $"))
change = (cashPayment - roundedUp)
change = round(change, 3)
print("Your change is $" + str(change))
elif str(finalTotalPrice).endswith("5" or "0") :
print("Final Total = $" + str(finalTotalPrice))
print()
cashPayment = float( input("How much cash will you pay with? $"))
change = (cashPayment - finalTotalPrice)
change = round(change, 3)
print("Your change is $" + str(change))
Python 不是自然语言。 and
和or
不按照你习惯的方式行事。 让我们看一下文档:
>>> help(str.endswith)
Help on method_descriptor:
endswith(...)
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
您的if
语句应如下所示:
if str(finalTotalPrice).endswith(("1", "2")):
正如tripleee所指出的,您实际上是在尝试在逻辑上做错事。
roundedDown = round(finalTotalPrice, 1)
这表明finalTotalPrice
是一个float
。 永远不要用花车赚钱。 它主要适用于小值,但总有一天事情会停止累加。 相反,请使用 integer 代表您拥有的最小面额的金额 - 在这里,您的美元看起来被分为 mils(您使用round(..., 3)
),所以一美元应该表示为1000
。
但是你还能用round
的function吗?
>>> help(round)
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
是的你可以; 只需输入-1
舍入到最接近的10
, -2
舍入到最接近的100
等。
str(finalTotalPrice).endswith("1" or "2")
暂时忽略这个错误,这是一个糟糕的解决方案。 如果您使用float
,它通常会给出完全错误的答案,如果您使用的是int
,则效率低下。 一旦你使用int
s,你可以解决这个问题; finalTotalPrice % 10
将获得最后一位, finalTotalPrice % 100
将获得最后两位,等等。然后你可以这样做:
if finalTotalPrice % 10 in (1, 2):
if finalTotalPrice % 10 > 7:
if finalTotalPrice % 5 == 0:
有必要的。
此外,您的现金支付代码在每个if
分支中都是相同的,因此应该写在它们之后,而不是在每个分支中。 而且,在我们这样做的同时,让我们让您的变量名称符合PEP 8、Python 样式指南,并改进输入处理:
import re
MONEY_REGEX = re.compile(r"[$]?(\d*)(?:\.(\d+))?")
def input_dollars(prompt="", places=3):
"""Input a dollar amount, returned as an integer.
The prompt string, if given, is passed to the input function.
The places argument determines how many decimal places are allowed.
The return value is shifted by that many decimal places,
so that it is an integer.
>>> input_dollars("prompt? ", places=2)
prompt? a
invalid input
prompt?
empty input
prompt? 0.
invalid input
prompt? $32
3200
>>> input_dollars("prompt? ", places=2)
prompt? 32.450
too many decimal places
prompt? 32.4
3240
>>> input_dollars("prompt? ", places=2)
prompt? .6
60
>>> input_dollars("prompt? ", places=4)
prompt? $.472
4720
"""
fix = 10 ** places
while True:
text = input(prompt)
match = MONEY_REGEX.fullmatch(text)
if match is None:
print("invalid input")
continue
integer, fractional = match.groups()
if fractional is None:
if len(integer) == 0:
print("empty input")
continue
return int(integer) * fix
if len(fractional) > places:
print("too many decimal places")
continue
ipart = int(integer) if integer else 0
fpart = int(fractional.ljust(places, '0'))
return ipart * fix + fpart
def format_dollars(dollars, places=3):
fix = 10 ** places
return "${}.{:0>{}}".format(dollars // fix, dollars % fix, places)
def print_final_total(final_total, places=3):
print("Final Total =", format_dollars(final_total, places))
print()
final_total_price = input_dollars("What's the final total price? ")
if final_total_price % 10 in (1, 2, 8, 9):
print_final_total(round(final_total_price, -2))
elif final_total_price % 5 == 0:
print_final_total(final_total_price)
cash_payment = input_dollars("How much cash will you pay with? $")
change = cash_payment - final_total_price
print("Your change is", format_dollars(change))
这段代码可能不会做你想做的事。 但是,那么,您的原件也没有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.