The function is supposed to receive a number representing a year, and then print if it's a leap year or not.
def isItALeapYear(year):
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
The program works, the only thing I can't get right is that it is supposed to notify you if anything that it's not a number is being used as an argument. I've tried both the isinstance() function, as well as writing what I want as year != int. And then year == None in the hopes of making it work in case anything nondefined is used as an argument.
I read this post with the exact same error: TypeError: not all arguments converted during string formatting python
But I'm not intending to format anything with the % symbol
As far as I'm concerned the % can be used as an operand to get the residue of a division.
So in this case I'm using it to figure out if a year is a leap year or not by asking if the residue is 0 when divided by 4. I'm pretty stuck, and the sad thing is the error comes up in the very first "if", so I can't really know if the last lines for excluding any non int type argument work or not. Any help would be really appreciated!
You could use the isleap() function from the standard library (module calendar):
from calendar import isleap
def isItALeapYear(year):
if not isinstance(year, int):
print("Please provide a number")
elif isleap(year):
print("That is a leap year!")
else:
print("That is not a leap year...")
I recommend to divide the functionality of checking the number from returning the output as well as from receiving the input.
def is_multiple_of_four(number: int):
if number % 4 == 0:
return True
else:
return False
if __name__ == '__main__':
user_input = ""
while not user_input.isdigit():
user_input = input("Please type in a year: ")
if is_multiple_of_four(int(user_input)):
print("That is a leap year!")
else:
print("That is not a leap year.")
Here you can see the function that checks the number does only that, it checks the number if it's modulo of 4 equals 0.
In the script outside the function you can retrieve the user input for as long as it takes to get a valid numeric and return the output in respect of the functions results.
Edit (adding clarification asked in the comments)
The first condition if __name__ == '__main__' is quiet common in python. It's not necessary for your function, but I like using it in answers if people seem to learn Python, so they don't miss out on it. Here is a question with a good answer: What does if __name__ == "__main__": do?
The short answer in the accepted answer is enough to understand why you might want to use it.
The second condition
user_input = ""
while not user_input.isdigit():
first defines a variable user_input with an arbitrary non-digit String value and than uses the negated isdigit() method of the String class on it as condition. Therefor the while loop gets entered in the beginning, as the arbitrary value is not an digit. From then on the value will be re-assigned with user input until it holds an actual digit. This digit is still a String however.
First thing while loop in the function makes no sense you can remove it(If you want).
There are multiple ways to do that I will show.
First One.
def isItALeapYear(year):
if type(year) != int:
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
Another is.
def isItALeapYear(year):
try:
int(year)
except ValueError: # this line of code executes when the year is not the int
return # here return to exit the function
while True:
if year % 4 == 0:
print("That is a leap year! ")
break
elif year % 4 != 0:
print("That is not a leap year...")
break
elif not isinstance(year, int) or year == None:
print("Please enter a number...")
break
I know there are more ways to do that but these are the best ones (I Think).
Your function is not accurate then you can use this one.
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
Edit For Quetioner
def isItALeapYear(year):
if type(year) != int:
return
if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
print(f"{year} is a Leap Year")
else:
print(f"{year} is Not the Leap Year")
try:
isItALeapYear(asdasd)
except NameError:
print("You give the wrong Value")
I am trying to create a function that accepts a users input and tries to figure out whether the year is a leap year and later also accept the users day of year (i.e. 355) and turns it into which day of the year it is (and output December, 10 2018). But for now I am not sure why it will not output whether the year is True or False. I tried to use the int parameter to change the user input from a string to a number but I am not sure if that is where I went wrong.
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")
You're only defining the function leap_year but you're never calling it, below is an example where it actually gets called:
user_year = input('Enter year: ')
val = int(user_year)
def leap_year(val):
if val % 400 == 0:
print ("True")
if val % 100 == 0:
print ("False")
if val % 4 == 0:
print ("True")
else:
print ("False")
leap_year(val)
Also your indentation is a bit off, which causes it to not compile in the first place, but that could also be an error while copying to Stackoverflow.
The last section of the code does not do what I want it to do. It should be true if checkdigit is the same as validdigit, so it should print 'The GTIN-8 Code is valid' if not it should say 'The GTIN-8 is not valid'
gtin = input('Enter a GTIN-8 Code: ')
if len(gtin) == 8 and gtin.isdigit() == True:
print ('Comparing')
else:
print ('Error, 8 digits have not been inputted and/or letters were inputted')
gtinlist = list(gtin)
print (gtinlist) # not needed
checkdigit = gtinlist[7]
print ('This is the check digit given: '+str(checkdigit))
no1 = int(gtinlist[0])*3
no2 = int(gtinlist[1])*1
no3 = int(gtinlist[2])*3
no4 = int(gtinlist[3])*1
no5 = int(gtinlist[4])*3
no6 = int(gtinlist[5])*1
no7 = int(gtinlist[6])*3
print (no1,no2,no3,no4,no5,no6,no7) # not needed
added = (no1+no2+no3+no4+no5+no6+no7)
print (added) #not needed
m = (added + 9) // 10 * 10
validdigit = m - added
print (validdigit)
print (checkdigit)
if (validdigit)==(checkdigit)==True:
print('This GTIN-8 Code is valid')
else:
print('This GTIN-8 Code is not valid')
Verify the data types in your equality check.
If you change the print lines near the end to:
print validdigit, type(validdigit)
print checkdigit, type(checkdigit)
You will see that one is a string and one is an integer.
Comparing these data types will always result in False. There is no implicit type conversion for int vs. str. In other words, '8' != 8 in Python. Convert one to int or the other to str and you'll be fine.
Test that the year passed is greater than or equal to 1582.
def gregyear():
try:
year =raw_input("Pick a year greater than or equal to 1582. It has to be divisible by four.)\n")
year =float(year)
leapyear = "Yes"
except:
print "please, only numbers"
else:
year =float(year)
if year >= 1582:
if year % 4:
print year
leapyear= "Yes"
else:
leapyear= "No"
else:
print "Wrong... print a year greater than 1582"
return leapyear
gregyear()
print "leapyear is "+ leapyear +"."
First, in Python, 0 is falsey, and all other numbers are truthy. So, when you do this:
if year % 4:
… that will trigger if year % 4 is anything except 0, meaning if the year is not divisible by 4. So your logic is backward.
Second, while gregyear does return a value, you ignore that return value If you want to use it, you have to store it:
leapyear = gregyear()
Third, you can't add strings to numbers, so this will raise a TypeError:
print "leapyear is "+ leapyear +"."
What you probably wanted is to either pass the strings and number to print to magically concatenate together while printing, like this:
print "leapyear is", leapyear, "."
Notice that I removed the extra spaces, because print with commas automatically puts spaces between its arguments.
However, a better way to write this is with string formatting:
print "leapyear is {}.".format(leapyear)
As a side note, you're also missing the rule that makes 1700, 1800, and 1900 not leap years (while 1600 and 2000 are).
In python, is there a difference between say:
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
and
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
Just wondering if multiple ifs could cause any unwanted problems and if it would be better practice to use elifs.
Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions..
An other easy way to see the difference between the use of if and elif is this example here:
def analyzeAge( age ):
if age < 21:
print "You are a child"
if age >= 21: #Greater than or equal to
print "You are an adult"
else: #Handle all cases where 'age' is negative
print "The age must be a positive integer!"
analyzeAge( 18 ) #Calling the function
>You are a child
>The age must be a positive integer!
Here you can see that when 18 is used as input the answer is (surprisingly) 2 sentences. That is wrong. It should only be the first sentence.
That is because BOTH if statements are being evaluated. The computer sees them as two separate statements:
The first one is true for 18 and so "You are a child" is printed.
The second if statement is false and therefore the else part is
executed printing "The age must be a positive integer".
The elif fixes this and makes the two if statements 'stick together' as one:
def analyzeAge( age ):
if age < 21 and age > 0:
print "You are a child"
elif age >= 21:
print "You are an adult"
else: #Handle all cases where 'age' is negative
print "The age must be a positive integer!"
analyzeAge( 18 ) #Calling the function
>You are a child
Edit: corrected spelling
def multipleif(text):
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
def eliftest(text):
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
text = "sometext"
timeit multipleif(text)
100000 loops, best of 3: 5.22 us per loop
timeit eliftest(text)
100000 loops, best of 3: 5.13 us per loop
You can see that elif is slightly faster. This would be more apparent if there were more ifs and more elifs.
Here's another way of thinking about this:
Let's say you have two specific conditions that an if/else catchall structure will not suffice:
Example:
I have a 3 X 3 tic-tac-toe board and I want to print the coordinates of both diagonals and not the rest of the squares.
I decide to use and if/elif structure instead...
for row in range(3):
for col in range(3):
if row == col:
print('diagonal1', '(%s, %s)' % (i, j))
elif col == 2 - row:
print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))
The output is:
diagonal1 (0, 0)
diagonal2 (0, 2)
diagonal1 (1, 1)
diagonal2 (2, 0)
diagonal1 (2, 2)
But wait! I wanted to include all three coordinates of diagonal2 since (1, 1) is part of diagonal 2 as well.
The 'elif' caused a dependency with the 'if' so that if the original 'if' was satisfied the 'elif' will not initiate even if the 'elif' logic satisfied the condition as well.
Let's change the second 'elif' to an 'if' instead.
for row in range(3):
for col in range(3):
if row == col:
print('diagonal1', '(%s, %s)' % (i, j))
if col == 2 - row:
print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))
I now get the output that I wanted because the two 'if' statements are mutually exclusive.
diagonal1 (0, 0)
diagonal2 (0, 2)
diagonal1 (1, 1)
diagonal2 (1, 1)
diagonal2 (2, 0)
diagonal1 (2, 2)
Ultimately knowing what kind or result you want to achieve will determine what type of conditional relationship/structure you code.
elifis just a fancy way of expressing else: if,
Multiple ifs execute multiple branches after testing, while the elifs are mutually exclusivly, execute acutally one branch after testing.
Take user2333594's examples
def analyzeAge( age ):
if age < 21:
print "You are a child"
elif age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
could be rephrased as:
def analyzeAge( age ):
if age < 21:
print "You are a child"
else:
if age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
The other example could be :
def analyzeAge( age ):
if age < 21:
print "You are a child"
else: pass #the if end
if age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
In your above example there are differences, because your second code has indented the elif, it would be actually inside the if block, and is a syntactically and logically incorrect in this example.
Python uses line indentions to define code blocks (most C like languages use {} to enclose a block of code, but python uses line indentions), so when you are coding, you should consider the indentions seriously.
your sample 1:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
both if and elif are indented the same, so they are related to the same logic.
your second example:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
elif is indented more than if, before another block encloses it, so it is considered inside the if block. and since inside the if there is no other nested if, the elif is being considered as a syntax error by Python interpreter.
When you use multiple if, your code will go back in every if statement to check the whether the expression suits your condition.
Sometimes, there are instances of sending many results for a single expression which you will not even expect.
But using elif terminates the process when the expression suits any of your condition.
Here's how I break down control flow statements:
# if: unaffected by preceding control statements
def if_example():
if True:
print('hey')
if True:
print('hi') # will execute *even* if previous statements execute
will print hey and hi
# elif: affected by preceding control statements
def elif_example():
if False:
print('hey')
elif True:
print('hi') # will execute *only* if previous statement *do not*
will print hi only because the preceding statement evaluated to False
# else: affected by preceding control statements
def else_example():
if False:
print('hey')
elif False:
print('hi')
else:
print('hello') # will execute *only* if *all* previous statements *do not*
will print hello because all preceding statements failed to execute
In the case of:
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
All the if statements at the same indentation level are executed even if only the first if statement is True.
In the case of:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
When an if statement is True, the preceding statements are omitted/ not-executed.