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

Python | language elements, branch structures and loop structures

編輯:Python
Author:AXYZdong Automation   Engineering Male A little bit of thinking , Have a little idea , A little bit rational ! Set a small goal , Try to be a habit ! Meet a better self in the most beautiful years ! More wonderful articles go to :  Personal home page

Language elements

Instructions and procedures
The hardware system of a computer usually consists of five parts : Arithmetic unit 、 controller 、 Memory 、 Input devices and output devices .
Combination of arithmetic unit and controller : a central processor . Execute various operations and control instructions and process data in computer software .
Combination of instructions : Program .
Common data types
  • plastic :python Can handle integer of any size (python 3 There are only  int  This kind of )
  • floating-point : Floating point numbers are decimals
  • String type : Any text enclosed in single or double quotation marks .'hello'  and  "hello"
  • Boolean type : Only  True  and  False  Two kinds of

Variable naming
  • Variable names are made up of letters 、 Numbers and underscores make up , The number can't start
  • Case sensitive ( Case indicates different variables )
  • Don't conflict with keywords and system reserved words

Use of variables
python Can be used in  type  Function to check the category of variables .
a=100

print(type(a)) # <class 'int'>

have access to python The built-in functions in convert variable types .
  • int(): Will a 【 Value or string 】 convert to 【 Integers 】
  • float(): Will a 【 character string 】  convert to 【 Floating point numbers 】
  • str(): take 【 Specified objects 】 convert to 【 character string 】
  • chr(): take 【 Integers 】 convert to 【 The string corresponding to this encoding ( A character )】
  • ord(): take 【 character string ( A character )】 convert to 【 Corresponding code ( Integers )】

chr()  and  ord()  Reverse each other .
a=1
b=2
print('%d + %d = %d' % (a,b,a+b)) #1 + 2 = 3

%d  Placeholder for integers ,%f  Placeholder for decimal , After the string  %  The following variable value will replace the placeholder and output to the terminal .
Operator
  • Arithmetic operator :**%///*-+
  • Assignment operator := += -= *= /= //=
  • Comparison operator :> < >= <= == !=
  • Logical operators :and or not
  • An operator :& | ~ ^ >> <<

Operator priority  : Monocular operator (~ + -)>  Arithmetic operator  >  An operator  >  Comparison operator . With parentheses , Parentheses take precedence .

Branching structure

One statement is executed in sequence : Sequential structure
Branching structure  ( Selection structure )
python Keywords for constructing branch structures in :if 、else 、elif
'''
Judge whether the input side length can form a triangle , If you can, calculate the perimeter and area of the triangle
Author:AXYZdong 
'''
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a+b > c and a +c > b and b+c >a :
 print(' Perimeter  = %f' % (a+b+c))
 p = (a+b+c)/2
 area = (p*(p-a)*(p-b)*(p-c))**0.5
 print(' area  = %f' % (area))
else:
 print(' Can't make a triangle ')

Loop structure

for-in  loop
Be clear about   Number of loop executions   perhaps   To iterate over a container  , Recommended  for-in  loop .
example : Calculation 1~100 The result of the summation


'''
1~100 Sum up
Author:AXYZdong 
'''
sum = 0
for x in range(101): # for x in range(1,101):
 sum = sum + x
print(sum)

  • range(101): produce 0~100 Range of integers , Can't get 101.
  • range(1,101): produce 1~100 Range of integers , amount to  [1,101)
  • range(1,101,2): produce 1~100 Odd numbers in the range , among 2 It's the step length , Each increment
  • range(100,0,-2): produce 100~1 Even numbers in the range , among -2 It's the step length , Decrease each time

1~100 Sum even numbers in the range ?
'''
use for Cycle to achieve 1~100 Sum even numbers in the range
Author:AXYZdong 
'''
sum = 0
for x in range(2,101,2): # for x in range(100,0,-2):
 sum = sum + x
print(sum)

range(2,101,2): from 2 Start with each 2 The step size is incremented , produce 2~100 The scope of the ( They are all even numbers )
while  loop
  Do not know the cycle structure of specific cycle times  , Recommended  while  loop .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 ; Expression for  False  End cycle .
'''
Guess the number game
Author:AXYZdong 
'''
import random

ans = random.randint (1,10)
counter = 0
while True:
 counter += 1
 num = int(input(' Please enter :'))
 if num > ans:
 print(' A little bigger ')
 elif num < ans:
 print(' Smaller one ')
 else:
 print(' Congratulations on your guesses ')
 break
print(' You guessed it all together %d Time '% (counter))
if counter > 5:
 print(' Your luck is too bad ')

random.randint( Parameters 1, Parameters 2)
  • Parameters 1、 Parameters 2 It has to be an integer
  • The return value of the function is the parameter 1 And parameters 2 Any number between , Closed interval  [ Parameters 1, Parameters 2](python 3 Verified in the environment )

example : Enter two positive integers , Calculate their greatest common divisor and least common multiple .
The greatest common factor : The largest number in the common factor of the two numbers Minimum common multiple : The product of two natural numbers divided by their greatest common factor
'''
Enter two positive integers , Find their greatest common divisor and least common multiple
Author:AXYZdong
'''
x = int(input('x = '))
y = int(input('y = '))
if x > y:
 x,y = y,x
for common in range(x,0,-1):
 if x%common == 0 and y%common == 0:
 print('%d and %d The greatest common divisor is %d' % (x,y,common))
 print('%d and %d The minimum common multiple is %d' % (x,y,(x*y//common)) ) # The product of two natural numbers is equal to the greatest common factor of these two numbers multiplied by their least common multiple
 break

reference
[1]:https://github.com/jackfrued/Python-100-Days[2]:Python Programming fast : Automate tedious work / ( beautiful ) Svegart (A1 Sweigart)  Writing ; Translated by Wang Haipeng . Beijing : People's post and Telecommunications Press ,2016.7[3]:Python  Chinese guide ; author : Wang Bingming , edition :v1.0
This sharing is here
If my article helps you 、 If you like the content of my article , please  “ give the thumbs-up ” “ Comment on ” “ Collection ”  One button, three links ! hear    give the thumbs-up    It's not that bad luck for people who are , Every day will be full of vitality !^ _ ^ It's not easy to code words , Everyone's support is my driving force to stick to it . Don't forget to like it   Focus on   I oh ! If any of the above is inaccurate , Welcome to leave a message below . Or you have a better idea , Welcome to exchange and study together ~~~


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