2017-09-11 31 views
-2

我想创建一个脚本,要求用户输入一个数字。如果数字越小/越大/相等,则用户得到不同的消息。我对此非常陌生,我无法弄清楚为什么我的脚本无法正常工作。Python比较

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!) 
+4

请检查巨蟒的语法,你是不是结束你的打印语句用“,也不是你的缩进Python代码,你可能想看看蟒蛇教程 –

回答

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!") 
0
  1. 你需要每个ifelif后冒号(:)。
  2. 你需要用另一个双引号结束你的字符串。
  3. 您的制表符需要保持一致,每个代码级缩进一次。
  4. 其他情况没有条件。
  5. 输入返回一个字符串,因此您需要在检查之前将其转换为int

下面是一个例子修复:

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!") 
0

所以,你可以通过采取哪些用户给出了输入并将其转换成INT做到这一点。检查下面的示例代码,希望你能理解。

num = input("Enter number: ") 
    val = int(num) 
    if num > 10: 
     print("The number you entered is bigger than 10!") 
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") 
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: "))) 
+0

尽管此代码可以回答这个问题,提供关于为什么和/或代码如何回答这个问题的附加背景提高了它的长期价值。 –