Master Python in 14 days_operators_loop statements_string formatting_(2)

Today is our second day of learning Python. There seems to be a lot of tasks. If there are any mistakes, I hope you can leave a message below to nullptr.cpp. First of all, thank you for watching

Operator_Loop statement_String formatting

    • .operator
      • Five operators you must master
      • operator precedence
    • .Branch and loop statements
      • if and else branch statement
      • while loop and for loop
        • while loop bad
        • for loop
    • .String formatting
      • Use % for formatting
      • format (highly recommended)
      • Use f (huge convenience)

.Operator

Five operators that must be mastered

When it comes to operators, I think the first thing everyone thinks of is addition, subtraction, multiplication, division, etc. In this section, I will talk to you systematically. Common operators when we write code can be divided into 5 types:

  • Basic arithmetic operators such as: addition, subtraction, multiplication, division

  • Basic comparison operators, such as: greater than, less than


Note: Not supported in python3 <> (python3 is not backward compatible with python2)

  • Assignment operations, such as variable assignment

  • Member operations, such as: contains

check = "null" in "nullpte.cpp" # "null" is in "nullptr", so the check variable is assigned True
# Let the user enter a piece of text and detect whether the text contains sensitive words.
test = input("Please enter the content:") # If you enter: ikun is me
if "ikun" in text: # ikun is in what we input
  print("True Love Fan") # Print: True Love Fan
else:
  print(text)
  • Logical operations, such as AND or NOT

check01 = not 1>2
print(check) # Print: True

check01 = 10>5 or 1>2
print(check) # Print: True

check01 = 10>5 and 1>2
print(check) # Print: False

Operator precedence

There are many priorities of operators. Just remember the commonly used ones. If you are not sure, just add parentheses. Hehe

  • Arithmetic precedence precedence greater than comparison operator
if 10 + 10 > 11:
print("true")
else:
print("false")
  • Comparison operator precedence is greater than logical operator
if 1>3 and 5<10:
print("Established")
else:
print("Not established")
  • The three internal priorities of logical operators are not > and > or
if not 2 and 1>3 or 10 == 8:
print("true")
else:
print("false")

The above three priorities are summarized from high to low: addition, subtraction, multiplication and division > comparison > not and or . Trick: Add parentheses if you are not sure. Hehe

.Branch and loop statements

if and else branch statement

Branch: To put it simply, at an intersection, there are many forks ahead, and you can only choose one of them.

password = 123
if password == input("Please enter your password"): # Execute this if the conditions are met
    print("Password is correct")
else
    print("The password is correct") # Otherwise it is the statement in else

Add an else

password = 123
if password == input("Please enter your password"): # Execute this if the conditions are met
    print("Password is correct")
elif "yes" == input("Password is wrong, please enter yes") # If is not satisfied for the first time, judge whether elif is satisfied.
    if password == input("Please enter your password"): # Execute this if the conditions are met
        print("Password is correct")
    else
        print("The password is correct") # Otherwise it is the statement in else
else
    print("Password is correct") # If neither if nor elif are satisfied, execute the statement in else

while loop and for loop

while loop

If you have learned C language or other languages before, these will be OK for you after reading them a few times. Let’s take a look together!
The cycle is to repeat a process desperately and stop when the corresponding conditions are encountered.

'''
Basic syntax:
 while condition:
     xxx statement
'''
cnt =10
while cnt<=20:
    print("cnt") # python defaults to four spaces for indentation
    cnt + =1

# break: exit the loop directly and continue: exit the current layer of the loop
# Same as C/C++

– Example 1

print("start")
while True:
    print("nullptr.cpp")
print("End")
''' Output:
start
nullptr.cpp
nullptr.cpp
nullptr.cpp
nullptr.cpp
...
'''
  • Example 2
print("start")
while 1 > 2:
print("If the motherland is invaded, passionate men should strengthen themselves.")
print("End")

# Output:
start
Finish
  • Practical game examples
# 2. Randomly obtain numbers from 1 to 100
import random
num = random.randint(1,100)

flag = True
cnt = 0
while flag:
    guess_num = int(input("Enter the number you guessed"))
    cnt + =1
    if guess_num==num:
        print("Congratulations, you guessed it correctly")
        break
        # or flag = False
    else:
        if guess_num>num:
            print("Unfortunately, I guessed too high")
        if guess_num<num:
            print("Unfortunately, the guess is too small")

print(f"You guessed {<!-- -->cnt} times")
for loop

We won’t go into details about the for loop, let’s go directly to the code.

# 1. Basic syntax for x in yyy: for loop cannot define loop conditions
#Just assign the contents of yyy to x in turn; similar to C++ --> for(autp x: nums)
name ='Python'
for x in name:
    print(x,end='')

 # Output: Python

Use the range function to control the number of loops

# 2.range statement
# 2.1 For example, range(5) gets 0-4
for x in range(5):
    print(x) #Print: 01234

# 2.2 For example, range(5,10) gets the range 5-9 as [left,right)
for x in range(5,10):
    print(x) #Print: 56789

# 2.3 For example, range(5,10,2) gets 5-7-9
for x in range(5,10,2):
    print(x) #Print: 579

# 3.for and range can control the number of loops range(x): that is how many times it is looped
for x in range(5):
    print("nullptr.cpp") # Print 5 times: nullptr.cpp
    

.String formatting

The formatting we are talking about does not mean clearing the string; it means that when we use the print function to print, we can better insert the data type into the corresponding string. We use string formatting and use the most convenient form to implement the string. of splicing.

Use % for formatting

Let’s get straight to the code! ! !

name = "nullptr.cpp"
# %: placeholder, corresponding to %x
# test = "My name is %s, I am 18 years old" %"nullptr.cpp"
test = "My name is %s, I am 123 years old" %name
# test = "My name is nullptr.cpp, I am 123 years old"

#When multiple variables
name = "nullptr.cpp"
age=18
# text = "My name is %s, I am %s this year" %("nullptr.cpp",18)
# text = "My name is %s, I am %s years old this year" %(name,age)

text = "My name is %s, I am %d this year" %(name,age)
message = "%(name)sAre you there? %(user)s is waiting for you." % {<!-- -->"name": "Brother Kun", "user\ ": "ikun"}
print(message)

There is a detail, when we use % to output the percentage, we must bring %!

test = "a17Pro chip only prompts 10%"
print(test) #Normal output: a17Pro chip only prompts 10%
name = "a17Pro"
print("%s chip only prompts 10%%"%name) # 10% plus % will output: a17Pro chip only prompts 10%

format (highly recommended)

Advantages

  • One more function is that you can position the output at the position in {num}.
  • No need to write data type in %x
# Use %x and str.format() to compare
text = "My name is %s, I am %f this year" # You need to write %s and %f to indicate the type
data1 = text %("nullptr.cpp",20)
data2 = text %("ikun",2.5)

# It will be much more convenient below
text = "My name is {0} and I am {1} years old"
data1 = text.format("nullptr.cpp",888)
data2 = text.format("ikun",2.5)

# Specific examples
text = "My name is {0}, I am 18 years old".format("nullptr.cpp")

text = "My name is {0}, I am {1} years old".format("nullptr.cpp",18)

print("My name is {}, I am {} years old this year, my real name is {}.".format("nullptr.cpp",18,ikun))
# Do not write numeric subscripts inside {}, which is the default order.
# Output: My name is nullptr.cpp, I am 18 years old, and my real name is ikun.

print("My name is {0}, I am {1} years old this year, my real name is {0}.".format("nullptr.cpp",18))
# Output: My name is nullptr.cpp, I am 18 years old, and my real name is nullptr.cpp.

Use f (huge convenience)

This f function is also brought to us by python3.6. It combines many advantages. See the code below.

test = f"Rated {<!-- -->10}km today!"
print(test) # Output: I ran 10km today!

num_km = 10
test = f"I ran {<!-- -->num_km}km today!"
print(test) # Output: I ran 10km today!
day ="Today"
num_km = 10
test = f"{<!-- -->day} ran {<!-- -->num_km}km!"
print(test) # Output: I ran 10km today!

#Introduced in Python3.8
test = f"The cat's name is Mei Li Mao, and he is {<!-- -->1 + 2=} years old this year"
print(test)
# Base conversion
c1 = f"Cat weight {<!-- -->5}kg"
print(c1)

c2 = f"Cat weight {<!-- -->5:#b}kg"
print(c2)

c3 = f"Cat weight {<!-- -->5:#o}kg"
print(c3)

c4 = f"Cat weight {<!-- -->5:#x}kg"
print(c4)

Finally, thank you for watching