Python比较

时间:2017-09-11 16:19:40

标签: python comparison

我想创建一个脚本,要求用户输入一个数字。如果数字更小/更大/相等,则用户获得不同的消息。我对此很陌生,我无法弄清楚为什么我的脚本无效。

 def Comparator(num):

    num = input("Enter a number")

if (num == 10)

    print("The number you entered is 10!)

elif num < 10

    print("The number you entered is smaller than 10!)

else num > 10

    print("The number you entered is bigger than 10!) 

5 个答案:

答案 0 :(得分:0)

我相信您的问题是input会返回键盘输入的字符串。如果你只是将其转换为int,它应该可以解决。你也错过了我为你添加的一些引号和分号。第三,既然你在数字等于10时处理,当它小于10时,一切都大于10,所以你可以使用else

num = int(input("Enter a number"))

if (num == 10):
    print("The number you entered is 10!")

elif num < 10:
    print("The number you entered is smaller than 10!")

else:
    print("The number you entered is bigger than 10!") 

答案 1 :(得分:0)

  1. 每个:if后需要冒号(elif)。
  2. 你需要用另一个双引号来结束你的字符串。
  3. 您的标签需要保持一致,每个代码级别一个缩进。
  4. 其他情况没有条件。
  5. 输入返回一个字符串,因此您需要在检查之前将其强制转换为int
  6. 以下是一个示例修复:

    def Comparator(num):
        num = int(input("Enter a number"))
        if (num == 10):
            print("The number you entered is 10!")
        elif num < 10:
            print("The number you entered is smaller than 10!")
        else:
            print("The number you entered is bigger than 10!") 
    

答案 2 :(得分:0)

所以你可以通过输入用户提供的内容并将其转换为int来实现。请查看下面的示例代码,希望您能理解。

    num = input("Enter number: ")
    val = int(num)
    if num > 10:
        print("The number you entered is bigger than 10!")

答案 3 :(得分:0)

ifelseforwhile以及无数其他内容需要以冒号(:)结尾。

您的代码应该是这样的。

num = int(input("Enter a number"))

如果您不添加int,则该数字将存储为字符串,当您尝试将其与稍后的整数(如10)进行比较时,它将始终返回false。

if num == 10:
    print("The number you entered is 10")
elif num < 10:
    print("the number you entered is smaller than 10")
else:
    print("The number you entered is more than 10")

答案 4 :(得分:0)

def Compare(value):
    if value == 10:
        #Returns the value the user entered in the answer
        print ('The number you entered ' + str(value) + ' is 10!')
    elif value < 10:
        #Returns the value the user entered in the answer
        print ('The number you entered ' + str(value) + ' is 10!')
    else:
        #Returns the value the user entered in the answer
        print ('The number you entered ' + str(value) + ' is bigger than 10!')

Compare(int(input("Enter a number: ")))
相关问题