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

Python Basics (values, variables, operators)

編輯:Python

Python Basics ( value , Variable , Operator )

pycharm operation

function :ctrl + f10

Run the current file :ctrl +shift + f10

One 、Python Output function in

print() function

  • It can output numbers
  • Can be a string
  • The output can be an expression with an operator

print() The function can output the content to

  • Monitor

  • file

    # Output to a file , Be careful :1, The specified drive letter exists , Use file=fp
    fp = open('D:/text.txt','a+')
    print('hello world',file=fp)
    fp.close()
    

Create files if they don't exist , If it exists, it will be appended after the contents of the file

print() The output form of the function

  • Line break

    • Execute the above again , Will be in text.txt Enter a new line in the file hello world
  • Don't wrap

    • # No line feed output ,
      print('hello','world','python')
      

Two , Escape character and original character

  • What is an escape character ?
    • It's a backslash + You want to implement the escape function
  • Why do you need escape characters ?
    • When the string contains a backslash , When there are special-purpose characters such as single quotation marks and double quotation marks , These characters must be escaped with a backslash ( Convert a meaning )
      • The backslash \
      • Single quotation marks ’
      • Double quotes "
    • When a string contains a newline , enter , Special characters that cannot be directly represented, such as horizontal tabs or backspace, are , You can also use escape characters
      • Line break \n
      • enter \r
      • Horizontal tabs \t
      • Backspace \b
print('hello \n world')

Output :

hello
world

Line feed

print('hello\nworld')
print('hello\tworld')
print('helloooo\tworld')

hello
world
hello world
helloooo world

One \t There are three spaces , the second \t There are four spaces , because hello Of o Has occupied a position , A tab stop is the size of four spaces , the second helloooo just 8 Characters , No tab stops

print('hello\rworld')

Output results :

world

Because output hello after \r enter , It goes back to the beginning , And then put hello To kill

print('hello\bworld')

Output :

hellworld

o be without , Because of backspace \b It's gone

print('http:\\\\www.baidu.com')

Output URL :

http:\\www.baidu.com

Output quoted content :

print(' The teacher said :\' Hello everyone \'')

Output :

 The teacher said :' Hello everyone '

Original character , You don't want escape characters in strings to work , Use the original character , Is to add... Before the string r, or R

print(r'hello\nworld')

Output :

hello\nworld

matters needing attention : The last character is not a backslash

Such as :

print(r'hello\nworld\')

Will report a mistake

however , It could be two

print(r'hello\nworld\\')

Output :

hello\nworld\\

3、 ... and , Binary and character encoding

Recommended utf-8

Four 、Python Identifiers and reserved words in

The rules :

  • Letter , Numbers , Underline
  • Cannot start with a number
  • It can't be reserved
  • Case sensitive

View reserved words :

import keyword
print(keyword.kwlist)

Output results :

[‘False’, ‘None’, ‘True’, ‘peg_parser’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]

5、 ... and , Definition and use of variables

  • A variable is a labeled box in memory

    name = ' cheer up '
    print(name)
    print(' identification ',id(name))
    print(' type ',type(name))
    print(' value ',name)
    

    Output :

     cheer up
    identification 2122703801680 # Memory address 
    type <class 'str'> # type 
    value cheer up
    
  • Multiple assignment of variables

    nam = 'men'
    nam = 'chu'
    print(nam)
    

    Output :

    chu
    

    nam The direction of this variable will change from the original to the new space

6、 ... and ,Python Common data types in

  • Common data types
    • Integer types int 98
    • Floating point type float 3.14159
    • Boolean type bool True False ( Start with a capital )
    • String type str ‘ Life is too short , I use Python’

Integer types

  • Can represent a positive number , negative , And zero

    • n1 = 90
      n2 = -12
      n3 = 0
      print(n1,type(n1))
      print(n2,type(n2))
      print(n3,type(n3))
      

      Output :

      90 <class ‘int’>
      -12 <class ‘int’>
      0 <class ‘int’>

  • Integers can be expressed as binary , Decimal system , octal , Hexadecimal

    • print(' Decimal system ',118)
      print(' Binary system ',0b10110101) # Binary system 0b start 
      print(' octal ',0o176) # octal 0o start 
      print(' Hexadecimal ',0xEFA) # Hexadecimal 0x start 
      

    Output :

Decimal system 118
Binary system 181
octal 126
Hexadecimal 3834

Floating point type

  • Integral part and decimal part make up
n4 = 3.14159
print(n4,type(n4))

Output :

3.14159 <class ‘float’>

  • Floating point number storage is inaccurate

    n5 = 1.1
    n6 = 2.2
    print(n5 + n6)
    

    Output :

    3.3000000000000003

    This is caused by the binary storage of the computer , But it doesn't have to be a mistake

    n5 = 1.1
    n6 = 2.1
    print(n5 + n6)
    n7 = 1.2
    print(n6 + n7)
    

    Output :

    3.2
    3.3

  • terms of settlement

    • The import module decimal

    • from decimal import Decimal
      print(Decimal('1.1') + Decimal('2.2'))
      

      Output :

      3.3

      Must have quotation marks :

      from decimal import Decimal
      print(Decimal(1.1) + Decimal(2.2))
      

      Output :

      ​ 3.300000000000000266453525910

Boolean type

Used to indicate true or false values

True,False

Boolean values can be converted to integers

  • True 1
  • False 0
f1 = True
f2 = False
print(f1,type(f1))
print(f2,type(f2))

Output

True <class ‘bool’>
False <class ‘bool’>

transformation :

f1 = True
f2 = False
print(f1 + 1) #1+1 As the result of the 2,True Express 1
print(f2 + 1) #0+1 As the result of the 1,False Express 0

Output :

2
1

String type

  • Strings are also called immutable character sequences
  • You can use single quotes ’’, Double quotes "", Three quotes ’’’ ‘’' or “”" “”" To define
  • The string defined by single quotation marks and double quotation marks must be on one line
  • A string defined by three quotation marks can be distributed on multiple consecutive lines
str1 = ' Life is too short , I use python'
str2 = " Life is too short , I use python"
str3 = ''' Life is too short , I use python'''
str4 = """ Life is too short , I use python"""
print(str1,type(str1))
print(str2,type(str2))
print(str3,type(str3))
print(str4,type(str4))

Output results :

 Life is too short , I use python <class 'str'>
Life is too short , I use python <class 'str'>
Life is too short ,
I use python <class 'str'>
Life is too short ,
I use python <class 'str'>

Only those with three quotation marks can have multiple lines , And the output result is multi line

Type conversion str() Function and int() function

  • str() function
name = ' Zhang San '
age = 20
print(type(name),type(age))
# print(' My name is '+name+ ' This year, '+age+' year ') #str The type and int Type , Report errors , To type conversion 
print(' My name is '+name+ ' This year, '+str(age)+' year ') #str() Function performs type conversion , Turn into str type 

<class ‘str’> <class ‘int’>
My name is Zhang San. This year 20 year

  • Other types are converted to str type

    a = 10
    b = 198.8
    c = False
    print(str(a),str(b),str(c))
    

    Output :

    10 198.8 False

    Type after conversion

print(str(a),str(b),str(c),type(str(a)), type(str(b)), type(str(c)))

Output :

10 198.8 False <class ‘str’> <class ‘str’> <class ‘str’>

It can be seen that the type has changed

  • int() function
s1 = '128'
f1 = 98.7
s2 = '78.77'
ff = True
s3 = 'hello'
print(int(s1),type(int(s1))) # take str Turn into int type , String to numeric string 
print(int(f1),type(int(f1))) # take float Turn into int type , Will intercept the integer part , Omit the decimal part 
# print(int(s2),type(int(s2))) # take str To int Report errors , Because the string is a decimal string 
print(int(ff),type(int(ff))) # Converts a Boolean value to int,True Turn into 1,False Corresponding to 0
# print(int(s3),type(int(s3))) # take str To int Report errors , The string must be a number , And is an integer 

Output :

128 <class ‘int’>
98 <class ‘int’>
1 <class ‘int’>

Type conversion _float() function

s1 = '128.98'
s2 = '76'
ff = True
fb = False
s3 = 'hello'
i = 98
print(float(s1),type(float(s1)))
print(float(s2),type(float(s2)))
print(float(ff),type(float(ff))) # Into the float type ,True Corresponding 1.0
print(float(fb),type(float(fb))) # Into the float type ,False Corresponding 0.0
# print(float(s3),type(float(s3))) # Report errors , Not a numeric string 
print(float(i),type(float(i))) # Into the float type , And add a decimal part 

Output :

128.98 <class 'float'>
76.0 <class 'float'>
1.0 <class 'float'>
0.0 <class 'float'>
98.0 <class 'float'>

int float str They can be conditionally converted to each other , function int() str() float()

python The comments in

Single-line comments # start , Until the end of the line feed

Multiline comment Code between a pair of three quotation marks ( Three single quotes and three double quotes are OK )

Comments on Chinese coding statement : Add a Chinese statement note at the beginning of the document , Used to specify the encoding format of the source file

​ How to operate : Create a new python file , The first line at the beginning of the file , No space , add

#coding:gbk

It can also be utf-8

Then you will know that this is an annotation file , Open in Notepad , When saving as, the format is ANSI

6、 ... and ,python The input function in the input()

effect : Receive input from the user

return type : The type of input value is str

Value storage : Use = Store the entered value

a = input(' Please enter an addend :')
b = input(' Please enter another addend :')
print(a + b)

Output :

 Please enter an addend :10
Please enter another addend :20
1020

Prove that the type of input changes str 了 , Then it becomes a concatenated string

  • Type conversion

    • If you need integer and floating point types , You need to str Type through int() Function or float() Function for type conversion

      Example :

      a = int(input(' Please enter an addend :'))
      b = int(input(' Please enter another addend :'))
      print(a + b)
      

      Output :

       Please enter an addend :10
      Please enter another addend :20
      30
      

      In this way, you can output , Get the output result conversion again, and then operate

7、 ... and , Operator

Common operators : Arithmetic operator ( Standard arithmetic operators , The remainder operator , Power operator ), Assignment operator , Comparison operator , Boolean operator , An operator

Arithmetic operator

  • Addition operation

    • print(1 + 1) # Addition operation
      

      Output :

      2

  • Subtraction

    • print(2 - 1) # Subtraction 
      

      Output :

      1

  • Multiplication

    • print(2*4) # Multiplication 
      

      Output :

      8

  • Division operations

    • print(2/4) # Division operations 
      

      Output

      0.5

  • Division operation

    • print(11//2) # Take business , Division operation 
      

      Output :

      5

  • Take over operations

    • print(11%2) # Take over operations 
      

      Output :

      1

  • Power operation

    • print(2**3) # Power operation 
      

      Output :

      8 namely : seek 2 Of 3 The next power

  • The special case of division

    • print(-9//4)
      print(9//-4)
      print(17//-4)
      print(11//2)
      

      Output :

      -3
      -3
      -5
      5

      reason : One is one minus one. , Rounding down

  • Special case of remainder

    • print(9%-4) # The formula : remainder = Divisor - Divisor * merchant 9-(-4)*(-3) = -3
      print(17%-4)
      

      Output :

      -3
      -3

      The quotient here should be the quotient of division

Assignment operator

=

Execution order : Right To the left

Support chain assignment : a=b=c=20

Support parameter assignment : += -= *= /= //= %=

Support series unpacking assignment :a,b,c=20,30,40

a=b=c=20
print(a)
print(b)
print(c)

Output :

20
20
20

Chain assignment essence , Multiple variables point to a space at the same time

a = 2
b = 3
a **= b
print(a)

Output :8

a,b,c = 20,30,40
print(a)
print(b)
print(c)
d,e,f=6,'egg',3.14159
print(d)
print(e)
print(f)

Output :

20
30
40
6
egg
3.14159

Be careful : The number of left and right variables should be consistent with the number of values

print("---------- Exchange the values of two variables --------")
a,b=10,20
print(' Before the exchange :',a,b)
# In exchange for 
a,b=b,a
print(' After the exchange :',a,b)

Output :

 Before the exchange : 10 20
After the exchange : 20 10

Be careful : effect , Do not use the third variable to transfer , Realize the exchange of values , Can compare other languages

Comparison operator

  • Size the result of a variable or expression 、 Comparison of true and false

  • type

  • >,<,>=,<=,!=
    == # object value Comparison 
    is, is not # Object's id Comparison 
    
print('--------- Comparison operator ----------')
a,b=10,20
print('a>b Do you ?',a>b)
print('a<b Do you ?',a<b)
print('a>=b Do you ?',a>=b)
print('a<=b Do you ?',a<=b)
print('a==b Do you ?',a==b)
print('a!=b Do you ?',a!=b)

Output :

--------- Comparison operator ----------
a>b Do you ? False
a<b Do you ? True
a>=b Do you ? False
a<=b Do you ? True
a==b Do you ? False
a!=b Do you ? True

Be careful :

One = It's called the assignment operator , == It's called a comparison operator

A variable consists of three parts , identification , type , value

== Compare values , For comparison marks is, is not

A special case :

a = 10
b = 10
print(a==b)
print(a is b )
print(a is not b)
list1=[11,22,33,44]
list2=[11,22,33,44]
print(list1==list2)
print(list1 is list2)
print(list1 is not list2)

Output :

True
True
False
True
False
True

prove : When it's a number , actually a,b All point to the same space id

and list Type will not

Boolean operator

  • For operations between Boolean values
and or not in not in
a,b=1,2
print(a==1 and b==2) #True True and True --->True
print(a==1 and b<2) #False True and False --->False
print(a!=1 and b == 2) #False False and True ---> False
print(a!=1 and b!=2) #False False and False --->False

Output :

True
False
False
False

a,b=1,2
print(a==1 or b==2) #True True or True --->True
print(a==1 or b<2) #True True or False --->True
print(a!=1 or b == 2) #True False or True ---> True
print(a!=1 or b!=2) #False False or False --->False

Output :

True
True
True
False

print('-----not Yes bool Type operand inversion ----')
f = True
ff = False
print(not f)
print(not ff)

Output :

-----not Yes bool Type operand inversion ----
False
True
print('-----in And not in --------')
s = 'helloworld'
print('w' in s)
print('k' in s)
print('w' not in s)
print('k' not in s)

Output :

-----in And not in --------
True
False
False
True

The list is waiting to be studied

An operator

 Bit and & The corresponding digits are 1, As a result, the number is 1, Otherwise 0
Bit or | The corresponding digits are 0, As a result, the number is 0, Otherwise 1
Left shift operator << High overflow discard , Low complement 0
Shift right operator >> Low overflow discard , High compensation 0

Operator priority

 First of all : **
second : *,/,//,%
Third :+,-
These are arithmetic operators , Priority first
Fourth : << >>
The fifth :&
The sixth : |
Bit operator priority second echelon
The seventh : >,<,>=,<=,==,!=
The third echelon of comparison operators
The eighth :and
The ninth :or
Fourth echelon : Boolean operator
Last := Assignment operator

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