Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using modulus operator in a python conditional statement

Tags:

python

modulus

When i run the code, it gives me an error: not all arguments converted during string formatting

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 )
like image 319
MrPickle5 Avatar asked Feb 04 '26 23:02

MrPickle5


1 Answers

Because raw_input returns a string, the line

year % 4 

Is trying to perform a string format operation, which shares the same operator % as modulus.

You need to convert your input to an integer, with int().

Also, as thefourtheye mentioned, the boolean AND operator is and, not && like C uses.

So:

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)

Note the correct string formatting, using format() as well.

like image 93
Jonathon Reinhart Avatar answered Feb 07 '26 13:02

Jonathon Reinhart