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

Chapter 2 Introduction to Python

編輯:Python

Chapter two Python introduction

What is computer language

 A computer is a machine used for computers , The computer must do whatever people want it to do !
You need to control the computer through its language ( programing language )!
There is no essential difference between computer language and human language , The difference is that the subjects of communication are different !
The development of computer language has gone through three stages :
machine language
- Machine language uses binary code to write programs
- Good execution efficiency , It's too cumbersome to write
Semiotic language ( assembly )
- Use symbols instead of machine codes
- When writing a program , You don't need to use binary , It's about writing symbols
- After writing , You need to convert symbols to machine code , And then it's done by the computer
The process of converting symbols into machine code is called assembly
- The process of converting machine code into symbols , It's called disassembly
- Assembly language is generally only applicable to some hardware , Poor compatibility
High-level language
- The grammar of advanced languages is basically similar to that of English today , And the relationship with hardware is not so close
- That is to say, we can develop programs in different hardware systems through high-level language
- And advanced languages are easier to learn , Now we know that languages are basically high-level languages
- C、C++、C#、Java、JavaScript、Python ...

Compiled and interpreted languages

 Computers can only recognize binary code ( Machine code ), So any language must be converted into machine code before it is executed by computer ,
It's like print('hello') Must be converted to something like 1010101 Such machine code
Depending on the timing of the switch , Language is divided into two categories :
Compiler language
- C Language
- Compiler language , The code will be compiled into machine code before execution , Then the machine code is handed over to the computer to execute
- a( Source code ) -- compile --> b( Compiled machine code )
- characteristic :
Very fast execution
Poor cross platform
Explanatory language
- Python JS Java
- Explanatory language , The code will not be compiled before execution , Instead, compile while executing
- a( Source code )-- Interpreter --> Explain to perform
- characteristic :
The execution speed is slow
Good cross platform

Python Introduction to

Python It's interpreted language
Python( English pronunciation :/ˈpaɪθən/ American pronunciation :/ˈpaɪθɑːn/), Is a widely used high-level programming language , It's a universal programming language , By Guido · Created by van Rossum , The first edition was published in 1991 year . It can be seen as an improvement ( Add some advantages of other programming languages , Like object-oriented ) Of LISP. As an interpretative language ,Python The philosophy of design emphasizes the readability of code and concise syntax ( In particular, use space indentation to divide code blocks , Instead of using braces or keywords ). Compared with C++ or Java,Python Let developers express their ideas in less code . Whether it's a small or a large program , The language tries to make the structure of the program clear .
Life is short you need Python ( Life is too short , I use Python)
Python Use of :
WEB application
Facebook douban ...
Crawler program
Scientific Computing
Automatic operation and maintenance
big data ( Data cleaning )
Cloud computing
Desktop software / game
Artificial intelligence
...

Python Development environment construction

 Development environment construction is installation Python Interpreter
Python The interpreter classification of :
CPython( official )
use c language-written Python Interpreter
PyPy
use Python language-written Python Interpreter
IronPython
use .net Compiling Python Interpreter
Jython
use Java Compiling Python Interpreter
step :
1. Download installation package python-3.6.5.exe
- 3.x
- 2.x
2. install ( Fool installation )
3. Open the command line window , Input python The following appears
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python Interactive interface of

 When we type... On the command line Python, The interface you enter is Python Interactive interface of
structure :
Version and copyright notice :
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Command prompt :
>>>
You can type... Directly at the command prompt Python Instructions ! The input command will be Python The interpreter immediately executes !
install Python At the same time , Will automatically install a Python Development tools IDLE, adopt IDLE You can also go into interactive mode
But here's the difference , stay IDLE Through TAB Key to view the prompt of the statement .
IDLE It's actually an interactive interface , But he can have some simple tips , And you can save the code
Interaction mode only allows you to enter one line of code , It's about executing a line , So it doesn't apply to our daily development !
It can only be used to do some daily simple tests !
We usually will Python Code to a py In file , And then through python Command to execute the code in the file
practice :
Try to create one yourself py file , And write... To the file python Print statement (print...)
Then execute the file .
If the extension of your system cannot be modified , Please try your own baidu!

Python and Sublime Integration of

1. stay Sublime In the implementation of Python Code ,ctrl + b Automatically in Sublime Execute... In the built-in console
This kind of execution , In some versions of Sublime Chinese support for Chinese is not good , And can't use input() function
2. Use SublimeREPL To run the python Code
installation is complete , Set shortcut key , Hope to press f5 The current Python Code
{ "keys": ["f5"], "caption": "SublimeREPL:Python","command": "run_existing_window_command", "args":{"id": "repl_python_run","file": "config/Python/Main.sublime-menu"}},

Several concepts

1. expression
An expression is something like a mathematical formula
such as :10 + 5 8 - 4
Expressions generally only use to calculate some results , Will not have a substantial impact on the process
If you enter an expression in interactive mode , The interpreter will automatically output the result of the expression
2. sentence
Statements in a program generally need to perform certain functions , For example, print information 、 pick up information 、 Assign values to variables ...
such as :
print()
input()
a = 10
Statement execution will generally have a certain impact on the program
In interactive mode, the execution result of the statement is not necessarily output
3. Program (program)
A program is made up of statements and expressions .
4. function (function)
A function is a statement , Functions are designed to perform specific functions
The shape of a function is like :xxx()
Classification of functions :
Built in functions
- from Python Functions provided by the interpreter , Can be in Python You can use
Custom function
- Functions created by programmers
When we need to complete a function , You can call built-in functions , Or custom functions
Two elements of a function :
Parameters
- () The contents of are the parameters of the function
- There can be no arguments in the function , There can also be multiple parameters , Use... Between multiple parameters , separate
Return value
- The return value is the return result of the function , Not all functions have return values

Basic grammar

1. stay Python Strictly case sensitive in
2.Python Each line in is a statement , Each statement ends with a new line
3.Python Do not make every statement in the ( It is recommended in the specification that each line should not exceed 80 Characters )
"rulers":[80],
4. A statement can be written in multiple lines , In multiline writing, the statement is followed by \ ending
5.Python It's indented language , So in Python Don't indent in
6. stay Python Use in # To represent a comment ,# The latter are all comments , The content of the comment will be ignored by the interpreter
We can explain the program through comments , Be sure to develop a good habit of writing notes
Notes need to be simple and clear , In general, it's customary to # A space will follow

Literals and variables

 Literal quantity is a value of one , such as :1,2,3,4,5,6,‘HELLO’
Literal quantity means its literal value , In the program can be used directly literal
Variable (variable) Variable can be used to store literal amount , And the amount of literals stored in variables is variable
The variable itself doesn't mean anything , It will express different meanings according to different literal quantities
Generally when we are developing , Seldom use literal quantity directly , It's all about saving literals to variables , Use variables to reference literals

Variables and identifiers

data type

 The data type refers to the value type of the variable , That is, what values can be assigned to variables
The number
integer
Boolean value
floating-point
The plural
character string
Null value

Type checking

object (object)

- Python It is an object-oriented language
- Everything is the object !
- The program is running , All data is stored in memory and then run !
- An object is an area of memory dedicated to storing specified data
- Object is actually a container , Dedicated to storing data
- Like we learned before 、 character string 、 Boolean value 、None Are all objects
- Reference resources chart 1

Structure of objects

- There are three kinds of data to be saved in each object
- id( identification )
> id Used to identify the uniqueness of an object , Every object has a unique id
> Object's id It's the same as a person's ID number
> Can pass id() Function to view the id
> id It's generated by the parser , stay CPython in ,id Is the memory address of the object
> Object once created , Then it's id Never change again
- type( type )
> Type is used to identify the type of the current object
> such as :int str float bool ...
> Type determines what functions an object has
> adopt type() Function to see the type of object
> Python It's a strong type of language , Once an object is created, it cannot be modified
- value( value )
> Value is the specific data stored in the object
> For some object values can be changed
> Objects are divided into two categories , The variable object Immutable object
The value of a mutable object can be changed
The value of an immutable object cannot be changed , The objects we studied before are immutable objects
- Reference resources chart 2
practice : Try to draw the memory structure of the object by yourself .

Variables and objects

- Objects are not stored directly in variables , stay Python Middle variable is more like an alias for an object
- The value stored in the variable is not the value of the object , It's about the object id( Memory address ),
When we use variables , It's actually going through the object id Looking for objects
- Objects stored in variables , It will only change if the variable is reassigned
- Variables and variables are independent of each other , Modifying one variable does not affect the other
- Reference resources chart 3

Type conversion

- So called type conversion , Convert an object of one type to another
- Type conversion is not about changing the type of the object itself , Instead, create a new object based on the value of the current object

Operator ( The operator )

- Operators can operate on one or more values or various operations
- such as + 、-、= All belong to operators
- Classification of operators :
1. Arithmetic operator
2. Assignment operator
3. Comparison operator ( Relational operator )
4. Logical operators
5. Conditional operator ( Ternary operator )

Code

01. Basic concepts .py

print('hello',' ha-ha ','abc')
print(123)
print('bcd')
a = 20
print(a)

02. Basic grammar .py

print('he\
aaa\
aaa')
# This is a print statement , Please don't panic when you see it 
# This is a comment 
# Comments are ignored by the interpreter 
# print(123+456) This line of code is annotated , Will not be executed 
print('abc') # This is a single line comment 

03. Variables and identifiers .py

# Python Using variables in , No declaration required , Just assign a value to the variable 
a = 10
# You can't use variables that haven't been assigned 
# If you use a variable that has not been assigned a value , Will report a mistake NameError: name 'b' is not defined
# print(b)
# Python Is a dynamic type of language , You can assign any type of value to a variable , You can also change the value of a variable 
a = 'hello'
# print(a)
# identifier 
# stay Python All the contents that can be named by themselves belong to identifier 
# such as : Variable name 、 Function name 、 Class name 
# Identifiers must follow the specification of identifiers 
# 1. Identifiers can contain letters 、 Numbers 、_, But you can't start with a number 
# Example :a_1 _a1 _1a
# 2. Identifier cannot be Python Keywords and reserved words in 
# Not recommended Python The function name in as an identifier , Because this will cause the function to be overridden 
# 3. Naming specification :
# stay Python Pay attention to two kinds of naming rules :
# Underline nomenclature 
# All letters lowercase , Use... Between words _ Division 
# max_length min_length hello_world xxx_yyy_zzz
# PASCAL nomenclature ( The name of the great hump ) 
# title case , Each word begins with a capital letter , The rest of the letters are lowercase 
# MaxLength MinLength HelloWorld XxxYyyZzz 
# 
# If you use non-conforming identifiers , Will be an error SyntaxError: invalid syntax 
# practice : Try to define a few variables yourself ( More complicated , Try different nomenclature ), Then print some variables 
# What other naming conventions do you have to search through search engines 
_b123 = 20
# print(_b123)
# print = 123
# print(print)

04. The number .py

# stay Python There are three kinds of values : Integers 、 Floating point numbers ( decimal )、 The plural 
# stay Python All integers in are int type 
a = 10
b = 20
# Python There is no limit to the size of integers in , It can be an infinite integer 
# c = 999999999999999999999999999999999999999999999 ** 100
# If the number is too long , You can use underscores as separators 
c = 123_456_789
# d = 0123 10 A decimal number cannot be in 0 start 
# Other base integers , As long as it is digital printing, it must be displayed in decimal form 
# Binary system 0b start 
c = 0b10 # The binary 10
# octal 0o start 
c = 0o10
# Hexadecimal 0x start 
c = 0x10
# You can also use operators to operate on numbers , And it can guarantee the accuracy of integer operation 
c = -100
c = c + 3
# Floating point numbers ( decimal ), stay Python All the decimals in are float type 
c = 1.23
c = 4.56
# When calculating floating-point numbers , You may get an imprecise result 
c = 0.1 + 0.2 # 0.30000000000000004
print(c)

05. character string .py

# character string (str)
# String is used to represent a piece of text information , String is the most commonly used data type in a program 
# stay Python The middle string needs to be enclosed in quotation marks 
s = 'hello'
# s = abc # Strings must be enclosed in quotation marks , Don't use non strings 
# Quotes can be double quotes , It can also be a single quotation mark , But be careful not to mix 
s = 'hello'
s = "hello"
# s = 'hello" Quotation marks cannot be mixed SyntaxError: EOL while scanning string literal
# The same quotes cannot be nested 
# s = " Confucius said :" Learn from time to time , Joy, joy, joy !""
s = ' Confucius said :" Learn from time to time , Joy, joy, joy !"'
# Long string 
# Single and double quotation marks cannot be used across lines 
s = ' Hoe standing grain gradually pawning a midday ,\
Sweat dripping under the grass ,\
Who knows what's on the plate ,\
Every grain is hard '
# Use triple quotes to represent a long string ''' """
# Triple quotes can wrap , And will keep the format in the string 
s = ''' Hoe standing grain gradually pawning a midday , Sweat dripping under the grass , Who knows what's on the plate , Every grain is hard '''
# Escape character 
# have access to \ As escape character , By escaping characters , You can use something special in a string 
# Example :
# \' Express '
# \" Express "
# \t Represents a tab 
# \n Represents a newline character 
# \\ Indicates a backslash 
# \uxxxx Express Unicode code 
s = " Confucius said :\" Learn from time to time ,\\\\n Joy, joy, joy !\""
s = '\u2250'
print(s)

06. Formatted string .py

# Formatted string 
a = 'hello'
# Strings can also be added between 
# If you add two strings , Will automatically splice the two strings into one 
a = 'abc' + 'haha' + ' ha-ha '
# a = 123 
# Strings can only be added to other types , If you do it, you will have an exception TypeError: must be str, not int
# print("a = "+a) # It's written in Python Not common in 
a = 123
# print('a =',a)
# When creating a string , You can specify placeholders in the string 
# %s To represent any character in a string 
# %f Floating point placeholder 
# %d Integer placeholder 
b = 'Hello %s'%' The Monkey King '
b = 'hello %s Hello %s'%('tom',' The Monkey King ')
b = 'hello %3.5s'%'abcdefg' # %3.5s The length of the string is limited to 3-5 Between 
b = 'hello %s'%123.456
b = 'hello %.2f'%123.456
b = 'hello %d'%123.95
b = ' ha-ha '
# print('a = %s'%a)
# Formatted string , You can do this by adding a... Before the string f To create a formatted string 
# Variables can be embedded directly in the formatted string 
c = f'hello {
a} {
b}'
print(f'a = {
a}')
# practice Create a variable to hold your name , Then there are four ways to format strings 
# Show... On the command line , welcome xxx presence !

07. Copy string .py

# Create a variable to hold your name 
name = ' The Monkey King '
# There are four ways to output , welcome xxx presence 
# Concatenation 
print(' welcome '+name+' presence !')
# Multiple parameters 
print(' welcome ',name,' presence !')
# Place holder 
print(' welcome %s presence !'%name)
# Formatted string 
print(f' welcome {
name} presence !')
# Copy of string ( Multiply a string by a number )
a = 'abc'
# * To express multiplication in language 
# If you multiply a string by a number , The interpreter repeats the string a specified number of times and returns 
a = a * 20
print(a)

08. Boolean and null values .py

# Boolean value (bool)
# Boolean value is mainly used for logical judgment 
# There are two Boolean values True and False
# True Said really False Said the false 
a = True
a = False
# print('a =',a)
# Boolean values are actually integers ,True Equivalent to 1,False Equivalent to 0
# print(1 + False)
# None( Null value )
# None Used specifically to indicate that there is no 
b = None
print(b)

09. Type checking .py

# Pass the type check , Can check only values ( Variable ) The type of 
a = 123 # The number 
b = '123' # character string 
# print('a =',a)
# print('b =',b)、
# type() Used to check the type of value 
# This function returns the result of the check as a return value , You can receive the return value of a function through a variable 
c = type('123')
c = type(a)
# print(type(b))
print(type(1)) # <class 'int'>
print(type(1.5)) # <class 'float'>
print(type(True)) # <class 'bool'>
print(type('hello')) # <class 'str'>
print(type(None)) # <class 'NoneType'>

10. Type conversion .py

# Type conversion four functions int() float() str() bool()
# int() Can be used to convert other objects to integers 
# The rules :
# Boolean value :True -> 1 False -> 0
# Floating point numbers : Round directly , Omit the decimal point 
# character string : Legal integer string , Convert directly to the corresponding number 
# If it's not a legal integer string , False report ValueError: invalid literal for int() with base 10: '11.5'
# For other objects that cannot be converted to integers , Throw an exception directly ValueError
# float() and int() Almost the same , The difference is that it converts objects to floating-point numbers 
# str() You can convert an object to a string 
# True -> 'True'
# False -> 'False'
# 123 -> '123' 
# ...
# bool() You can convert objects to Boolean values , Any object can be converted to a Boolean value 
# The rules : All objects that represent emptiness are converted to False, The rest is converted into True
# The emptiness of which representations :0 、 None 、 '' ...
a = True
# call int() to a Convert to integer 
# int() Function does not affect the original variable , It converts the object to the specified type and returns it as a return value 
# If you want to change the original variable , You need to reassign the variable 
a = int(a)
a = False
a = int(a)
a = '123'
a = int(a)
a = 11.6
a = int(a)
a = '11.5'
# a = int(a)
a = None
# a = int(a)
a = 1
a = float(a)
a = False
a = float(a)
a = 123
a = str(a)
a = None
a = bool(a)
print('a =',a)
print('a The type is ',type(a))
# b = 456
# print('hello'+str(b))

11. Arithmetic operator .py

# Arithmetic operator 
# + The addition operator ( If it's an addition between two strings , String splicing will be performed )
# - Subtraction operators 
# * Multiplication operators ( If you multiply a string by a number , Then the string will be copied , Repeat the string a specified number of times )
# / Division operator , The result will always return a floating point type 
# // to be divisible by , Only the whole digits after calculation will be reserved , Always return to an integer 
# ** Power operation , Find the power of a value 
# % modulus , Find the remainder of the division of two numbers 
a = 10 + 5 # Calculation 
a = 'hello' + ' ' + 'world' # Concatenation 
a = 10 - 5 # Calculation 
a = 5 - True
a = a - 2 # With variable a The value of minus 2, And then assign it to a
# a = 'hello' - 'h' TypeError
a = 5 * 5
a = 10 / 5
a = 5 / 2
# a = 5 / 0 ZeroDivisionError: division by zero
a = 10 / 3
a = 10 // 3
a = 5 // 2
a = 2 ** 2
a = 10 ** 5
a = 16 ** 0.5 # seek 16 The square root of 
a = 10 % 5 # 0
a = 10 % 4 # 2
a = 10 % 3 # 1
a = 10 % 2 # 0
print("a =",a)

12. Assignment operator .py

# Assignment operator 
# = The value to the right of the equal sign can be assigned to the variable to the left of the equal sign 
# += a += 5 amount to a = a + 5 
# -= a -= 5 amount to a = a - 5 
# *= a *= 5 amount to a = a * 5 
# **= a **= 5 amount to a = a ** 5 
# /= a /= 5 amount to a = a / 5 
# //= a //= 5 amount to a = a // 5 
# %= a %= 5 amount to a = a % 5 
a = 10
# a = a + 5
# a += 5
a -= 5
a *= 5
a **= 2
a /= 25
a = 25.0 # When doing arithmetic operations on floating-point numbers , The result also returns a floating-point number 
a //= 5
a = 5
a %= 4
print('a =',a)

13. Relational operator .py

# Relational operator 
# Relational operators are used to compare the relationship between two values , Always return a Boolean value 
# If the relationship works , return True, Otherwise return to False
# > Compare left value with right value 
# >= Compare whether the value on the left is greater than or equal to the value on the right 
# < Compare left value with right value 
# <= Compare whether the value on the left is less than or equal to the value on the right 
# == Compare the values of two objects for equality 
# != Compare two objects for unequal values 
# Equality and inequality compare the value of an object , instead of id
# is Compare whether two objects are the same object , Compared to the object id
# is not Compare whether two objects are not the same object , Compared to the object id
result = 10 > 20 # False
result = 30 > 20 # True
result = 30 < 20 # False
result = 10 >= 10 # True
result = 2 > True # True
# result = 2 > '1' TypeError: '>' not supported between instances of 'int' and 'str'
# 0032 > 0031
result = '2' > '1' # True
result = '2' > '11' # True
# stay Python Two strings can be greater than ( be equal to ) Or less than ( be equal to ) Arithmetic ,
# When comparing strings , It's actually comparing strings Unicode code 
# Compare two strings of Unicode When coding , It's a bit by bit comparison 
# With this feature, strings can be sorted alphabetically , But it doesn't mean much to Chinese 
# Be careful : If you don't want to compare two strings Unicode code , It needs to be converted to numbers and then compared 
# 0061 > 0062
result = 'a' > 'b' # False
result = 'c' < 'd' # True
result = 'ab' > 'b' # False
# print(int('2') > int('11'))
result = 1 == 1 # True
result = 'hello' == 'hello' # True
result = 'abc' == 'bcd' # False
result = 'abc' != 'bcd' # True
result = 1 == True # True
result = 1 is True # False
result = 1 is not True # True
print('result =',result)
print(id(1),id(True))

14. Logical operators .py

# Logical operators 
# Logical operators are mainly used to make some logical judgments 
# not Logic is not 
# not You can do a non operation on the value to the right of the symbol 
# For Boolean , Non operation will reverse it ,True change False,False change True
# For non Boolean values , The non operation will first convert it to a Boolean value , Then reverse 
# 
# and Logic and 
# and The values on both sides of the symbol can be calculated 
# Only the values on both sides of the symbol are True when , Will return True, As long as there is one False Just go back to False
# And arithmetic is to find False Of 
# Python The sum operation in is short circuited and , If the first value is False, No longer look at the second value 
# 
# or Logic or 
# or You can do or operate on the values on both sides of the symbol 
# Or just one of the two values True, It will return True
# Or arithmetic is to find True Of 
# Python The or operation in is short circuited or , If the first value is True, No longer look at the second value 
# 
# practice :
# Try three logical operations on Boolean values 
# Try three logical operations on non Boolean values , And watch the results 
# 
a = True
a = not a # Yes a Perform non operation 
a = 1
a = ''
a = not a
# print('a =',a)
result = True and True # True
result = True and False # False
result = False and True # False
result = False and False # False
# print(result) 
# True and print(' You guess I came out ?') The first value is True, Will see the second value , therefore print() Will execute 
# False and print(' You guess I came out ?') The first value is False, Don't look at the second value , therefore print() Not execute 
result = True or True # True
result = True or False # True
result = False or True # True
result = False or False # False
# print(result) 
# False or print(' You guess I came out ?') The first value is False, Keep looking at the second , So print statement execution 
# True or print(' You guess I came out ?') The first value is True, Don't look at the second , So the print statement doesn't execute 
# The sum or operation of a non Boolean value 
# When we do sum or operations on non Boolean values ,Python It will be treated as a Boolean operation , It will eventually return the original value 
# And the rules of operation 
# And arithmetic is to find False Of , If the first value is False, Then don't look at the second value 
# If the first value is False, Then directly return the first value , Otherwise return the second value 
# Or the rules of operation 
# Or arithmetic is to find True Of , If the first value is True, Then don't look at the second value 
# If the first value is True, Then directly return the first value , Otherwise return the second value 
# True and True
result = 1 and 2 # 2
# True and False
result = 1 and 0 # 0
# False and True
result = 0 and 1 # 0
# False and False
result = 0 and None # 0
# True or True
result = 1 or 2 # 1
# True or False
result = 1 or 0 # 1
# False or True
result = 0 or 1 # 1
# False or False
result = 0 or None # None
print(result)

15. Conditional operator .py

# Conditional operator ( Ternary operator )
# grammar : sentence 1 if Conditional expression else sentence 2
# Execute the process :
# Conditional operators are executed , Will evaluate the conditional expression first 
# If the result is True, Then execute the statement 1, And return the execution result 
# If the result is False, Then execute the statement 2, And return the execution result 
# practice :
# Now there is a b c Three variables , There are three values in each of the three variables ,
# Get the maximum of the three values through the conditional operator 
# print(' Hello ') if False else print('Hello')
a = 30
b = 50
# print('a Is larger !') if a > b else print('b Is larger !')
# obtain a and b The greater of 
max = a if a > b else b
print(max)

16. Operator precedence .py

a = 40
b = 50
c = 30
# Get the maximum of the three values through the conditional operator 
# max = a if a > b else b
# max = max if max > c else c
max = a if (a > b and a > c) else (b if b > c else c) # This is not recommended 
# max = a if (b < a > c) else (b if b > c else c)
# print(max)
# Operator precedence 
# As in Mathematics , stay Python Operations also have priority , For example, multiply and divide first Add or subtract after 
# The priority of operators can be queried according to the priority table ,
# The lower the position in the table, the higher the priority of the operator , The higher the priority, the higher the priority 
# If the priority is the same, calculate from left to right 
# A table of priorities , You know it's enough to have such a thing , Never remember 
# In the development process, if you encounter an unclear priority , You can change the order of operations through parentheses 
a = 1 + 2 * 3
# equally and high or high 
# If or High priority , Or two operators have the same priority 
# You need to do or operation first , Then the result is 3
# If and High priority , You should first calculate and calculate 
# Then the result is 1
a = 1 or 2 and 3
# print(a)
# Logical operators ( Add )
# Logical operators can be used in conjunction with 
result = 1 < 2 < 3 # amount to 1 < 2 and 2 < 3
result = 10 < 20 > 15
print(result)

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