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

Python learning day-3

編輯:Python

python Study Day-3

One 、 Process control - Control the sequence of code execution

  • Sequential structure —— The code is executed from top to bottom , Each statement only runs sequentially ( Default )

    age=18
    print(' adult ')
    print(' A minor ')
    
  • Branching structure —— Choose to execute or not execute part of the code according to the conditions ( Use if)

    • if Single branch structure - If … Just …
      • Problem solved : Perform an operation when conditions are met , When the addition is not satisfied, it will not be executed

      • explain :

        • if( keyword ; Fixed writing )
        • Conditional statements ( You can any expression that has a result , Include specific numbers or operational expressions ( Except assignment ))
        • :( Fixed writing )
        • Code segment ( Structurally, it is and if One or more statements that hold an indent , Code executed only when the condition is satisfied )
      • grammar :

        if Conditional statements :
        Code segment ( Code that executes only when conditions are met
        age = 28
        if age >= 18:
        print(' adult ')
        print('=====')
        
    • if Two branch structure - If … Just … otherwise …
      • Execution process :
        First, judge the conditional statements , The result is True when , Execute code snippets 1; The result is False when , Execute code snippets 2; The code snippet must be executed 3.

        # grammar 
        Applicable if .... Just .... otherwise ...
        if Conditional statements :
        Code segment 1
        else:
        Code segment 2
        Code segment 3
        
    • if Multi branch structure - If … Just … If … Just … If … Just … otherwise …
      # grammar 
      Method 1 :
      # Do different things according to different conditions , This applies to situations where conditions are mutually exclusive .
      if Conditional statements 1:
      Code segment 1
      elif Conditional statements 2:
      Code segment 2
      elif Conditional statements 3:
      Code segment 3
      else:
      Code segment 4
      Method 2 :
      # Do different things according to different conditions , There is no relationship between multiple conditions. If one of the other conditions is true, the other conditions will not be true .
      if Conditional statements 1:
      Code segment 1
      if Conditional statements 2:
      Code segment 2
      if Conditional statements 3:
      Code segment 3
      if Conditional statements 4:
      Code segment 4
      Be careful :elif It could be any number ;else There can be or not
      
  • Loop structure —— Let the code execute repeatedly (for)

    • for Principle of circulation : Variables are taken from the sequence in turn , Until it's done ; Each order , Perform a loop body .

    • for The number of cycles of a loop is only related to the number of elements in the sequence .

    • grammar :

      for Variable in Sequence :
      The loop body
      explain - keyword ; Fixed writing
      Variable - Valid variable name ( Whether it has been defined does not affect the implementation )
      in - keyword ; Fixed writing
      Sequence - Data of container data type ( Dictionaries 、 Tuples 、 character string 、 list 、 aggregate 、 iterator 、 Generator, etc )
      : - Fixed writing
      The loop body - and for One or more statements that hold an indent ; Code that needs to be executed repeatedly
      example :
      for x in 'abc':
      print('hello world!')
      print('======')
      """ Execution process : The first 1 Time :x = 'a' -> print('hello world!') The first 2 Time :x = 'b' -> print('hello world!') The first 3 Time :x = 'c' -> print('hello world!') The loop ends ! hello world! hello world! hello world! """
      
    • for Two basic application scenarios of the loop :

      • The cumulative
      # seek 100 To 200 All can be 3 The sum of even numbers divided by integers 
      result = 0
      for x in range(102, 201, 6):
      result += x
      print(result)
      
      • Number of Statistics
      # Statistics 1000 Number of odd numbers within 
      count = 0
      for x in range(1, 1000, 2):
      count += 1
      print(count)
      
  • range( A function that produces an arithmetic sequence )

    • range(N) produce 0-N Left closed right open interval of , The difference is 1.
    • range(A,B) produce A-B Left closed right open interval of , The difference is 1.
    >>>range(10) # from 0 Start to 9
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> range(1, 11) # from 1 Start to 10
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> range(0, 30, 5) # In steps of 5
    [0, 5, 10, 15, 20, 25]
    >>> range(0, 10, 3) # In steps of 3
    [0, 3, 6, 9]
    >>> range(0, -10, -1) # negative 
    [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
    >>> range(0)
    []
    >>> range(1, 0)
    []
    

Two 、 Exercises

Basic questions

1. Print according to the range of grades entered pass perhaps fail, .

grade=int(input(' Please enter the score ( Percentage system ):'))
if 0<=grade<60:
print(' unfortunately , You failed QAQ')
else:
print(" Pass ")

2. Print according to the entered age range adult perhaps A minor , If the age is not within the normal range (0~150) Print This is not a person !.

age=int(input(' Please enter age :'))
if 0<age<18:
print(' A minor ')
elif 18<=age<150:
print(' adult ')
else:
print(' Not human ')

3. Enter two integers a and b, if a-b The result is an odd number , The result is output , Otherwise, the prompt message will be output a-b The result is not an odd number

a=int(input(' please enter an integer a:'))
b=int(input(' please enter an integer b:'))
result=a-b
if result%2==1:
print(result)
else:
print('a-b The result is not an odd number ')

4. Use for Cyclic output 0~100 All in 3 Multiple .

# Method 1 
for x in range(0,101,3):
print(x)
# Method 2 
for x in range(0,101):
if x%3==0:
print(x)

Use for Cyclic output 100~200 The inner single digit or ten digit can be 3 Divisible number .

for x in range(100,201):
if x%10%3==0 or x//10%10%3==0:
print(x)

Use for Cycle statistics 100~200 The median ten is 5 The number of

# Method 1 
for x in range(100, 201):
if x // 10 % 10 == 5:
print(x)
# Method 2 
for x in range(150,160):
print(x)

Use for Loop printing 50~150 All can be 3 Divisible but not by 5 Divisible number

for x in range(51,151,3):
if x%5!=0:
print(x)

Use for Cycle calculation 50~150 All can be 3 Divisible but not by 5 The sum of divisible numbers

count=0
for x in range(51,151,3):
if x%5!=0:
count+=x
print(count)

Statistics 100 The inner single digits are 2 And can be 3 The number of integers .

count=0
for x in range(0,101,3):
if x%10==2:
count+=1
print(count)

Advanced questions

  1. Enter any positive integer , Ask him how many digits ?

    Be careful : You can't use strings here , Only loop

    # Method 1 
    num=int(input(" Please enter a positive integer :"))
    for x in range(0,10):
    if num//(10**x)>=1:
    continue
    print(x)
    break
    # Method 2 
    num=int(input(" Please enter a positive integer :"))
    n=0
    x=0
    while n<1:
    if num//(10**x)>=1:
    x+=1
    else:
    break
    print(x)
    
  2. Print out all the daffodils , The so-called narcissus number refers to a three digit number , Its figures ⽴ The sum of the squares is equal to the number itself .例 Such as :153 yes

    ⼀ individual ⽔ Fairy flower number , because 1³ + 5³ + 3³ be equal to 153.

    for x in range(100,1000):
    a=x//100
    b=x//10%10
    c=x%10
    if a**3+b**3+c**3==x:
    print(x)
    
  3. Judge whether the specified number is a prime number ( Prime numbers are prime numbers , In addition to 1 A number other than itself that cannot be divided by other numbers )

    k=0
    num=int(input(" Please enter a positive integer :"))
    for x in range (2,num):
    if num%x==0:
    k+=1
    if k==0:
    print(' prime number ')
    else:
    print(' Not primes ')
    
  4. Output 9*9 formula . Program analysis : Branch and column considerations , common 9 That's ok 9 Column ,i The control line ,j Control the column

    for i in range(1,10):
    for j in range(1,i+1):
    print(i,'*',j,'=',i*j,end=" ")
    print('')
    
  5. This is the classic " A hundred horses and a hundred burdens " problem , There are a hundred horses , Carry a hundred loads , Big horse, big horse 3 Dan , On the back of a horse 2 Dan , Two ponies carry 1 Dan , How big is it , in , How many ponies each ?( You can directly use the exhaustive method )

for small in range(0,101):
for mid in range(0,101):
for big in range(0,101):
if big+mid+small==100 and big*3+mid*2+small/2==100:
print(' Malaysia ',big,' horse '','' Zhongma ',mid,' horse '','' The pony ',small,' horse ','.')

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