Python (3)-Three major processes and exercises for getting started with Python (if, for, while)

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right


Preface

An interesting case of expanding knowledge about the combination of turtle and for loop: https://blog.csdn.net/xiamoyanyulrq/article/details/81842604

1、if

1.1 Simple if statement

  • grammar structure
if conditional_test:    
    do something

If age>18, output the indented statement after the if statement, otherwise do nothing

age=19
if age>=18:
    print("已成年")

1.2 if-else statement

  • The if statement performs one operation when the conditional test passes, and performs another operation when it fails; in this case, you can use the if-else statement provided by Python.
  • The if-else statement block is similar to a simple if statement, but the else statement allows you to specify that the conditional test is to be executed when the test fails.
    Syntax format
if conditional_test:    
    do something
else:
    do something

If age>18, the output is adult; otherwise, the output is minor

age=int(input("请输入你的年龄:"))
if age>=18:
    print("已成年")
else:
    print("未成年")

1.3 if-elif-else statement

  • In actual scenarios, multiple conditions often need to be checked, and the if-elif-else structure provided by Python can be used.
  • Python only executes one code block in the if-elif-else structure, and it checks each conditional test in turn until it encounters a conditional test that passes.
  • Python will execute the code immediately following it and skip the remaining tests

grammar structure

if case1: ##符合case1将执行
    do something
elif case2: ##符合case2将执行
    do something
elif case3: ##符合case3将执行
    do something
else:  ##其他条件
    do something

Grading of student performance: [0,59) Failed [60,70) Passed [70.80) Medium [80,90) Good [90,100) Excellent

score=86
if score>=60 and score<70:
    print("及格")
elif score>=70 and score<80:
    print("中等")
elif score>=80 and score<90:
    print("良好")
elif score>90 and score<=100:
    print("优秀")
else:
    print("不及格")

1.4 Ternary operator

  • Ternary arithmetic, also known as ternary arithmetic, is a shorthand for simple conditional statements

grammar structure:

if_suite if expression1 else else_suite

Judging whether you are an adult

age=12
print("成年" if age>=18 else "未成年")

2、while

  • The for loop is used to have a code block for each element in the collection, while the while loop runs continuously until the specified conditions are not met.

while syntax format

while expression:
      suite_to_repeat
# while 循环的 suite_to_repeat 子句会一直循环执行, 直到 expression 值为布尔假.

2.1 Counting cycle

count=0
while count<5:
    count+=1
    print(f"这是第{count}次循环")

2.2 Infinite loop

Enter the name, print out the entered name

while True
    name=input("请输入你的名字")
    print(f"你输入的名字是:{name}")

Insert picture description here

3、for

Built-in function range

  • Syntax: range(start, end, step =1) returns a list containing all k, start <= k <end, k is incremented by
    step each time
for i in range (1,5):     ##遍历1~4,步长为1
    print(i)
for i in range (1,5,2):   ##遍历1~4,步长为2
    print(i)

4. Practice questions

4.1 Determine whether the entered year is a leap year

  • Rule: A leap year is divisible by 4 but not divisible by 100 or year can be divisible by 400.
  • Output: The year 2000 is a leap year. / Year 1983 is not a leap year
    exit(): launch the program

4.2 Find the even number from 1 to 100 (for)

  • Rules: An even number is an integer that can be divisible by 2. 0 is a special even number
for  num in range(0,101,2):
    print(num)

Insert picture description here

4.3 Enter the username and password to log in to the system (for)

If the account password is correct, it will prompt the user to log in successfully and log out; if the account and password entered by the user are incorrect, it will prompt that there are several login opportunities left, and the user can re-enter the account password to log in.

for n in range(1,4):
  user=input("请输入用户名:")
  psword=input("请输入密码:")
  if user=="root" and psword=="westos":
    print("登录成功")
    exit()
  elif (3-n)>0:
    print(f'用户 {user} 登录失败,您还有{3-n}次机会')
  else:
    print(f'用户 {user} 登录失败,系统锁定')
    break

Insert picture description here

Insert picture description here

4.4 According to the input user name and password (while, if)

Determine whether the user name and password are correct. In order to prevent brute force cracking, there are only three opportunities to log in. If there are more than three opportunities, an error message will be reported

count=0
while count<3:
    name=input("请输入名字:")
    password=input("请输入密码:")
    if name=="admin" and password=="password":
        print(f"{name}用户登录成功")
        exit()
    else:
        count+=1
        print(f"用户第{count}次登录失败")
else:
    print("用户已经三次登录失败,账号被锁定!")

4.5 Nine-Nine Multiplication Table (for)

for i in range (1,10):
    for j in range(1,i+1):
        print(f"{i}x{j}={i*j}",end=' ')
    print()

Insert picture description here

Insert picture description here
Requirements:
According to the input user name and password, determine whether the user name and password are correct.
In order to prevent brute force cracking, there are only three opportunities to log in. If there are more than three opportunities, an error message will be reported.
Database information:
name='root' passwd='westos'
“”"

try_count = 1 # The number of user attempts to log in
while True:
print(f'The {try_count} user logged in to the system for the first time')
try_count += 1 # The number of user attempts to log in+1
name = input("Username:")
password = input("Password:")
if name =='root' and password =='westos':
print( f'User {name} successfully logged in')
exit() # Exit the program
else:
print( f'User {name} Login failed')

Guess you like

Origin blog.csdn.net/weixin_41191813/article/details/113467861