程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

6.1_ 3 Python3. X entry P3 [basic] process statement [loop structure]

編輯:Python

Related links

  • Catalog
  • Mac M1 Python Environment building
  • Python3.x introduction P1 【 Basics 】 notes 、 identifier 、 Variable 、 data type
  • Python3.x introduction P2 【 Basics 】 Operator
  • Python3.x introduction P3 【 Basics 】 Process statement 【 Loop structure 】
  • Python3.x introduction P4 【 Basics 】 Variable sequence ( list list、 Dictionaries dict、 aggregate set)
  • Python3.x introduction P5 【 Basics 】 Immutable sequence ( Tuples tuple、 character string str)
  • Python3.x introduction P6 【 String formatting 】 Four ways ( Manual 、%-formatting、str.format()、f-String)
  • Python3.x introduction P7 【 function 】

brief introduction

""" @author GroupiesM @date 2022/4/27 15:44 @introduction """
Any simple or complex algorithm can be structured by sequence 、 Selection structure 、 The circular structure is combined
Sequential structure ( The default is the sequential structure )
Selection structure :if sentence
Loop structure :while sentence ,for-in sentence

One 、 Sequential structure ( A little )

""" @author GroupiesM @date 2022/4/27 16:05 @introduction """

Two 、 Selection structure

2.1 if、elif、else Selection structure

""" @author GroupiesM @date 2022/4/27 16:05 @introduction if Conditional expression : Conditional executors else """
money = 1000; # balance 
tips = " The current balance is " + str(money) + " element , Please enter the withdrawal amount :"
get = int(input(tips)) # Withdrawal amount 
b = True
# Judge whether the balance is sufficient 
if get < 0:
print(" The withdrawal amount cannot be negative ")
elif get < money:
print(" Successful withdrawals , The balance is " + str(money - get), " element .")
else:
print(" Lack of balance .")
""" The current balance is 1000 element , Please enter the withdrawal amount :-5 The withdrawal amount cannot be negative Successful withdrawals , The balance is 1005 element . """
""" The current balance is 1000 element , Please enter the withdrawal amount :123 Successful withdrawals , The balance is 877 element . """
""" The current balance is 1000 element , Please enter the withdrawal amount :1234 Lack of balance . """

2.2 Select structure nesting

""" @author GroupiesM @date 2022/4/27 16:26 @introduction Business logic : If you are a member , Greater than 200 hit 1 fold ,100-200 hit 5 fold , lower than 100 No discount If not a member , Greater than 200 hit 9 fold , lower than 200 No discount """
isMember = input(" Are you a member ?y/n:")
if isMember not in ('y','n'):
print(" Input error ")
quit()
money = int(input(" The amount of money purchased :"))
if isMember == 'y':
if money > 200:
money *= 0.1
elif money > 100 & money < 200 :
money *= 0.5
if isMember == 'n':
if money > 200:
money *= 0.9
print(" The actual payment amount is :",str(money))
""" Are you a member ?y/n:y The amount of money purchased :2000 The amount of payment is : 200.0 """
""" Are you a member ?y/n:n The amount of money purchased :150 The actual payment amount is : 150 """

3、 ... and 、 Conditional expression ( Ternary operator )

""" @author GroupiesM @date 2022/4/27 16:39 @introduction Simulate user login The conditional expression is similar to Java Ternary operator used in , have only if、else Two results , No other elif Branch condition """
uname = input(" user name :")
pwd = input(" password :")
# Selection structure 
if uname == "Groupies" and pwd =="123":
print(" Welcome landing !")
else:
print(" Wrong user name or password !")
print('-----')
# Conditional expression 
print(" Welcome landing !" if uname == "stenven" and pwd =="123" else " Wrong user name or password !")

Four 、 Loop structure

4.1 rang() loop - Generate list

""" @author GroupiesM @date 2022/4/27 16:55 @introduction Used to create a sequence of integers establish range Three ways of objects 1)range(stop): establish [0,stop) A sequence of integers between , In steps of 1 2)range(start,stop): establish [start,stop) A sequence of integers between , In steps of 1 3)range(start,stop,step): establish [start,stop) A sequence of integers between , In steps of step Returns an iterator object range advantage : No matter range How long is the sequence of integers represented by object , all range Objects take up the same amount of memory , Because you just need to store start,stop and step, Only when used will it be calculated int And not in Determine whether there is a specified integer """
"""range(stop)"""
r = range(10)
l = list(r) # For viewing range Object 
print(l) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""range(start,stop,step)"""
r = range(1, 50, 5)
l = list(r)
print(l) # [1, 6, 11, 16, 21, 26, 31, 36, 41, 46]
"""int And not in Determine whether there is a specified integer """
print(6 in r) # True
print(6 in l) # True
print(8 in r) # False
print(6 not in l) # False

4.2 while loop

""" @author GroupiesM @date 2022/4/27 17:08 @introduction Cycle classification while for-in grammar : while Conditional expression : Conditional executors ( The loop body ) Choose structural if And the cycle while The difference between : if Judge once , Conditions True Do it once while Judge n+1 Time , Condition is True perform n Time """
a: int = 1
while a < 5:
print(a) # 1 2 3 4
a += 1

4.3 for loop

""" @author GroupiesM @date 2022/4/27 17:16 @introduction for-in loop : in Expression from ( character string 、 Sequence, etc ) Take values in order , It's also called traversal for-in The convenience object must be an iteratable object for-in Grammatical structure : for Custom variables in Iteratable object : The loop body 【 Iteratable object 】: character string 、 Sequence, etc There is no need to access custom variables inside the loop , You can replace custom variables with underscores """
print("-------for-in String--------")
for i in "python":
print(i)
""" p y t h o n """
print("-------for-in range()--------")
for i in range(2, 5, 1):
print(i)
""" 2 3 4 """
print("-------for-in nothing--------")
for i in range(3):
print("hello world")
""" hello world hello world hello world """
print("-------for-in 1-100 Even sum --------")
sum = 0;
for i in range(101):
if i % 2 == 0:
sum += i
print(sum)
"""2550"""

5、 ... and 、pass、break、continue


5.1 pass skip

  • Apply to : Selection structure 、 Loop structure
""" @author GroupiesM @date 2022/4/27 16:44 @introduction pass sentence : Don't do anything? , Just a placeholder , It's used where syntax requires statements Don't skip ,pass Before the statement 、 The following execution logic when: First, build the grammatical structure , I haven't figured out how to write the code yet where:1)if Conditional executor of 、2)for-in Circulatory body of 、3) The body of a function """
answer = input(" Are you a member ?y/n")
if answer == 'y':
print("123")
pass
print("321")
else:
pass # If you don't write anything here, you can't compile it 
""" Are you a member ?y/n y 123 321 """

5.2 break Out of the loop

5.2.1 while - break

  • Apply to : Loop structure
""" @author GroupiesM @date 2022/4/27 17:34 @introduction break sentence : Used to end the loop structure , Usually with branch structure if Use it together """
# Enter the password on the keyboard , most 3 Time , If correct , Prompt for successful login , exceed 3 The second prompt account is locked 
password = "python"
i = 0;
while i < 3:
if input(" Please input a password :\n") == "python":
print(" The password is correct , Landing successful ")
break
elif i != 2:
print(" Wrong password , Remaining attempts :", 2 - i)
i += 1
else:
print(" Wrong password , Account locked ")
break
""" Please input a password : python The password is correct , Landing successful """
""" Please input a password : 1 Wrong password , Remaining attempts : 2 Please input a password : 2 Wrong password , Remaining attempts : 1 Please input a password : 3 Wrong password , Account locked """

5.2.2 for - break

""" @author GroupiesM @date 2022/4/27 17:25 @introduction break sentence : Used to end the loop structure , Usually with branch structure if Use it together """
# Enter the password on the keyboard , most 3 Time , If correct , Prompt for successful login , exceed 3 The second prompt account is locked 
password = "python"
for i in range(3):
if input(" Please input a password :\n") == "python":
print(" The password is correct , Landing successful ")
break
elif i != 2:
print(" Wrong password , Remaining attempts :", 2 - i)
else:
print(" Wrong password , Account locked ")

5.2.3 Nested loop - break ( multiplication table )

""" @author GroupiesM @date 2022/4/27 17:51 @introduction """
''' Realization 99 Multiplication table '''
for i in range(0, 10, 1):
for j in range(1, i + 1, 1):
if j > i:
break
print(str(i), "*", str(j), "=", str(i * j), end="\t")
print("")
''' 1 * 1 = 1 2 * 1 = 2 2 * 2 = 4 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 '''

5.3 continue Enter next cycle

  • Apply to : Loop structure

5.3.1 while - continue

""" @author GroupiesM @date 2022/4/27 17:36 @introduction continue sentence : Used to end the current loop , Enter next cycle , Usually pre branch if Use it together """
''' Output 1-20 Between all 5 Multiple '''
i: int = 1;
while i < 20:
i += 1
if i % 5 != 0: continue
print(i)
""" 5 10 15 20 """

5.3.2 for - continue

""" @author GroupiesM @date 2022/4/27 17:37 @introduction continue sentence : Used to end the current loop , Enter next cycle , Usually pre branch if Use it together """
''' Output 1-20 Between all 5 Multiple '''
i: int = 1;
for i in range(20):
if i % 5 != 0: continue
print(i)
""" 5 10 15 20 """

5.3.3 Nested loop - continue

""" @author GroupiesM @date 2022/4/28 09:14 @introduction In a nested loop break and continue It is only used to control the circulation of this layer else -> if ... else -> while ... else -> for ... else """
for i in range(1, 5):
if (i % 2 == 0):
continue
else:
print(i)
else:
print("abc")
""" 1 3 abc """

22/06/27

M


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved