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 ~
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
stay Python in , To construct a branching structure, you can use
else keyword . So-called keyword Is a word with a special meaning , image
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
ifA new branch structure is constructed inside of , Empathy
elseWe 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
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
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 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 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
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 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
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
author[A bowl week],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
- leetcode 110. Balanced Binary Tree（python）
- Django uses Django celery beat to dynamically add scheduled tasks
- The bear child said "you haven't seen Altman" and hurriedly studied it in Python. Unexpectedly
- Optimization iteration of nearest neighbor interpolation and bilinear interpolation algorithm for Python OpenCV image
- Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
- Use of Python partial()
- Python game development, pyGame module, python implementation of angry birds
- leetcode 1104. Path In Zigzag Labelled Binary Tree（python）
- Save time and effort. 10 lines of Python code automatically clean up duplicate files in the computer
guess what you like
Learn python, know more meat, and be a "meat expert" in the technical circle. One article is enough
[Python data structure series] "stack (sequential stack and chain stack)" -- Explanation of knowledge points + code implementation
Datetime module of Python time series
Python encrypts and decrypts des to solve the problem of inconsistency with Java results
Chapter 1: introduction to Python programming-4 Hello World
Summary of Python technical points
11.5K Star！ An open source Python static type checking Library
Chapter 2: Fundamentals of python-1 grammar
[Python daily homework] day4: write a function to count the number of occurrences of each number in the incoming list and return the corresponding dictionary.
Python uses turtle to express white
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
- Base64 encryption and decryption in Python
- Chapter 2: Fundamentals of python-2 variable
- Python garbage collection summary
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
- Python draws a spinning windmill with turtle
- Deep understanding of Python features
- A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
- Python opencv Canny edge detection knowledge supplement
- Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
- Python: faker extension package
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat 
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
- Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
- [Python data collection] university ranking data collection
- [Python data collection] stock information collection
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
- Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
- [Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
- Python type hints from introduction to practice
- Python notes (IX): basic operation of dictionary
- Python notes (8): basic operations of collections
- Python notes (VII): definition and use of tuples