current position:Home>Python notes (3): conditional statements and circular statements

Python notes (3): conditional statements and circular statements

2022-01-30 10:44:02 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

Conditional statements

So-called Conditional statements , It is to judge whether to execute or skip some specified statement blocks by the running result of the specified expression . In short, if the operation result of the specified expression is true, Execute the specified statement block ; If the result is false Skip a statement block or execute other statement blocks . The following code is as follows :

#  adopt input Type the user name and password 
user = input(" Please enter a user name :")
passwd = input(" Please input a password :")

#  Set the default user name to admin  password 123456
user_d = "admin"
passwd_d = "123456"

#  adopt if,elif else Carding process 
if user == user_d and passwd == passwd_d:
    print(" Landing successful ")
elif user != user_d:
    print(" The username does not exist ")
else:
    print(" Wrong password ")
 Copy code 

if sentence

stay Python in , To construct a branching structure, you can use ifelif and else keyword . So-called keyword Is a word with a special meaning , image if and else It's a key word used to construct a branching structure , Obviously you can't use it as a variable name ( in fact , You can't use it as any other identifier ).

In the code above , The analysis is as follows :

  • Use a colon after each condition : , Indicates the statement block to be executed after the condition is met .
  • A login system exists 3 Medium condition ,1. The user name and password match , Landing successful ;2. The username does not exist , Login failed ;3. Wrong password , Login failed
  • If the user name and password match , Print login successful
  • The user name does not match. The printed user name does not exist
  • The first two exclude , There's only the condition of wrong password

It is worth noting that Python Indents are used to represent the structure of the code , That is to say, you want to be in if To execute a statement in a statement , Just give it the same indent . Indent You can use any number of spaces , but Usually use 4 A space

Nested branch statements

The sample code is as follows :

user_key = int(input(" Input 1 Enter the landing system , Input 0 Exit the system "))

#  adopt if,elif else Carding process 
if user_key == 1:  #  As long as the user enters 1 To enter the login system interface 
    #  adopt input Type the user name and password 
    user = input(" Please enter a user name :")
    passwd = input(" Please input a password :")
    #  Set the default user name to admin  password 123456
    user_d = "admin"
    passwd_d = "123456"
    if user == user_d and passwd == passwd_d:
        print(" Landing successful ")
    elif user != user_d:
        print(" The username does not exist ")
    else:
        print(" Wrong password ")
elif user_key == 0:
    print(" Exited ")
else:
    print(" Input error ")
 Copy code 
  • Because at this time, there is an extra layer of structure in the outer layer , So it needs to be in if A new branch structure is constructed inside of , Empathy elif and else We can also construct new branches in , It's called nested branching
  • But if you can not use nested structure, try not to use , Nesting structure affects the readability of code

Case practice

  1. The English unit inch is interchangeable with the metric unit centimeter (1 Inch (in)=2.54 centimeter (cm))

    value = float(input(" Please enter the value :"))
    unit = input(" Please enter the unit ( Inches or in And centimeters or cm):")
    
    if unit == "in" or unit == " Inch ":
        print("%.2f Inch =%.2f centimeter " % (value, value * 2.54))
    elif unit == "cm" or unit == " centimeter ":
        print("%.2f centimeter =%.2f Inch " % (value, value / 2.54))
    else:
        print(" Unit error ")
     Copy code 
  2. Conversion of a 100% grade to a graded grade

    requirement : If the score entered is in 90 More than ( contain 90 branch ) Output A;80 branch -90 branch ( Not included 90 branch ) Output B;70 branch -80 branch ( Not included 80 branch ) Output C;60 branch -70 branch ( Not included 70 branch ) Output D;60 The output is as follows E.

    score = float(input(' Please enter the grade : '))
    if score >= 90:
        grade = 'A'
    elif score >= 80:
        grade = 'B'
    elif score >= 70:
        grade = 'C'
    elif score >= 60:
        grade = 'D'
    else:
        grade = 'E'
    print(' The corresponding level is :', grade)
     Copy code 

Loop statement

Loop statement Is the repeated execution of certain statements , This repetition is controlled by specifying an expression . Simply put, specify that the expression is converted to boolean The result after the value of type is true, Which statements should be repeated all the time , Until the specified expression is converted to boolean The result after the value of type is false Will stop executing .

for-in loop

for The loop is used to iterate the sequence ( The list of , Tuples , Dictionaries , Set or string ). The grammatical structure is as follows :

for <variable> in <sequence>:
    <statements>
 Copy code 

range() function

Generate a series of numbers ,range() Several uses of

  • range(101): Can be used to produce 0 To 100 The integer of the range , It should be noted that you can't get 101.
  • range(1, 101): Can be used to produce 1 To 100 The integer of the range , It's equivalent to a closed interval in the front and an open interval in the back .
  • range(1, 101, 2): Can be used to produce 1 To 100 The odd number , among 2 It's the step length , That is, the value of each increment .
  • range(100, 0, -2): Can be used to produce 100 To 1 An even number of , among -2 It's the step length , That is, the value of each decreasing number .

example 1: Calculation 1-100 And

#  Used to store the results of each calculation 
sum = 0
for i in range(101):
    sum += i  #  This is equivalent to sum=sum+1
print(sum)
 Copy code 

example 2: Calculation 1-100 An even sum

#  Used to store the results of each calculation 
sum = 0
for i in range(0, 101, 2):
    sum += i
print(sum)
 Copy code 

from 0 Start , Each step is 2, Just skip the singular

example 3: Calculation 1-100 Odd sum

It can be downloaded from 1 Start , In steps of 2, This skips the even number , It can also be realized through nested branch structure , for example

#  Used to store the results of each calculation 
sum = 0
for i in range(101):
    if i % 2 == 1:  #  Because singular Division 2 more than 1, So only if this condition is met , Only then can the cumulative calculation be carried out 
        sum += i
print(sum)
 Copy code 

while loop

while The ability to produce or convert out of bool Value to control the loop , The value of the expression is True Then continue the cycle ; The value of the expression is False End cycle .

The grammatical structure is as follows :

while  Judge the condition :
     Execute statement ……
 Copy code 

adopt while Statement to implement 1-100 The cumulative result

#  Used to store the results of each calculation 
sum = 0
#  Set the starting value 
i = 1
#  Set the maximum number of cycles allowed 
n = 100
while i <= n:
    sum += i
    i += 1
print(sum)
 Copy code 

break and continue sentence

break Sentences can jump out of for and while Circulatory body of . If you for or while To terminate in a cycle .

continue Statements are used to tell Python Skip the remaining statements in the current loop block , Then proceed to the next cycle .

Code execution process

example : Guessing games

The rules : A computer comes up with 1 To 100 Random number between , Players enter their own guesses , The computer gives the corresponding prompt information ( A little bigger 、 Smaller or right ), If the player guesses the number , The computer prompts the user to guess how many times , Game over , Otherwise the game goes on ; If the number is greater than 5 Time , Then exit the loop .

import random  #  Import random number module 

answer = random.randint(1, 100)  #  Generate 1-100 The random number 
counter = 0  #  The initial number of times will be 0
while True:
    number = int(input(' Please enter : '))
    if number < answer:
        print(' A little bigger ')
        counter += 1
    elif number > answer:
        print(' Smaller one ')
        counter += 1
    else:
        print(' Congratulations on your guesses !')
        break  #  If you're right   Just jump out of the loop 
    if counter >= 5:  #  More times than 5 Then exit the system 
        print(' Your IQ balance is obviously insufficient ')
        break
print(' You guessed in all %d Time ' % counter)
 Copy code 

A nested loop

Just like the branch structure , Loop structures can also be nested , That is to say, the loop structure can also be constructed in the loop

example 1: adopt for...in Statements to print 99 Multiplication table

for x in range(1, 10):
    for y in range(1, x+1):
        print("%d * %d = %d" % (y, x, x*y), end="  ")
    print()
 Copy code 

example 2: adopt while Statements to print 99 Multiplication table

x = 1
y = 1
while x <= 9:
    y = 1  #  After each execution of the sub loop ,y Reset to 1
    while y <= x:
        print("%d * %d = %d" % (y, x, x*y), end="  ")
        y += 1
    x += 1
    print()  #  Each sentence ends with a new line 
 Copy code 

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301044000587.html

Random recommended