我需要解释简单的“if”语句?

问题描述 投票:-1回答:2

我在学习if语句。我写了这段代码然后运行它。似乎第2和第3行被忽略了。当我输入一个低于45的数字时,它会提示第2行和第3行。我希望你理解我的意思。

price = input('How much did your taxi ride cost?:')
if price < 45:
  print('Processing')
if price > 45:
      response = ('Your taxi cost over $45 you will be charged a $5.00 fee')
      print(response)
      response = input('Would you like to proceed:')
      if response == 'yes': 
        print('Processing...')
if response == 'no':
    print('!Error!')
python if-statement
2个回答
1
投票

TL; DR:使用int()函数将输入转换为数字

price = int(input('How much did your taxi ride cost?:'))

答案很长

通常,当代码中的某些内容没有达到预期效果时,您应该根据代码为您提供的信息找出可能导致内容的原因。一种方法是在评估if语句之前尝试打印if子句!例如,你可以尝试,就在if之前:

print(input < 45)

你说你的if块被忽略了。这可能意味着它的测试正在返回一个虚假的价值! if的工作方式是,当且仅当if:之间的任何内容评估为真正的价值时,它才会执行它的块(真实性因语言而异,但True / true / YES / etc-无论你的语言使用哪种 - 绝对是真的) 。


对于你的具体情况,你问“price严格小于45?”,你的if语句是nah,所以它不会执行。原因是input()函数返回一个字符串而不是一个数字,因此将它与45进行比较意味着您将文本与数字进行比较。 See this question to see how that works in Python

CPython实现细节:除了数字之外的不同类型的对象按其类型名称排序;不支持正确比较的相同类型的对象按其地址排序。

要解决您的问题,请在将字符串结果与另一个数字进行比较之前将其转换为数字(在本例中为整数)。你可以通过在int()的结果上调用input()函数来做到这一点,例如:

price = int(input('How much did your taxi ride cost?:'))

0
投票

使用ifelif语句。

if语句的正确用法是

if

然后:

elif你可以拥有尽可能多的elif ...

然后最后,如果没有匹配。

else

您可以使用int或'float`,具体取决于要在用户输入中使用的数字类型,否则它将返回一个字符串。

int是一个整数,即1,2,3和float可以采用小数,即1.5,2.3,3.5

对于这个答案,我使用了浮动。

price = float(input('How much did your taxi ride cost?:'))
if price < 45:
  print('Processing')
elif price > 45:
    response = ('Your taxi cost over $45 you will be charged a $5.00 fee')
    print(response)
    response = input('Would you like to proceed:')
    if response == 'yes': 
        print('Processing...')
    elif response == 'no':
        print('!Error!')
© www.soinside.com 2019 - 2024. All rights reserved.