One 、if Judge
Grammar 1 :
if Conditions :
# Here's the last one if Sub code block of
print( Subcode 1)
print( Subcode 2)
print( Subcode 3)

if After running, the code will be executed Previous indent Code block for

Grammar II :
if Conditions :
# The following indentation level is the code block executed when the condition holds
print( Subcode 1)
print( Subcode 2)
print( Subcode 3)
else:
# The following indentation level is the code block executed when the condition is not true
print( Subcode 4)
print( Subcode 5)
print( Subcode 6)

Grammar 3 :
if Conditions 1:
print( Subcode 1)
print( Subcode 2)
print( Subcode 3)
elif Conditions 2:
print( Subcode 4)
print( Subcode 5)
print( Subcode 6)
elif Conditions 3:
print( Subcode 7)
print( Subcode 8)
print( Subcode 9)
else:
print( Subcode 10)
print( Subcode 11)
print( Subcode 12)

Example :
# Requirements describe :
If the result >= 90, that : good
If the result >= 80 And < 90, that : good
If the result >= 70 And < 80, that : Ordinary
Other situations : Is very poor

score = input('please input your score')

if score >= 90:
print(' good ')
elif score >= 80:
print(' good ')
elif score >= 70:
print(' Ordinary ')
else:
print(' Is very poor ')

Grammar 4 :(if Nesting of judgments )
sex = 'female'
age = 18
is beautiful = True
is cuccessful = True

if sex == 'female' and age == 18 and is beautiful:
print(' Start to say ')
if is cuccessful:
print(' together ')
else:
print(' It's predestined ')
else:
print(' How's Auntie ')

Two 、while loop
grammar :
while Conditions :
print(' Code 1')
print(' Code 2')
print(' Code 3')

Example :
# Loop in the account number and password , And nested if Judge to print the result after inputting the account password
while True:
name = input('please input your name:')
pwd = int(input('please input your password'))
if name == 'egon' and pwd == 123
print('login successful')
else:
print('username or password error')

end while Two ways of cycling :
Mode one : take while Change to condition False
Change the condition to False It doesn't end the loop immediately , It will not take effect until the next cycle to judge the condition

Example :
# After entering the correct account password, stop entering the account again
tag = True # take True Assign to a variable , Let the true or false of the variable be a condition , By changing the true and false of the variable to change the true and false of the condition
while tag:
name = input('please input your name')
pwd = input('please input your password')
if name == 'egon' and pwd == 123:
print('login successful')
tag = False
else:
print('username or password error')

Mode two :while + break
break It's got to be in the circulatory system , Once the loop body executes to break It will immediately end this layer cycle

Example :
# After entering the correct account password, stop entering the account again
while True:
name = input('please input your name')
pwd = input('please input your password')
if name == 'egon' and pwd == 123'):
print('login success')
break
else:
print('username or password error')

suspend while The way :( It's not the end )
while + continue: End this cycle , Go directly to the next cycle

Example :
# except 4, take 1-6
count = 1
while count < 7:
if count == 4:
count += 1

Because that's the end of the cycle , Want to keep the code running , You have to be right count Today's increment assignment
continue The following incremental assignment instruction cannot be executed , But the incremental assignment has to be done
So add in contine above

continue
print(count)
count += 1

Be careful :continue The last line of the loop is useless code ,

Because after the last line of the loop runs, the loop will automatically be repeated , There is no need to continue To stop the cycle

while Nesting of loops :

while Conditions 1:

while Conditions 2:
Code 1
Code 2
Code 3

Example 1 :
In the wrong input cycle , Input on the basis of the end of the program plus :
Enter the next function interface after the input , The exit function can directly terminate the cycle
while True:
name = input('please input your name')
pwd = input('please inpunt your password')
if name == 'egon' and pwd == '123':
print('login successful')
while True:
print('''
0 sign out
1 Withdraw money
2 Transfer accounts
3 Inquire about
''')
choice = input(' Please select the action you want to perform :')
if choice == '0':
break # Terminate this layer cycle , Execute the code of the previous indent , namely #1 break
elif choice == '1':
print(' Withdraw money ')
elif choice == '2':
print(' Transfer accounts ')
elif choice == '3':
print(' Inquire about ')
else:
print(' Wrong operation , Please reselect :')
break # Here is #1 break
else:
print(' Wrong username or password !')

Example 2 :
# Two while Loop through the same variables True , Just run to '0 sign out ' Just block all of them whjle loop
tag = True
while tag:
name = input('please input your name:')
pwd = input('please input your password:')

if name == 'egon' and pwd == '123':
print('login successgul')
while tag:
print('''
0 sign out
1 Withdraw money
2 Transfer accounts
3 Inquire about
''')
choice = input(' Please select the action you want to perform :')
if choice == '0':
tag = False
elif choice == '1':
print(' Withdraw money ')
elif choice == '2':
print(' Transfer accounts ')
elif choice == '3':
print(' Inquire about ')
else:
print(' Wrong operation , Please reselect :')
else:
print(' Wrong username or password !')

3、 ... and 、for loop
for The strength of the loop lies in the loop value

Example :
# Take the values from the list and print
list = [a,b,c,d,e]
# Use while Value cycle :
i = 0
while i < 6:
print(list[i]) # i As an integer variable, it acts as an index in the list and exists in list[i] in , So as to achieve Defer index value To evaluate the effect of
i += 1
# Use for Value cycle :
for i in list:
# This floor for Loop the first time , This line of work is actually i = list[1], Assign the first value in the list to i
print(i)

# Take out the values in the dictionary and print
dic={'name':'egon','age':18,'gender':'male'}
for i in dic:
print(i,dic[i])
# there i For... In the dictionary key, so dic[i] In the dictionary key_i Corresponding value

for + continue: Stop this for loop ( It's not the end )

Example :
# print to xx Just skip this print
nums=[11,22,33,44,55]
for i in nums:
if i == 44
continue
print(i)

for + break: Terminate this layer for loop

Example :
# print to xx Stop printing
nums=[11,22,33,44,55]
for i in nums:
if i == 44:
break
print(i)

for + else :

Example :
names=['egon','kevin1111_dsb','alex_dsb','mac_dsb']
for name in names:
if name == 'kevin1111_dsb'
break # Once because break And the end of the cycle , Last indented else The code will not be executed
print(name)
else:
print('else Test code ')

for + range():
range Usage of
>>> range(1,5)
[1, 2, 3, 4]
>>> for i in range(1,5):
... print(i)
...
1
2
3
4
>>> range(1,5,1)
[1, 2, 3, 4]
>>> range(1,5,2) # 1 3
[1, 3]

for Nesting of loops :

Example :
for i in range(3):
for j in range(4):
print(i,j)
# What you can't understand is the following code , the range Convert to a list for easy understanding
for i in [0,1,2]: # i=1
for j in [0,1,2,3]: # j=1
# Perform the lower indent for loop ,
Will go back to the upper indent level for Loop to continue looping the unfinished upper loop
print(i,j)

DAY4 if、while and for More articles about

  1. python_way,day4 Built in functions (callable,chr, Random verification code ,ord), Decorator

    python_way,day4 1. Built in functions - Next Make a random captcha 2. Decorator 1. Built in functions - Next callable() # Object can be called chr() #10 The base number corresponds to ascii In the code table ...

  2. Spark Rookie camp Day4 Unit test program writing

    Spark Rookie camp Day4 Unit test program writing Spark Compared with traditional code, it is more difficult to debug , It is necessary to write unit tests . Step0: Demand analysis Before writing the test case , Need to complete requirement analysis , Identify all the inputs to the program ...

  3. Spark Tungsten reveal Day4 Memory and CPU Optimize the use of

    Spark Tungsten reveal Day4 Memory and CPU Optimize the use of Today's focus is on memory and CPU Optimized use of , This is a Spark2.0 Provides a very large optimization part of execution time . Research on past code , We will find that , The improvement of abstraction , ...

  4. Catalyst reveal Day4 analyzer analysis

    Catalyst reveal Day4 analyzer analysis Let's continue to analyze today catalyst, Let's talk about it analyzer, stay sql Statement processing flow ,analyzer Is in sqlparse On the basis of , hold unresol ...

  5. Kakfa reveal Day4 Kafka Analysis of the depth of the middle partition

    Kakfa reveal Day4 Kafka Analysis of the depth of the middle partition Today's talk is mainly about Kafka The number of partitions and consumer The degree of parallelism in . From using Kafka From the angle of , These are crucial . Zoning principles Partition Representing one to ...

  6. Python The way ,Day4 - Python Basics 4 (new edition )

    Python The way ,Day4 - Python Basics 4 (new edition )   Content of this section iterator & generator Decorator Json & pickle Data serialization Software directory structure specification Homework :ATM Project development ...

  7. Day4 - Python Basics 4 iterator 、 Decorator 、 Software development specifications

    Python The way ,Day4 - Python Basics 4 (new edition )   Content of this section iterator & generator Decorator Json & pickle Data serialization Software directory structure specification Homework :ATM Project development ...

  8. ##DAY4 The basic concept of events 、 The basic concept of touch 、 Responder chain 、 gesture

    ##DAY4   The basic concept of events . The basic concept of touch . Responder chain . gesture #pragma mark ——————— The basic concept of events  ——————————— The basic concept of events : 1) The event is when the user's finger touches the screen and on the screen ...

  9. Day4:T1 Tips ( Similar to pointer operation )T2 Search for + Little details

    Day4: There are a lot of tricks get T1 I haven't heard any technical terms like this , It's a bit like pointer operation , I have encountered many such problems before Every time it comes in a different form , But I think it's a little bit close ( For example, one day ...

  10. Python The basic chapter -day4

    Contents of this section : 1. Character encoding 2. function 2.1 Parameters 2.2 Variable 2.3 Return value 2.4 recursive 2.5 Programming paradigm 2.6 Higher order function *************************************** ...

Random recommendation

  1. Use APC cache PHP opcode

    1.   About the version my php The version is 5.3.10   First use APC-3.1.8   Compile successfully , however php -m No extension , Switch to  APC-3.1.9   After the solution . 2.   About configuration apc.cac ...

  2. POI Read excel

    HSSF yes Horrible Spread Sheet Format Abbreviation Read 2007 Before version XSSF yes XML Spread Sheet Format Abbreviation   Read 2007 After version ( contain 2007)

  3. stay Firefox Pass through AJAX Cross domain access Web resources ---

    One . The solution is firefox There is no cross domain access problem in AJAX In essence, it's naming XMLHttpRequest Component to send HTTP request , Please receive the corresponding information . As for the operation after successfully receiving the response information , Just like the ordinary Web customer ...

  4. ASP----- The realization of paging function

    WEB The implementation of paging function C# Code section : // establish Linq Database connection private MYDateDataContext context = new MYDateDataContext(); / ...

  5. 3563: DZY Loves Chinese - BZOJ

    Description Seminary XJ It's a bully ,Dzy Huang Kao said JC. Take a picture of TiZhen in mengzou , But Gengyin Dzy To lower . Numerous Dzy It's beautiful inside , To cultivate energy . So it came to OI world , I want to use my divine power * Insult all living beings .  today Dzy There is a picture , There is N Seat sacrifice ...

  6. cmd Command accumulation

    dir: Show all the catalogs cd fileName: Go to the next directory cd .. : Go back to the previous Directory cd\: Return to root

  7. tnsping unable ping General questions ,TNS-12535 TNS Operation timeout ( Server environment :window server 2008R2 Database environment :oracle 11 g)

    Today, build a new database server for testing , The operating system is WIN server 2008 r2 edition . Installed in the system oracle 11g database, The database server has been configured , monitor listener Enabled . I am here ...

  8. javascript DOM Expand querySelector() And querySelectorAll()

    It's in the symbol API There are two ways at the core of this :querySelector() and querySelectorAll() querySelector(a):a It's a css Selector , Returns the first element that matches the pattern , If there is no match ...

  9. Let your :active Work hard

    In some versions of safari On ,:active Pseudo classes don't work , Can pass css and js Two ways hack once : html <div class="button"> I should turn red when I click ...

  10. selenium.common.exceptions.ElementNotVisibleException: Message: element not visible processing method :selenium Handling of pull down menu events

    Use Selenium Reptilian time , You may encounter some drop-down menus , Dynamic loading , If used directly find_element_by_ The function will report an error , Show selenium.common.exceptions.ElementNotVi ...