简体   繁体   English

我在这个脚本中使用 if / then 有什么问题?

[英]What's wrong with my use of if / then in this script?

I'm learning if and then statements.我正在学习 if 和 then 语句。 I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)我正在尝试编写接受任何十进制数输入(如 2、3 甚至 5.5)并打印输入是偶数还是奇数的代码(取决于输入是否实际上是 integer。)

I get an error in line 8第 8 行出现错误

#input integer / test if any decimal number is even or odd

inp2 = input("Please enter a number: ")

the_number = str(inp2)

if "." in the_number:
    if int(the_number) % 1 == 0
        if int(the_number) % 2 == 0:
            print("Your number is even.")
        else:
            print("Your number is odd.")
    else:
        print("You dum-dum, that's not an integer.")
else:
    the_number = int(inp2)
    if the_number % 2 == 0:
        print("Your number is even.")
    else:
        print("Your number is odd.")

I'm just starting with python so I appreciate any feedback.我刚从 python 开始,所以我很感激任何反馈。

You have to include a colon at the end of second if statement, like you did in your other conditional statements.您必须在第二个 if 语句的末尾包含一个冒号,就像您在其他条件语句中所做的那样。

if int(the_number) % 1 == 0:

Next time, give a closer look at the error message.下次,请仔细查看错误消息。 It'll give you enough hints to fix it yourself, and that's the best way to learn a language.它会给你足够的提示来自己修复它,这是学习一门语言的最好方法。

EOL.停产。

You forgot a : .你忘了一个: Line 8 should read if int(the_number) % 1 == 0: . if int(the_number) % 1 == 0: ,则第 8 行应读取。

Try putting the: at the end of the if statement if int(the_number) % 1 == 0:尝试将:放在 if 语句的末尾 if int(the_number) % 1 == 0:

You can test your input as following code snippet您可以按照以下代码片段测试您的输入


num = input('Enter a number: ')

if num.isnumeric():
    print('You have entered {}'.format(num))
    num = int(num)
    if num%2:
        print('{} is odd number'.format(num))
    else:
        print('{} is even number'.format(num))
else:
    print('Input is not integer number')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM