【问题标题】:Why is the 'if statement' getting ignored?为什么“if 语句”被忽略?
【发布时间】:2019-10-06 17:30:03
【问题描述】:
print("10 apples on a tree")
userChoice = input("Would you like to change the amount on apples ([Y]/[N]): ")

if userChoice == 'Y':
appleAmount = input("Please enter the amount of apples: ")

if appleAmount == 1:
    print("1 apple on a tree")
else:
    print(appleAmount, "apples on a tree")

if userChoice == 'N':
print("Okay.")

每当我运行我的代码并输入“1”时。它打印出“树上的 1 个苹果”,而不是我写的“树上的 1 个苹果”。努力找出问题所在。

我的目标是,允许用户修改苹果的数量。如果他们决定输入“1”,则“apples”一词需要更改为“apple”。

我用谷歌搜索了一下,每个人都是这样做 if 语句的,但肯定有什么地方出了问题,或者我错过了什么。

【问题讨论】:

  • input() 返回一个字符串值。字符串"1" 与整数1 不同。

标签: python if-statement printing


【解决方案1】:

因为有缩进,appleAmount 的类型也应该是int

print("10 apples on a tree")
userChoice = input("Would you like to change the amount on apples ([Y]/[N]): ")

if userChoice == 'Y':
    appleAmount = int(input("Please enter the amount of apples: "))

if appleAmount == 1:
    print("1 apple on a tree")
else:
    print(appleAmount, "apples on a tree")

if userChoice == 'N':
    print("Okay.")

【讨论】:

    【解决方案2】:

    实际上,我认为这是因为您检查的是整数 1 而不是字符串 "1"input() 的返回值是字符串,因此要么将它们更改为整数进行比较,要么在这种情况下与 1 的字符串版本进行比较:

    print("10 apples on a tree")
    userChoice = input("Would you like to change the amount on apples ([Y]/[N]): ")
    
    if userChoice == 'Y':
        appleAmount = input("Please enter the amount of apples: ")
    
    if appleAmount == "1":
        print("1 apple on a tree")
    else:
        print(appleAmount, "apples on a tree")
    
    if userChoice == 'N':
        print("Okay.")
    

    【讨论】:

      【解决方案3】:

      改变这个:

      if appleAmount == 1:

      到这里:

      if int(appleAmount) == 1:

      input() 返回一个字符串,这就是 if 语句不起作用的原因。

      【讨论】:

        猜你喜欢
        • 2015-08-13
        • 2014-03-04
        • 1970-01-01
        • 2020-03-05
        • 1970-01-01
        • 1970-01-01
        • 2018-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多