2020_9_23_Operator and branch structure

Operator and branch structure

Operator

Operators supported in python: mathematical operators, comparison operators, logical operators, assignment operators, bitwise operations (understand)
1. Mathematical operators: + (addition operation),-(subtraction operation), (multiplication operation) , / (Division operation),% (remainder, modulus), // (division), ** (power operation)
1) +, -
,, / have exactly the same functions as +, -, ×, ÷ in mathematics
print(5+2) # 7
print(5-2) # 3
print(5*2) # 10
print(5/2) # 2.5

2)%-take the remainder, take the modulus (remainder in mathematics)
x% y-find the remainder of x divided by y
print(10% 3) # 1

Application 1: Determine whether a number can be divisible by another number
x% y is 0, which means x can be divisible by y
num = int(input('Please enter an integer:'))
num = 23
print(num% 3 )

Application 2: Take the low digit of the integer
x% 10-get the single digit of x; x% 100-get the last two digits of x;…

Get the single digit of any integer
print(123% 10) # 3
print(92831% 10) # 1

3) //-
Divide (quotient rounded) x // y-the quotient of x divided by y rounded
towards small rounded down: 1.9 -> 1 -1.9 -> -2 3.4 -> 3
print(5 // 2) # 2
print(-5 //2) # -3

Application: remove the low digit
678 // 10 -> 67 678 // 100 -> 6
num = 23562
print(num // 100) # 235

Exercise: Get the hundreds digit of any number greater than 100
234 -> 2 1345 -> 3 78623 -> 6
"""
234 // 100 -> 2% 10 -> 2
1345 // 100 -> 13% 10 -> 3
78623 // 100 -> 786% 10 -> 6

234% 1000 -> 234 // 100 -> 2
1345% 1000 -> 345 // 100 -> 3
78623% 1000 -> 623 // 100 -> 6
"""
num = 23232
num = int(input('Please Enter an integer greater than 100:'))
method one
print(num // 100% 10)

Method two
print(num% 1000 // 100)

4) **-exponentiation
x ** y -> find x to the power of y
print(2 ** 3) # 8
print(3 ** 3) # 27

If the number of powers is 1/N, it means opening to the power of N
print(4 ** 0.5) # 2.0
print(8 ** (1/3)) # 2.0

2. Comparison operators: >, <, >=, <=, ==, !=
The results of all comparison operators are boolean
print(10> 20) # False
print(10 <20) # True
print (10 >= 10) # True
print(10 == 10) # True
print(10 != 10) # False

Note: The comparison operators in Python support continuous writing to indicate the value range
age = 32
print(18 <= age <= 28)

3. Logical operators: and (logical and), or (logical or), not (logical negation)

  1. and-logic and
    """
    application scenario: equivalent to "and" in life, used when multiple conditions need to be met at the same time.
    Operation rules: if all are True, the result is True, as long as one is False, the result is False
    True and True -> True
    True and False -> False
    False and True -> False
    False and False -> False
    """
    Conditions for scholarship:
    grade point greater than 3.5 and operating score no less than 90 grade = 3.9
    score = 98
    print('whether Can get scholarship:', grade> 3.5 and score >= 90)

Exercise: Write the condition
num = 67 whether a number can be divisible by 3 and 7 at the same time.
Method 1:
print('Whether it can be divisible by 3 and 7 at the same time:', num% 3 == 0 and num% 7 == 0)

Method two:
print('Is it divisible by 3 and 7 at the same time:', num% 21 == 0)

2) or-logical OR operation
"""
application scenario: equivalent to " or " in life, the
operation rule is used when only one of the multiple conditions is satisfied : the result is False, as long as one is False The result of True is True
True or True -> True
True or False -> True
False or True -> True
False or False -> False
"""
Exercise: Write the conditions for judging leap years.
Leap years-divisible by 4 but not divisible by 100 , Or divisible by 400
year = 2012
divisible by 4: year% 4 == 0
not divisible by 100: year% 100 != 0
divisible by 400: year% 400 == 0
print('Is it a leap year:' , (year% 4 == 0 and year% 100 != 0) or year% 400 == 0)

3) Not-logical NOT operation
"""
Application scenario: negate a certain condition
Operation rule: True becomes False, False becomes True
not True -> False
not False -> True
"""
age = 18
print(not age> 18) # True

When to use not: If a condition is very troublesome to write in the forward direction, but it is easy to write in the reverse direction, write the condition in the reverse direction and then add not.
Practice: write a condition that is not divisible by 3 and 7 at the same time
num = 12
Method 1:
print( (num% 3 != 0 and num% 7 != 0) or (num% 3 == 0 and num% 7 != 0) or (num% 3 != 0 and num% 7 == 0))
Method two :
Print(not num% 21 == 0)

4) *Short-circuit operation
and short-circuit operation: Condition 1 and Condition 2-If condition 1 is False, then the code corresponding to condition 2 will not perform
the short-circuit operation of or: Condition 1 or Condition 2-If condition 1 is True, then condition 2 The corresponding code will not execute
False and print('=====')
True or print('+++++')

5) *The operand is not a Boolean value
""" In
actual development, the operand and result of the logical operator are generally Boolean, but in the interview, I like to consider the case where the operand is not Boolean.

Expression 1 and Expression 2-If the result of expression 1 is True, then the result of the operation is the value of expression 2;
if the result of expression 1 is False, then the result of the operation is the value of expression 1.
Expression 1 or Expression 2-If the result of expression 1 is False, the result of the operation is the value of expression 2;
if the result of expression 1 is True, the result of the operation is the value of expression 1.

Note: If the value of the expression is not boolean, just convert it to boolean and then judge
how to convert : python data of any type can be converted into boolean value, all values ​​that are 0 and empty will be converted to False,
other values ​​are True
" ”"
a. Boolean conversion
print(bool(0), bool(0.0)) # False False
print(bool(100), bool(-1000)) # True True
print(bool(''), bool("" )) # False False
print(bool('False'), bool('')) # True True

print(5 and 3) # 3
print(0 and 3) # 0

print(5 or 3) # 5
print(0 or 3) # 3

print(‘abc’ and ‘123’)
print(False or ‘123’)

4. Assignment operators: =, +=, -=, *=, /=, %=, //=, **=
All assignment operations are used to assign values ​​to variables, and the left side of the assignment operator must be a variable ;
The variable on the left side of the compound assignment operation must be a variable that has already been assigned.

  1. =
    a = 10

  2. Compound assignment operator
    a += 3 # a = a+3
    print(a) # 13

a = 2 # a = a2 = 13*2
print(a) # 26

a %= 3 # a = a%3 = 26%3
print(a) # 2

5. The precedence of
operators Math operators> comparison operators> logical operators> assignment operators (lowest)
Math operators: **> *, /, %, //> +,-
logical operators: and> or
if there are parentheses, first count the content inside the parentheses
print(2 * 3 ** 2) # 18

6. *Bit operation: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise inversion), >> (right shift), << (left shift)
bit The operation efficiency of operation is higher than that of ordinary operators (tens of times to hundreds of times higher)

Application 1: Determine the parity of an integer-perform a bitwise AND operation on a number. If the result is 1, it is an odd number, and the result is 0 is an even number
print(28 & 1, 10 & 1, 102 & 1, -20 & 1) # 0 0 0 0
print(11 & 1, 9 & 1, -23 & 1, 1005 & 1) # 1 1 1 1

Application 2:
Number << N-Quickly multiply 2 N
number>> N-Quickly divide 2

number << 1-Quickly multiply 2: Number*2
Number>> 1-Quickly divide 2: Number//2
print(4 << 1, 5 << 1, 5 << 2) # 8 10 20
print(4 >> 1, 5 >> 1, -5 >> 1) # 2 2 -3

Branch structure

1. Process control

  1. Sequence structure-execute each statement sequentially from top to bottom (default)
    2) Branch structure-selectively execute code according to conditions (if statement)
    3) Loop structure-allow code to be executed repeatedly (for loop, while loop)

2. Branch structure
1) if single branch structure-execute an operation if the condition is met, and do not execute
"""
syntax
if the condition is not met : if conditional statement:
code segment

Description:

  1. if-keyword, fixed writing
  2. Conditional statement-any expression that has a result: any type of data, operator
    expressions other than assignment statements , function call expressions. (All expressions except assignment statements)
  3. Colon-fixed writing.
    (The colon in python generally needs to be indented after a line break to indicate a code block)
  4. Code segment-One or more statements that are indented (by tab) with if;
    code that will be executed only when the conditions are met

Execution process:
first judge whether the conditional statement is True (if it is not a Boolean value, convert to Boolean and then judge),
if it is True, execute the code segment, otherwise the code segment will not execute
""" The
conditional statement can be any expression except assignment statement
if 100:
pass

if ‘abc’:
pass

if 10+20:
pass

a = 100
if a % 2 + 3:
pass

Note: the assignment statement after
if cannot be if a = 20:
pass

The code segment after if will be executed only when the conditions are met
print('=======')
if 20> 10:
print('+++++++')
print('------ -')

Exercise: Enter an integer, and if it is an even number, print "this number is divisible by 2"
num = int(input('Please enter an integer:'))
num = 25
if num & 1 == 0:
print(num, ' This number is divisible by 2')

if num & 1:
print('This number is odd')

There must be at least one statement in the code segment of the if statement. If you are not sure, you can use pass to occupy the position
if num% 5 == 0:
pass

2) If double-branch structure-perform an operation when the condition is satisfied, and perform another operation if the condition is not satisfied.
"""
Syntax:
if conditional statement:
code block 1 (code to be executed when the condition is met)
else:
code block 2 (not satisfied Condition code to be executed)

Execution process:
first judge whether the conditional statement is True, if it is, execute code block 1 otherwise execute code block 2
"""
Exercise 1: If the number entered is an even number, print'even number', otherwise print'odd number'
num = 25
if num & 1 == 1:
print('odd')
else:
print('even')

Exercise 2: age input value print 'Adult' or 'Minor'
Age = 14
IF Age> = 18 is:
Print ( 'Adult'),
the else:
Print ( 'minor')

Exercise 3: Enter the year and print'leap year'
or'non -leap year' according to the year value year = 2012
if year% 4 == 0 and year% 100 != 0 or year% 400 == 0:
print('leap year')
else :
print('non-leap year')

  1. if multi-branch structure-perform different operations according to different conditions
    """
    syntax:
    if conditional statement 1:
    code block 1
    elif conditional statement 2:
    code block 2
    elif conditional statement 3:
    code block 3

    else:
    code block N

Execution process:
first judge whether conditional statement 1 is True, if it is directly execute code block 1, then the entire if structure directly ends;
if it is not True, judge whether conditional statement 2 is True, if it is, execute code block 2, then The entire if structure ends;
if it is not True, judge whether conditional statement 3 is True, ...
and so on, if the previous conditional statements are not satisfied, execute the code segment
""" after the else .
Exercise: Enter the student's grade point, Judge the level at which the student can obtain the lecture fee
First class: grade point> 4
Second class: 3.5 <= grade point <= 4
Third class: 3 <= grade point <3.5
Fourth class: 2.5 <= grade point <3
No: grade point Click <2.5
grade = 4.1
if grade> 4:
print('first-class scholarship')
elif grade >= 3.5:
print('second-class scholarship')
elif grade >= 3:
print('third-class scholarship')
elif grade> = 2.5:
print('fourth-class scholarship')
else:
print('no scholarship')

Guess you like

Origin blog.csdn.net/xdhmanan/article/details/108761972