在python条件语句中使用模运算符

时间:2014-02-18 04:33:33

标签: python modulus

当我运行代码时,它给了我一个错误:在字符串格式化过程中没有转换所有参数

year = raw_input( "Please enter a year" )

if year % 4 == 0 && year % 100 != 0:
    print ( "{0} is a leap year", year )
elif year % 4 == 0 && year % 100 == 0 && year % 400 == 0:
    print ( "{0} is a leap year", year )
else:
    print ( "{0} is not a leap year", year )

4 个答案:

答案 0 :(得分:4)

因为raw_input返回一个字符串,所以

year % 4 

尝试执行string format操作,该操作与模数共享相同的运算符%

您需要使用int()将输入转换为整数。

此外,正如thefourtheye提到的那样,boolean AND operatorand,而非&&,就像C使用的那样。

所以:

while True:
    # Prompt the user until they give a valid integer.
    year = raw_input( "Please enter a year" )
    try:
        year = int(year)
        break
    except ValueError:
        pass

if (year % 4 == 0) and (year % 100 != 0):
    print "{0} is a leap year".format(year)
elif (year % 4 == 0) and (year % 100 == 0) and (year % 400 == 0):
    print "{0} is a leap year".format(year)
else:
    print "{0} is not a leap year".format(year)

使用format()注意正确的字符串格式。

答案 1 :(得分:3)

  1. raw_input的结果始终是一个字符串,您需要将它们显式转换为您想要的类型

    year = int(raw_input( "Please enter a year" ))
    
  2. 在Python中,条件和运算符用and而非&&表示。

    if year % 4 == 0 and year % 100 != 0:
    ...
    elif year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
    ...
    
  3. 并且,当您使用{0}时,您应该使用.format,就像这样

    print ( "{0} is a leap year".format(year) )
    ...
    print ( "{0} is a leap year".format(year) )
    ...
    print ( "{0} is not a leap year".format(year) )
    

答案 2 :(得分:1)

raw_input的输出将是一个字符串;当你使用%运算符,并且第一个操作数是一个字符串时,它会string formatting,而不是模数。 (与year % 4中一样,year是一个字符串,因为它是raw_input的输出。)

简而言之,您希望year成为一个数字。你需要这样的东西:

year = int(year)

答案 3 :(得分:1)

更改

year = raw_input( "Please enter a year" )

为:

year = int(raw_input( "Please enter a year" ))

并将每个&&替换为and

year = int(raw_input( "Please enter a year" ))

if year % 4 == 0 and year % 100 != 0:
    print ( "{0} is a leap year", year )
elif year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
    print ( "{0} is a leap year", year )
else:
    print ( "{0} is not a leap year", year )