[Python] The problem of and and or priorities in calculating leap years and short-circuit logic

Source: Internet
Author: User

Well, the topic is very easy. But some of the details are quite interesting.


The title is: Calculate whether it is a leap year, infer a leap-year condition, meet the years modulus 400 is 0, or modulo 4 is 0 but modulo 100 is not 0


The answer is this:

Import time# calculates whether this year is a leap years and infers a leap year condition that satisfies the 400 of the model 0. Or modulo 4 is 0 but modulo 100 is not 0thisyear = Time.localtime () [0] #获取年份if thisyear%400==0 or thisyear%4==0 and Thisyear%100<>0:print ' This was a ' a leap year ' else:print ' This yeat are not a leap year '

very easy source code. Here to record some of the details.


Recall the array in Python, with three types of Python arrays:
(1) A list of ordinary lists, initialized to be able to dynamically add elements through a specific method.
How to define: arr = [element]

(2) a fixed array of tuples, once defined, the number of its elements can no longer be changed.
How to define: Arr = (Element)

(2) Dictionary dictionary type. That is the hash array.


How to define: Arr = {element K:v}


Next look at the source code.


The first is the time module. LocalTime () returns a tuple, which is a fixed-size array with some data for the current time:

LocalTime ([seconds]), (TM_YEAR,TM_MON,TM_DAY,TM_HOUR,TM_MIN,TM_SEC,TM_WDAY,TM_YDAY,TM_ISDST)


Then is the if inference inside the OR and and.

Not in Python's logical operator! " (non),&& (with), | | (or) ".

These three notation symbols (all in English). That is not,and,or.


But look at the source code. Infer whether a leap year should be:

1. Suppose to be divisible by 400 that's a leap year

2. Suppose to be divisible by 4 and not divisible by 100


That if inference should not be:

If Thisyear%400==0 or (Thisyear%4==0 and thisyear%100<>0):

Is that right?


This is actually true, but in Python, and has a higher priority than or.


We can look at a sample example:

>>> if 1 or 1 and not 1:     ... print ' OK ' ... Ok

assume that priority equality should not be output. In fact, the above inference is equivalent to:

If 1 or (1 and not 1):
in other words,

True or True and not true simply means (true) or (True and False)



I can see another interesting thing here. Look at the short-circuit mechanism inside Python:

Def a ():    print ' This is a! '    return 1def B ():    print ' This is b! '    return 1def C ():    print ' This is c! '    Return 1if A () or B () and not C ():    print ' ok! '

assume that the and priority is higher than or. Then it should be B again c again a, how directly output a?


In fact, this is the case in other languages, just not at the time, which is an interesting feature of the Boolean operator .


The Boolean operator has an interesting feature: it only evaluates when a value is required.

For example, an expression x and Y requires two variables to be true.

So assuming that X is false, the expression returns false immediately, regardless of the value of Y (in fact each language has this feature).

In fact, suppose X is false. The expression returns an X-value----Otherwise it returns the value of Y.

This behavior is known as short-circuit logic (short-circuit logic) or lazy evaluation (lazy evaluaion):

Boolean operators are often referred to as logical operators. As you can see, the 2nd value is sometimes "shorted out".

This behavior applies equally to or.

In an expression x or Y. When x is true, it returns the value of x directly, otherwise the Y value is returned.

Attention. This means that all code after the Boolean operator does not run.



Let's look at the example just now. and high priority. Indicates that the expression closest to both sides of it is the relationship, and this combination is preferred.

Very obvious. If you encounter the first true, it is not necessary to calculate the thing behind or, and the result is true.



The use of and and or in Python enables ternary operations. For example, a function in JS:

function Trans (v) {      return (v==0) 1:v;  

There are two alternatives available in Python:

def trans (v):          

or:

def trans (v):          return v==0 and 1 or V  

explain:

If v equals 0, then 1 is done with the operation. Is true, no subsequent or operation is performed, and 1 is returned directly.

Assuming that V equals 0 is false, then 1 is done with the operation. To false, proceed or operate. Returns v.




[Python] The problem of and and or priorities in calculating leap years and short-circuit logic

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.