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

Python notes 03

編輯:Python

Python03

Python03 Object's Boolean program organization structure sequence structure selection structure single branch structure double branch structure multi branch structure nesting if Conditional expression pass sentence *range() Use loop structure of function while loop for-in Flow control statement breakcontinueelse Statement nested loop in a double loop break and continue

Boolean value of the object

  • Python Everything is an object , All objects have a Boolean value

  • Use built-in functions bool() Gets the Boolean value of the object

# Boolean values of test objects
print(' The Boolean value of the following object is false')
print(bool(False))  # False
print(bool(0))  # False
print(bool(0.0))  # False
print(bool(None))  # False
print(bool(''))  # False
print(bool(""))  # False
print(bool([]))  # An empty list False
print(bool(list()))  # An empty list False
print(bool(tuple()))  # An empty tuple False
print(bool({}))  # An empty dictionary False
print(bool(dict()))  # An empty dictionary False
print(bool(set()))  # Empty set False
print(' Boolean values for other objects are True')
print(bool(18))
print(bool(1.1))
print(bool('hello'))

The organizational structure of the program

Sequential structure

# Sequential structure
''' Put the elephant in the fridge in a few steps '''
print('-------- Program starts ----------')
print('1. Open the refrigerator door ')
print('2. Put the elephant in the refrigerator ')
print('3. Close the refrigerator door ')
print('-------- Program end ----------')

Selection structure

Single branch structure

money = 1000  # balance
s = int(input(' Please enter the withdrawal amount '))  # Withdrawal amount
# Judge whether the balance is sufficient
if money >= s:
   money = money - s
   print(' Successful withdrawals , The balance is :', money)

Two branch structure

# Two branch structure if...else, Choose one of the two
''' Enter an integer from the keyboard , Judge whether it's odd or even '''
num = int(input(' Please enter an integer '))
# conditional
if num % 2 == 0:
   print(num, ' It's even ')
else:
   print(num, ' Is odd ')

Multi branch structure

# Multi branch structure , Select one more to execute
'''
Enter an integer from the keyboard , achievement
90-100 a
80-89 b
70-79 c
60-69 d
0-59 e
Less than 0 Or greater than 100 Illegal data
'''
score = int(input(' Please enter a grade '))
# Judge
if score >= 90 and score <=100:
   print('A level ')
elif score >=80 and score <=89:
   print('B level ')
elif 70 <= score <= 79:
   print('C level ')
elif score >=60 and score <=69:
   print('D level ')
elif score >=0 and score <=59:
   print('E level ')
else:
   print(' Illegal grades ')

nesting if

''' members   >=200 20 percent discount
      >= 100 10% off
      No discount
  Non members >=200 5% off
        No discount
'''
answer = input(" Are you a member ?y/n")
money = float(input(" Please enter your purchase amount "))
# If you are a member
if answer == 'y':# members
   print(' members ')
   if money >= 200:
       print(" The payment amount :", money*0.8)
   elif money>=100:
       print(" The payment amount :", money * 0.9)
   else:
       print(" No discount , The payment amount :", money)
else:
   print(' Non members ')
   if money >= 200:
       print(" The payment amount :", money*0.95)
   else:
       print(" No discount , The payment amount :", money)

Conditional expression

# Conditional expression
''' Enter two integers from the keyboard , Compare the size of two integers '''
num_a = int(input(' Please enter the first integer :'))
num_b = int(input(' Please enter the second integer :'))
# Compare the size
'''if num_a >= num_b:
  print(num_a, ' Greater than or equal to ', num_b)
else:
  print(num_a, ' Less than ', num_b)'''
print(' Use conditional expressions to compare ')
print(str(num_a) + ' Greater than or equal to ' + str(num_b)  if num_a >= num_b else  str(num_a) + ' Less than ' + str(num_b))

pass sentence

  • pass Sentences do nothing , Just a placeholder , It's used where syntax requires statements

# pass sentence
answer = input(' Are you a member ?y/n')
# Judge whether you are a member
if answer == 'y':
   pass
else:
   pass

*range() Use of functions

  • The default starting value is 0

  • The default step size is 1

  • Built in functions range()

  • Used to generate a sequence of integers

  • The return value is an iterator object

  • use in or not in Determine whether an integer exists

  • 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 range Object time , To calculate the relevant elements in the sequence

# range() Three ways to create
​
''' The first way to create it , There is only one parameter ( Only one number is given in parentheses ) '''
r = range(10)   # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], The default from the 0 Start , Default phase difference 1 Step length
print(r)    # range(0,10)
print(list(r))  # For viewing range Object -->list It means list
​
''' The second way to create , Give two parameters ( Give two numbers in parentheses )'''
r = range(1,10)  # The starting value... Is specified , from 1 Start , To 10 end ( It doesn't contain 10), The default step size is 1
print(r)  # range(1, 10)
print(list(r))  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
​
''' The third way to create , Given three parameters ( Three parameters are given in parentheses )'''
r = range(1, 10, 2)
print(list(r))  # [1, 3, 5, 7, 9]
''' Judge the specified integer , Whether there is... In the sequence , in , not in'''
print(10 in r)  # False ,10 Not in the current r In this sequence of integers
print(9 in r)  # True, 9 In the current r This sequence
​
print(10 not in r)  # True, 10 Not in the current r This sequence
print(9 not in r)  # False ,9 Not in the current r In this sequence of integers
​
print(range(1, 20, 1))
print(range(1, 100, 1))
'''- 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 range Object time , To calculate the relevant elements in the sequence '''

Loop structure

while loop

  • It is used to solve the cycle with an indefinite number of times

  • while Cycle and selection if The difference between :if It's a judgment , Condition is True Do it once ;while Is a judgment n+1 Time , Condition is True perform n Time

  • Four step cycle method

    1. Initialize variable
    2. conditional
    3. Conditional executors
    4. Change variables 
    • summary : The initialized variable is the same as the conditional judgment variable and the changed variable

      # Loop structure
      a = 1
      # The expression of judgment condition
      while a < 10:
         # Execution condition executor
         print(a)
         a += 1
# Calculation 0-4 Cumulative sum between
''' The initialization variable is 0'''
a = 0
sum = 0  # Used to store cumulative sum
''' conditional '''
while a < 5:
   ''' Conditional executors ( The loop body )'''
   sum += a
   a += 1
print(' And for ', sum)
# Calculation 1-100 Between even numbers and
''' Initialize variable '''
a = 1
sum = 0  # Used to store even numbers and
''' conditional '''
while a <= 100:
   ''' Conditional executors ( The loop body )'''
   if not bool(a % 2):
       sum += a
   ''' Change variables '''
   a += 1
print("1-100 Between even numbers and ", sum)

for-in

  • in Expression from ( character string 、 Sequence ) Take values in order , It's also called traversal

  • for-in The traversal object must be an iteratable object

  • Grammatical structure for Custom variables in Objects that can be iterated :

    The loop body

for item in 'Python': # The first time I took it out was P, take P assignment item, take item Value output of
   print(item)
# range() Generate a sequence of integers --> It's also an iterative object
for i in range(10):
   print(i)
# If you don't need to use custom variables in the loop body , You can set custom variables 1 Written as “_"
for _ in range(5):
   print("i love python")
print(" Use for loop , Calculation 1-100 Between even numbers and ")
sum = 0  # Used to store even numbers and
for item in range(1, 101):
   if item % 2 == 0:
       sum += item
print('1-100 The even sum between is :', sum)
''' Output 100-999 Between the number of daffodils '''
for item in range(100,1000):
   ge = item % 10
   shi = item // 10 % 10
   bai = item //100
   # print(bai, shi, ge)
   # Judge
   if ge**3+shi**3+bai**3 == item:
       print(item)

Flow control statement

break

  • Used to end the loop structure , Usually with branch structure if Use it together

''' Enter the password from the keyboard , Enter three times at most , If correct, end the loop '''
for item in range(3):
   pwd = input(" Please input a password :")
   if pwd == "8888":
       print(" The password is correct ")
       break
   else:
       print(" Incorrect password ")
       
a = 0
while a < 3:
   ''' Conditional executors ( The loop body )'''
   pwd = input(" Please input a password :")
   if pwd == '8888':
       print(' The password is correct ')
       break
   else:
       print(' Incorrect password ')
   ''' Change variables '''
   a += 1

continue

  • Used to end the current loop , Enter next cycle , Usually associated with... In a branching structure if Use it together

''' Request output 1-50 There are many 5 Multiple '''
for item in range(1,51):
   if item % 5 == 0:
       print(item)
print('----------- Use continue-----------------')
for item in range(1,51):
   if item % 5 != 0:
       continue
   else:
       print(item)

else sentence

  • if The conditional expression does not hold and should be executed else

for item in range(3):
   pwd = input(" Please input a password :")
   if pwd == '999':
       print(" The password is correct ")
       break
   else:
       print(" Incorrect password ")
else:
   print(' I'm sorry , The password was entered incorrectly three times ')
  • stay while and for There is no break perform else

a = 0
while a < 3:
   pwd = input(" Please input a password :")
   if pwd == "888":
       print(" The password is correct ")
       break
   else:
       print(' Incorrect password ')
   # Change variables
   a += 1
else:
   print(' I'm sorry , The password was entered incorrectly three times ')

Nested loop

  • Another complete loop structure is nested in the loop structure , The inner loop is executed as the loop body of the outer loop

''' Output a rectangle with three rows and four columns '''
for i in range(1,4):
   for j in range(1,5):
       print('*', end='\t')  # Don't wrap output
   print()  # Line break 
''' Output a multiplication table '''
for i in range(1,10):
   for j in range(1,i+1):
       print(i, '*', j, '=', i*j, end='\t')
   print()

In a double cycle break and continue

# Flow control statement :break And continue Use in double cycle
for i in range(5):  # Represents the outer loop execution 5 Time
   for j in range(1,11):
       if j % 2 == 0:
           continue
       print(j, end='\t')
   print()

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