3

这是我在介绍性编程课程的第二天,我遇到了麻烦。我们在 if 语句上。作业是

编写一个程序,提示用户输入一个整数(您可以假设输入的值是一个整数)。如果该整数等于零,则打印“零”。如果不是,请确定它是正面的还是负面的,并打印出它是哪一个。此外,确定该数字是否能被 5 整除。

现在我可以提示用户输入一个数字并确定它是正数还是负数,或者它是否可以被 5 整除,但我不知道如何让程序绕过未满足的第一个条件并进入第二组条件,下面是我的代码示例,

number = input("enter an integer: ")

if number > 0 and number%5 == 0:
    print number, "is positive and divisible by 5"
else :
    print "positive but not divisible by 5"

if number < 0 and number%5== 0:
    print "neggy and divisible by 5"
else :
    print "neggy but not divisible by 5"

我的问题是,当我输入负数时,它会打印“正数但不能被 5 整除”,因为第一个条件不满足。我试过 elif 但我每次都遇到语法错误,求助?请不要幻想,因为我的老师只想要基本的“and”,“or”,“if”,“else”和“elif”,使用的词。谢谢

4

5 回答 5

6

使用 elif:

number = input("enter an integer: ")

if number > 0 and number%5 == 0:
    print number, "is positive and divisible by 5"
elif number > 0:
    print "positive but not divisible by 5"
elif number < 0 and number%5== 0:
    print "neggy and divisible by 5"
elif number < 0:
    print "neggy but not divisible by 5"
else:
    print "zero"
于 2013-09-09T23:59:19.927 回答
1
于 2013-09-10T00:26:33.017 回答
1

最好使用if ... elif ... else,但无论如何,我正在抛出另一个选项:

if number == 0:
    print 'zero'
else:
    print number, 'is', 'positive' if number > 0 else 'negative', 'and',
    print 'not' if number % 5 else '', 'divisible by 5'

解释... 这利用了printPython 2 中的语句可以采用逗号分隔的多个值的方式,并显示以空格分隔的值;它使用条件表达式,允许您重写(例如)

if condition:
    print 'yes'
else:
    print 'no'

作为

print 'yes' if condition else 'no'

但不是很推荐,因为它们通常会使代码的可读性降低。

于 2013-09-10T00:19:12.930 回答
0
if number == 0:
    print "zero"
else:

    pos = (number > 0 )
    div_by_5 = (number % 5 == 0)

    if pos and div_by_5:
        print number, "is positive and div by 5"
    elif pos and not div_by_5:
        print number, "is positive but not div by 5"
    elif not pos and div_by_5:
        print number, "is negative and div by 5"
    elif not pos and not div_by_5:
        print number, "is negative but not div by 5"
于 2013-09-10T00:05:38.377 回答
0

Python 2.7.4

number = int(raw_input())

if not number: print "zero"
elif abs(number) % 5 == 0:
    print [ `number` + " is negative and divisible by 5", 
        `number` + " is positive and divisible by 5"][number > 0]
else: print [ `number` + " is negative but not divisible by 5", 
        `number` + " is positive but not divisible by 5"][number > 0]

反引号

于 2013-09-10T00:14:33.550 回答