Python basics (loop statement while loop, break, continue, character formatting, operators)

1. while loop

[1] Grammar:

while 条件:
    ...
    ...
    ...

Example:

print("123")
while 条件:
  ...
  ...
  ...
print(456)

[2] Basic use of loop statements

Example 1:

print("开始")
while True:
    print("hello world")
print("结束")

# 输出:
开始
hello world
hello world
hello world
hello world
...

Example 2:

print("开始")
while 1 > 2:
	print("如果祖国遭受到侵犯,热血男儿当自强。")
print("结束")

# 输出:
开始
结束

Example 3:

data = True
print("开始")
while data:
	print("如果祖国遭受到侵犯,热血男儿当自强。")
print("结束")

# 输出:
开始
如果祖国遭受到侵犯,热血男儿当自强。
如果祖国遭受到侵犯,热血男儿当自强。
如果祖国遭受到侵犯,热血男儿当自强。
...

Example 4:

print("开始")
flag = True
while flag:
	print("滚滚黄河,滔滔长江。")
	flag = False
print("结束")

# 输出:
开始
滚滚黄河,滔滔长江。
结束

Example 5:

print("开始")
num = 1
while num < 3:
	print("滚滚黄河,滔滔长江。")
	num = 5
print("结束")

# 输出:
开始
滚滚黄河,滔滔长江。
结束

Example 6:

print("开始")
num = 1
while num < 5:
	print("给我生命,给我力量。")
	num = num + 1
print("结束")

# 输出:
开始
给我生命,给我力量。
给我生命,给我力量。
给我生命,给我力量。
给我生命,给我力量。
结束

【3】Case

Please implement a user login system. If the password is wrong, the user will be repeatedly prompted to re-enter, and it will not stop until the input is correct.

print("开始运行路飞系统")

flag = True
while flag:
    user = input("请输入用户名:")
    pwd = input("请输入密码:")
    if user == "xuyi" and pwd == "123":
        print("登录成功")
        flag = False
    else:
        print("用户名或密码错误")

print("系统结束")

Guess the number, set an ideal number such as: 66, and always prompt the user to enter the number. If it is greater than 66, it will display a larger guessing result; if it is smaller than 66, it will display a smaller guessing result; only if the input is equal to 66, Show that the guess was correct, and exit the loop.

lag = True
while flag:
    num = input("请输入数字:")
    num = int(num)
    if num > 66:
        print("大")
    elif num < 66:
        print("小")
    else:
        print("猜测结果正确")
        flag = False

Use a loop to belong to all integers within 1-100

num = 1
while num < 101:
    print(num)
    num = num + 1

Use a loop to output integers from 1-10, but not 7

方法1
num = 1
while num < 11:
    if num == 7:
        pass           表示什么都不输出,或者使用不等于号 !=
    else:
        print(num)
    num = num + 1
   
方法二:
num = 1
while num < 11:
    if num != 7:
        print(num)
    num = num + 1

Odd numbers within 1-100

num = 1
while num < 101:
    if num % 2 == 1:
        print(num)
    num = num + 1

The sum of all integers from 1-100

total = 0
num = 1
while num < 101:
    total = total + num
    num = num + 1
print(total)

Output an integer of 10-1

num = 10
while num > 0:
    print(num)
    num = num - 1

【4】break

Used in a while loop to terminate the loop

print("开始")
while True:
	print("1")
  break
	print("2")
print("结束")

# 输出
开始
1
结束

Therefore, when writing code in the future, there are two ways to end the loop, namely: conditional judgment and the break keyword. There is no difference between the two in use, as long as the function can be realized.

【5】 continue

continue, used in the loop to end this loop and start the next loop.

print("开始")
while True:
	print("红旗飘飘,军号响。")
	continue
	print("剑已出鞘,雷鸣电闪。")
	print("从来都是狭路相逢勇者胜。")
print("结束")

# 输出
开始
红旗飘飘,军号响。
红旗飘飘,军号响。
红旗飘飘,军号响。
红旗飘飘,军号响。
...

Both break and continue are placed in the loop statement to control the loop process. Once a break is encountered, all loops will be stopped. Once a continue is encountered, the current loop will be stopped and the next loop will start.

Of course, if there is no break and continue, we can use the judgment of the while condition and other assistance to complete many functions. With break and continue, our code logic can be simplified to a certain extent.

[6] while else syntax

When the condition after while is not true, the code in else will be executed.

while 条件:
  代码
else:
  代码

Example:

num = 1
while num < 5:
  print(num)
  num = num + 1
else:
  print(666)

# 输出 
1
2
3
4
666
while True:
  print(123)
	break      brink可终止else中的代码
else:
  print(666)

# 输出
123

2. String formatting

String formatting, using a convenient form to achieve string splicing.

【1】%

  • Basic formatting operations
    %s: placeholders for character strings
    %d: placeholders for integers
text = "我叫%s,今年%d岁" %(name,age)
  • Percentages
    Once there is a percentage display in the string formatting, be sure to add %% to output %.

[2] format (recommended)

text = "我叫{0},今年18岁".format("张三")

text = "我叫{0},今年{1}岁".format("张三",18)

text = "我叫{0},今年{1}岁,真是的姓名是{0}。".format("张三",18)


text = "我叫{},今年18岁".format("张三")

text = "我叫{},今年{}岁".format("张三",18)

text = "我叫{},今年{}岁,真是的姓名是{}。".format("张三",18,"张三")
text = "我叫{n1},今年18岁".format(n1="张三")

text = "我叫{n1},今年{age}岁".format(n1="张三",age=18)

text = "我叫{n1},今年{age}岁,真是的姓名是{n1}。".format(n1="张三",age=18)
text = "我叫{0},今年{1}岁"
data1 = text.format("张三",666)
data2 = text.format("李四",73)

【3】f

Versions after python 3.6

text = f"张三喜欢{
      
      '跑步'},跑完之后满身大汗"
action = "跑步"
text = f"张三喜欢{
      
      action},跑完之后满身大汗"

3. Operators

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

【1】Operator example

  • Arithmetic operators, such as: addition, subtraction, multiplication, and division
    insert image description here
print( 9//2 )
  • Comparison operators, such as: greater than, less than
    insert image description here
    Note: not supported in python3<>
if 1 >2:
  pass
while 1>2:
  pass

data = 1 == 2
  • Assignment operations, such as: variable assignment
    insert image description here
num = 1
while num < 100:
  print(num)
  # num = num + 1
  num += 1
  • Membership operations, such as whether to contain
    insert image description here
v1 = "le" in "llee"  # True/False
  • Logical operations, such as: and or not
    insert image description here
if username == "张三" and pwd == "123":
  pass

data = 1 > 2
if not data:
  pass

[2] Operator: Priority

There are many priorities of operators, but there are not many common ones. It is recommended that you remember 3:

  • Arithmetic precedence precedence is greater than comparison operators
  if 2 + 10 > 11:
  	print("真")
  else:
  	print("假")
  • Comparison operators have precedence over logical operators
  if 1>2 and 2<10:
  	print("成立")
  else:
  	print("不成立")
  • The three priorities inside the logical operator are not > and > or
  if not 1 and 1>2 or 3 == 8:
  	print("真")
  else:
  	print("假")

The above three priorities are summarized from high to low: 加减乘除 > 比较 > not and or . Add parentheses if you are unsure.

【3】Operator: knowledge about interview questions

In logical operations: and or

v1 = name == "张三" and pwd == "123"
# v1 = True and False
v2 = "张三" and "李四"

# 第一步:将and前后的只转换为布尔值 True and True
# 第二步:判断本次操作取决于谁?由于前面的是True,所以本次逻辑判断取决于后面的值。
# 所以,后面的只等于多少最终结果就是多少。 v2 = "李四"


v3 = "" and "李四"
# 第一步:将and前后的只转换为布尔值 False and True
# 第二步:判断本次操取决于谁?由于前面的是False,所以本次逻辑判断取决于前面的值。
# 所以,前面的只等于多少最终结果就是多少。 v2 = ""

v4 = 1 or 8 
# 第一步:将and前后的只转换为布尔值 True or True
# 第二步:判断本次操作取决于谁?由于前面的是True,所以本次逻辑判断取决于前面的值。
# v4 = 1

v5 = 0 or 8 
# 第一步:将and前后的只转换为布尔值 False or True
# 第二步:判断本次操作取决于谁?由于前面的是False,所以本次逻辑判断取决于后面的值。
# v5 = 8

practice questions

v1 = 1 or 2               1
v2 = -1 or 3            -1
v3 = 0 or -1             -1
v4 = 0 or 100           100
v5 = "" or 10            10
v6 = "张三" or ""        张三
v7 = 0 or ""               “ ”       

print(v1,v2,v3,v4,v5,v6,v7)

# or,看第一个值,如果第一个值为真,结果就应该是第一个值,否则就结果就是第二个值。
v1 = 4 and 8                   8
v2 = 0 and 6                   0         
v3 = -1 and 88                 88
v4 = "" and 7                  “”
v5 = "张三" and ""             “”
v6 = "" and 0                  “”
v7 = 0 and "中国"              0

print(v1,v2,v3,v4,v5,v6,v7)

# and,看第一个值,如果第一个值真,结果就应该是第二个值,否则结果就是第一个值。

interview questions

  • If there are multiple and and or, first calculate and and then calculate or.
v1 = 0 or 4 and 3 or 7 or 9 and 6
     0 or 3 or 7 or 9 and 6
     0 or 3 or 7 or 6
     3 or 7 or 6
     3 or 6
     3
v2 = 8 or 3 and 4 or 2 and 0 or 9 and 7
		 8
  
  
v3 = 0 or 2 and 3 and 4 or 6 and 0 or 3
		 4
  • Calculate not first, then calculate and, and finally calculate or
v4 = not 8 or 3 and 4 or 2
		 4

practise

Guess the age game
Requirements: Allow the user to try up to 3 times. If the guess is not correct for 3 times, it will exit directly. If the guess is correct, print a congratulations message and exit.

num = 0
while num < 3:
    num += 1
    age = input("年龄:")
    if age == "18":
        print("正确")
        break
    else:
        text = "错误,还有{0}机会".format(3 - num)
        print(text)
  1. Requirements for the upgraded version of the age guessing game
    : allow the user to try up to 3 times. After each 3 attempts, if the guess is not correct, ask the user if he wants to continue playing. If the answer is Y, continue to let him guess 3 times, and so on , if you answer N, you will exit the program, if you guess right, you will exit directly.
num = 0
while num < 3:
    num += 1
    age = input("年龄:")
    if age == "18":
        print("正确")
        break
    else:
        text = "错误,还有{0}机会".format(3 - num)
        print(text)
        if num == 3:
            choice = input("是否继续")
            if choice == "否":
                break
            elif choice == "是":
                num = 0
                continue
            elseprint("输入错误")
                break

Guess you like

Origin blog.csdn.net/weixin_46268244/article/details/130755838