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

[Python] basic Python syntax

編輯:Python

【Python】python Basic grammar .md

C Too many seats , You will know ~ It's strange ~--- Kaikai doesn't cry ~ Kaikai is strong

I just finished writing the grammar set ,

Then make up some python Grammar point ~ Just open a third-party library ~~ This is more interesting

Even review the spelling of academic terms , It also makes sense .


Python Some notes

About whether to add the semicolon at the end of the statement

  • I saw that the semicolon can be added or not , Add no error , Although most of the time play python Not at all Get used to a language and just play it python There is no need to change your habits , Looking for a Formatting tool that will do ~
  • Python It's indented language ~ Be careful not to leave blank spaces tab
    • Report errors unexpected indent
  • Use # Notation ~ commonly # Followed by a space ~ ( Standard )

Literal literal Variable variable

In fact, it is difficult to understand the literal quantity directly ~ I understand it the other way around

  • A literal is a value that can be assigned to a variable ~
    • The number 1 , 2,3,4
    • character string "1" "2"
    • ...

python Variables do not need to be declared

  • It can be used directly
  • But you can't use variables without assignment , Will you report an error defined
  • python and js The same is dynamic language , You can assign any type of value ~, It can also be modified at will !

identifier identifier

All can be named by themselves --- Function name , Class name , Variable names belong to identifiers identifier

  • Identifier naming specification
    • Can contain alphanumeric underscores
      • No dollar sign ,js Yes
    • The number can't start
    • Keyword reserved words cannot be used ~
  • Naming method
    • Underline naming underscore case max_number
    • The short bar The actual translation should be " Mutton kebab nomenclature " kabob case max-number
    • Little hump Lower Camel Case maxNumber
    • Hump Upper Camel Case Also called Pascal Case MaxNumber

data type

The type of variable value ~ That is, the type of literal quantity ~

The number : Integers , Floating point numbers ( decimal ), The plural

  • stay Python All integers in are int type
image-20220625205827216
  • python There is no limit on the size of integers in , It can be an infinite integer
    • If the number is too large, you can use the underscore as the separator
c = 123_456_789 #  Underline at random 
  • ​ If the input content is not recognized, it will be reported invalid token

  • Other numbers in base ( I don't know how to use it )

    • 0b It starts in decimal
      • 0b10
    • 0o It starts with octal
      • 0o10
    • 0x It starts with hexadecimal
      • 0x10
  • Statements and expressions

    • Expressions do not produce substantial results , It's like half a sentence
    • A sentence is a complete sentence ~
      • c+3 Output c There is no change
      • c = c+3 That's the statement.
      • that c++ Is it a statement or an expression ~ Is the statement
  • Floating point numbers ( decimal ), stay Python All the decimals in are float type

  • When calculating floating-point numbers , You may get an imprecise result ( It's interesting )

a1 = 0.1
a2 = 0.2
print(a1+a2)  # 0.30000000000000004
####  character string 

Text message ~ String is used to represent ' Text information ' Of

Wrap in quotation marks

-    You also need to use quotation marks inside double quotation marks. You need to use single quotation marks ---`  The same quotation marks cannot be nested next to each other `

```python
a1 = ' Hoe standing grain gradually pawning a midday ,\
Sweat dripping under the grass ,\
Who knows what's on the plate ,\
Every grain is hard ,\
'
print(a1)  #  The result line
a2 = ''' Hoe standing grain gradually pawning a midday ,\
Sweat dripping under the grass ,\
Who knows what's on the plate ,\
Every grain is hard ,\
'''
print(a2)  #  No branches
a3 = ''' Hoe standing grain gradually pawning a midday ,
Sweat dripping under the grass ,
Who knows what's on the plate ,
Every grain is hard ,
'''
print(a3)  #  branch

From the above, we can find , This backslash acts like a " Soft wrap "

Just tell the interpreter , The following line breaks should not be regarded as line breaks / Connect content

It's actually called Line continuation operator ~ It is also a kind of Escape character

  • Escape character
Escape character describe \( At the end of the line ) Line continuation operator \ The backslash ’ Single quotation marks " Double quotes \b Backspace \n Line break \v Vertical tabs \t Horizontal tabs \r enter \f Change the page

There are some inconvenient web pages ~ Because it is not necessarily a single web page ~ For example, format retention . Need to keep writing escape characters

C In this respect, it is even more outrageous

Write an interesting \u0040 You can display a @ Symbol

\u After that unicode code 4 position

No dice ... The editor doesn't produce results You dare to use it directly in the browser ?

String operations

intro = ' Hello '
name = 'Shinkai'
#  The same string type can be added
print(intro + name)  #  Hello Shinkai
#  The following expression is used in python Not often
print(intro + name + "!!!!!")  #  Hello Shinkai!!!!!
#  It is usually written like this
print(intro+name, "!!!!!")  #  Hello Shinkai !!!!!

Place holder

str = 'hello %s' % ' The Monkey King ' # %s  yes  string Abbreviation 
print(str)  # hello  The Monkey King
str1 = 'hello %s  Hello  %s' % ('monkey', ' The Monkey King ')
print(str1)  # hello monkey  Hello   The Monkey King
str2 = 'hello %3s' % 'ab'  #  Minimum string length 3
print(str2)  # hello  ab
str3 = 'hello %3.5s' % 'abcdef'  #  The string length is 3-5
print(str3)  # hello abcde

%f It's a floating-point placeholder

%d Is an integer placeholder , Just round off the decimal part

Just don't use so fine ~ I just know when I study ~

General writing method

res = 'res'
print('res = %s' % res)  # res = res

Formatted string ( Better written in a similar way js)

intro = 'hello'
name = 'Shinkai'
res = f'{intro} {name}'
print(res)  # hello Shinkai

I want to play with the flowers. I read the newspaper wrong. OK .. Don't simulate everything

To summarize the string splicing methods 4 Kind of ( There are actually two kinds )

  1. String operations
  2. String parameters
  3. String placeholder
  4. String formatting

String copy

python Unique , character string *n Will repeat the string n Return times

name = 'Shinkai' * 2
print('hello ' + name)  # hello ShinkaiShinkai
print('hello', name)
print('hello %s ' % name)
print(f'hello {name} ')

Boolean value bool

logic

Boolean values are actually integers , True yes 1, False yes 0

print(1 + True)  # 2
print(1 + False)  # 1
print(1 * False)  # 0

None( It doesn't work very well )

None Does not exist Don't follow null It doesn't exist null Type but with None type

Type checking

The contents mentioned so far above, There are strings , The number , Null value

The value contains : integer ( Contains Boolean ), floating-point , The plural

Why type checking

str = '123'
num = 123
print(str)  # 123
print(num)  # 123

You can see Different types of content It's all printed out 123 I don't know the type ~

actually pycharm When the pointer is placed on the variable, it shows ~

print(type(num))  # <class 'str'>
print(type(str))  # <class 'int'>

All types of checks

#  Type checking 
print(type('123'))  # <class 'str'>
print(type(123))  # <class 'int'>
print(type(123.123))  # <class 'float'>
print(type(True))  # <class 'bool'>
print(type(None))  # <class 'NoneType'>

python It's an object-oriented language ~

To put it bluntly, today's are all object-oriented , Object - oriented is called object - oriented as long as its syntax contains declarative expressions .....

Python It's an object-oriented language

  • Everything is the object
image-20220626130532146

There are many things to learn again ~ This is the content of the operating system

Scheduling algorithm ~ Although we don't have to ~ But having one doesn't make much difference

This difference has a static data area Static variables are placed here .

What is an object

Don't write here ~ There's too much content ....

Structure of objects

Each object will have one id, type, value

We downloaded the official version of python, That is, there is no prefix python Interpreter ~ So is Cpython, Cpython Of id Is the memory address of variable storage

  • id Is a unique identifier
  • type It's the type
    • Determines what functions a variable has ( Method )
  • value It's worth it
    • Objects are divided into variable objects and immutable objects
      • The value of a mutable object can be changed ,
#  Object structure 
name = 'Shinkai'
print(id(name))  # 4313468016, 4443786352
print(type(name))  # <class 'str'>
print(name)  # Shinkai

python It's a strong type of , Once the type is created , Do not modify

Objects and variables

Objects don't actually exist directly in variables , What is actually stored is the address of the object in memory

image-20220626132252654
test = 123
test2 = test
test3 = 123
print(test == test2)  # True
print(test == test3)  # True

#  It's the same way to write

test = {"key": "value"}
test2 = test
test3 = {"key": "value"}
print(test == test2)  # True
print(test == test3)  # True
image-20220626133438697

Type conversion int(),float(),bool(),str()

Python It's a strong type , It cannot affect the declared variables , And can not be implicitly converted ~ But you can assign the content to the original variable after forced conversion ~

Variables can be assigned infinitely ~

To explain, for example int(a), Actually a Change the type of int Then copy the rest , Then give this address to a.

Integer conversion ,int()

  • Boolean value
    • Ture -> 1 Flase ->0
  • character string
    • A valid numeric string can be converted to an integer
    • Illegal ones will report errors
  • Floating point numbers
    • Round directly
  • None Report errors

Floating point conversion , float()

similar int(), But it's in decimal form

String conversion , str()

Ture->'True'

False->'False'

123->'123'

...

a=True

Turn bull ,bool()

0,None,'' Empty strings are False

Operator

classification

  • Arithmetic operator Arithmetic operator
  • Assignment operator assignment operator
  • Comparison operator ( Relational operator )relational operator
  • Logical operators logical operator
  • Conditional operator ( Ternary operator )ternary operator

Arithmetic operator 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
# **  Power operation
# %  Modulo complementary operation   The result is the remainder

Assignment operator assignment operator

= Simply assign the right value to the left

  • a+=a -> a = a+a
  • -=
  • *=
  • /=
  • //=
  • **=
  • %=

Relational operator relational operator

  • >=
  • <=
  • >
  • <
  • ==
  • !=

There is an interesting point String size comparison

print('2'>'11') # true

In fact, the string comparison is unicode code ~ Everyone 's unicode. The first greater than is true

js equally

It can be inferred that

'a'>'b' # false
'ab' > 'b' # false

It's useless but interesting .

Logical operators logical operator

Logic is not not

Logic and and

Logic or or

Short circuit operation is also available ~

  • Logic and As long as the first one is false So the result is false Will not execute the following , first true, After execution
  • Logic or As long as the first one is true So the result is true Will not execute the following , first false, After execution
False and print(a)  #  No printing 
True and print(a)  #  Print
False or print(a)  #  Print
True or print(a)  #  No printing

Non Boolean logic operation

Convert each value to a Boolean operation

res = 1 and 2 #  The first is true, Go back to the second 
res = 1 and 0 
res =  0 and 1 #  The first is false  A short circuit   Go straight back to false

or equally ~

Conditional operator

grammar : sentence 1 if expression else sentence 2

print('1') if True else print('2')

It's usually used this way

max = a if a > b else b

Namely max yes ab A medium large number

Operator priority

I suggest adding brackets first

Look at the priority table , Don't pay any attention to him Hate him , If you don't understand it diss He

sentence

Conditional statements (if sentence )Conditional statement

  • if Conditional expression : sentence
  • When only one statement is executed, it can be executed in : Followed by a statement
  • If there are multiple statements, you have to open one Code block
  • python The code block is indented ~ Restart a line without curly braces
a = 2
if a == 1:
    print('1')
    print('2')
print('3') # 3

input() Function can temporarily prevent the program from ending ~ End after entering random characters ~

if- elif -else

A few small exercises

# #  Even and odd numbers 
# num = int(input(' Enter any number '))
# print(' even numbers ' if num % 2 == 0 else ' Odd number ')

# #  Leap year judgment
# year = int(input(' Enter any year '))
# print(' Leap year ' if ((year % 100 != 0 and year % 4 == 0) or (year % 100 == 0))else ' Non leap year ')

# #  A dog is a man's age
# dog_age = int(input(' Please enter your dog's age '))
# if dog_age <= 0:
#     print(' Who are you kidding ')
# elif dog_age <= 2:
#     person_age = dog_age * 10.5
#     print(f' A dog is as old as a man {person_age}')
# else:
#     person_age = (dog_age - 2) * 4 + 21
#     print(f' A dog is as old as a man {person_age}')

#  According to the score ,  Give a reward
# score = int(input(' Please enter your score '))
# if score == 100:
#     print('niubi666')
# elif 80 <= score <= 99:
#     print(' ok ')
# elif 60 <= score <= 79:
#     print(' The butt blossoms ')
# else:
#     print('no  Reward ')
# print(bool(0))
# print(bool('0'))

#  Whether to marry or not ~
# question1 = bool(input('1 be for the purpose of , If it is not filled in, it means No ,  A house ?'))
# question2 = bool(input('1 be for the purpose of , If it is not filled in, it means No ,  A car ?'))
# question3 = bool(input('1 be for the purpose of , If it is not filled in, it means No ,  Handsome ?'))
# if question1 or question2 or question3:
#     if question1 and question2 and question3:
#         print(' Married married ')
#     else:
#         print(' You can live a little ')
# else:
#     print(' You are here to make fun of me ')

All the code

# a1 = ' Hoe standing grain gradually pawning a midday ,\
#  Sweat dripping under the grass ,\
#  Who knows what's on the plate ,\
#  Every grain is hard ,\
# '
# print(a1)  #  The result line
# a2 = ''' Hoe standing grain gradually pawning a midday ,\
#  Sweat dripping under the grass ,\
#  Who knows what's on the plate ,\
#  Every grain is hard ,\
# '''
# print(a2)  #  No branches
# a3 = ''' Hoe standing grain gradually pawning a midday ,
#  Sweat dripping under the grass ,
#  Who knows what's on the plate ,
#  Every grain is hard ,
# '''
# print(a3)  #  branch
# intro = ' Hello '
# name = 'Shinkai'
# #  The same string type can be added
# print(intro + name)  #  Hello Shinkai
# #  The following expression is used in python Not often
# print(intro + name + "!!!!!")  #  Hello Shinkai!!!!!
# #  It is usually written like this
# print(intro+name, "!!!!!")  #  Hello Shinkai !!!!!
# str = 'hello %s' % ' The Monkey King ' # %s  yes  string Abbreviation
# print(str)  # hello  The Monkey King
# str1 = 'hello %s  Hello  %s' % ('monkey', ' The Monkey King ')
# print(str1)  # hello monkey  Hello   The Monkey King
# str2 = 'hello %3s' % 'ab'  #  Minimum string length 3
# print(str2)  # hello  ab
# str3 = 'hello %3.5s' % 'abcdef'  #  The string length is 3-5
# print(str3)  # hello abcde
# res = 'res'
# print('res = %s' % res)  # res = res
# #  A better way to write
# intro = 'hello'
# name = 'Shinkai'
# res = f'{intro} {name}'
# print(res)  # hello Shinkai
# assignment
# name = 'Shinkai' * 2
# print('hello ' + name)  # hello ShinkaiShinkai
# print('hello', name)
# print('hello %s ' % name)
# print(f'hello {name} ')
# print(1 + True)  # 2
# print(1 + False)  # 1
# print(1 * False)  # 0

# str = '123'
# num = 123
# print(str)  # 123
# print(num)  # 123
# print(type(num))  # <class 'str'>
# print(type(str))  # <class 'int'>

# #  Type checking
# print(type('123'))  # <class 'str'>
# print(type(123))  # <class 'int'>
# print(type(123.123))  # <class 'float'>
# print(type(True))  # <class 'bool'>
# print(type(None))  # <class 'NoneType'>

# #  Object structure
# name = 'Shinkai'
# print(id(name))  # 4313468016, 4443786352
# print(type(name))  # <class 'str'>
# print(name)  # Shinkai

# test = {"key": "value"}
# test2 = test
# test3 = {"key": "value"}
# print(test == test2)  # True
# print(test == test3)  # True

# #  Type conversion
# a = True
# a = int(a)
# print(a)

# a = 2**2
# print(a)

# obj1 = {'a': 123}
# obj2 = {'a': 123}
# print(obj1 is obj2)
# a = 0
# a = not a
# print(a)
# a = 0
# False and print(a)  #  No printing
# True and print(a)  #  Print
# False or print(a)  #  Print
# True or print(a)  #  No printing
# print('1') if True else print('2')
# if 1 == 1:
#     print('1')
#     print('1')
# a = 2
# if a == 1:
#     print('1')
#     print('2')
# print('3')
# a = input(' Please enter 1-100 A number ')
# if a == '123':
#     print(' Correct answer ')
# else:
#     print(' Wrong answer ,  Your answer is ', a)
# age = int(input(' Please enter your age :'))
# if age > 18:
#     print(' You are an adult ')
# elif age > 10:
#     print(' You went to primary school ')
# elif age <= 3:
#     print(' You are still a child ')
# else:
#     print(' Strange age ')

# #  Even and odd numbers
# num = int(input(' Enter any number '))
# print(' even numbers ' if num % 2 == 0 else ' Odd number ')
# #  Leap year judgment
# year = int(input(' Enter any year '))
# print(' Leap year ' if ((year % 100 != 0 and year % 4 == 0) or (year % 100 == 0))else ' Non leap year ')

# dog_age = int(input(' Please enter your dog's age '))
# if dog_age <= 0:
#     print(' Who are you kidding ')
# elif dog_age <= 2:
#     person_age = dog_age * 10.5
#     print(f' A dog is as old as a man {person_age}')
# else:
#     person_age = (dog_age - 2) * 4 + 21
#     print(f' A dog is as old as a man {person_age}')
# score = int(input(' Please enter your score '))
# if score == 100:
#     print('niubi666')
# elif 80 <= score <= 99:
#     print(' ok ')
# elif 60 <= score <= 79:
#     print(' The butt blossoms ')
# else:
#     print('no  Reward ')
# print(bool(0))
# print(bool('0'))
# question1 = bool(input('1 be for the purpose of , If it is not filled in, it means No ,  A house ?'))
# question2 = bool(input('1 be for the purpose of , If it is not filled in, it means No ,  A car ?'))
# question3 = bool(input('1 be for the purpose of , If it is not filled in, it means No ,  Handsome ?'))
# if question1 or question2 or question3:
#     if question1 and question2 and question3:
#         print(' Married married ')
#     else:
#         print(' You can live a little ')
# else:
#     print(' You are here to make fun of me ')

Shortcut record

command + / notes

shift+ enter The cursor jumps to the beginning of the next line

option+command + L formatting code

shift+command+ Up and down All contents of the current line can be moved up and down

and JavaScript The difference between

  • Indents represent blocks of code at different levels
  • Different types cannot be calculated
  • have access to \ Distinguish between different lines , For multi line content ''' '''triple quotation mark
    • js Use back quotes backquote
  • python Strings can * Numbers ( Grammatical sugar )
  • python Of boolean yes True, False lowercase It's wrong.
    • js Of boolean yes ture, false uppercase It's wrong.
  • python The variable of has no type , The type of the variable is the type of the value assigned

Many differences ....js Give up everything you can

js Not at all ' Static resource area ' Or static resources are stored in the stack . See, no one asked

  • python It's a strong type of , Once the type is created , Do not modify
    • js Weak type , And there are implicit conversions ~. Out of line

js Can't print Memory address , The trouble can only be judged by double and third class

js On the bottom api Many have not been thrown out

  • python There is no third class

    • Don't compare addresses ~ After all, you can see the memory address ~

    • js The object content is the same , But the memory addresses are different. The comparison will show false

      • js in == Two objects actually compare memory addresses ~so It can't be the same unless it points to the same

      • python use is and is not To compare The memory address is id similar js===

      • It can be used to compare whether it is the same object

  • python Do not distinguish between reference data types and basic data types , The distinction is between variable and immutable data types

  • python Illegal string to numeric value , Will report a mistake js There is no error report NaN type ~

  • python One more integral division operation // And multiply by the string ~

    • js Also have ** Power operation
  • python and js Short circuit operation is also available

    • But the logical operators look different not->! or->|| and-> &&
  • python It can be compared in a chain 1<score<100

    • js no way , The result of the operation is wrong
  • js Of '0' Turn Boolean yes false js Implicit conversions tend to be numeric '0' by 0 0 yes false

  • python Of '0' Turn Boolean yes true.


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