Python Basics (values, variables, operators)

Posted by ben2005 on Mon, 14 Feb 2022 15:08:49 +0100

Python Basics (values, variables, operators)

pycharm operation

Run: ctrl + f10

Run the current file: ctrl +shift + f10

1, Output functions in Python

print() function

  • You can output numbers
  • Can be a string
  • The output can be an expression containing an operator

The print() function can output the content to the destination

  • monitor

  • file

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

If the file does not exist, it will be created. If it exists, it will be appended after the file content

The output form of the print() function

  • Line feed

    • Execute the above again and it will be displayed in text Txt file and enter hello world again
  • nowrap

    • #Output without line feed,
      print('hello','world','python')
      

2, Escape character and original character

  • What is an escape character?
    • Is the backslash + the first letter that you want to escape
  • Why do I need escape characters?
    • When a string contains special-purpose characters such as backslash, single quotation mark and double quotation mark, these characters must be escaped (converted into a meaning) with backslash
      • Backslash\
      • Single quote '
      • Double quotation mark“
    • Escape characters can also be used when the string contains special characters that cannot be directly represented, such as line feed, carriage return, horizontal tab or backspace
      • Wrap line \ n
      • Enter \ r
      • Horizontal tab \ t
      • Backspace \ b
print('hello \n world')

Output:

hello
world

There are line breaks

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

hello
world
hello world
helloooo world

One \ t is three spaces, and the second \ t is four spaces, because the o of hello has occupied a position, one tab stop is the size of four spaces, and the second helloooo is just 8 characters, not tab stops

print('hello\rworld')

Output result:

world

Because after outputting Hello, press enter, then you will return to the beginning and kill the hello

print('hello\bworld')

Output:

hellworld

o no, because the backspace \ b is 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. If you don't want the escape character in the string to work, use the original character, that is, add R or r before the string

print(r'hello\nworld')

Output:

hello\nworld

Note: the last character is not a backslash

For example:

print(r'hello\nworld\')

Will report an error

However, it can be two

print(r'hello\nworld\\')

Output:

hello\nworld\\

3, Binary and character encoding

utf-8 is recommended

4, Identifiers and reserved words in Python

Rules:

  • Letters, numbers, underscores
  • Cannot start with a number
  • Cannot be a reserved word
  • Strictly case sensitive

View reserved words:

import keyword
print(keyword.kwlist)

Output result:

['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, Definition and use of variables

  • A variable is a labeled box in memory

    name = 'awesome'
    print(name)
    print('identification',id(name))
    print('type',type(name))
    print('value',name)
    

    Output:

    awesome
     Identification 2122703801680    #Memory address
     type <class 'str'>    #type
     It's worth Ollie
    
  • Multiple assignments of variables

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

    Output:

    chu
    

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

6, Common data types in Python

  • Common data types
    • Integer type int 98
    • Floating point type float 3.14159
    • Boolean type bool True False (start with uppercase)
    • String type str 'life is short, I use Python'

Integer type

  • Can represent positive numbers, negative numbers, 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 in binary, decimal, octal and hexadecimal

    • print('decimal system',118)
      print('Binary',0b10110101)  #Starting with binary 0b
      print('octal number system',0o176)      #Octal 0o    
      print('hexadecimal',0xEFA)     #Starting with hex 0x
      

    Output:

Decimal 118
Binary 181
Octal 126
Hex 3834

Floating point type

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

Output:

3.14159 <class 'float'>

  • Floating point storage imprecise

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

    Output:

    3.3000000000000003

    This is caused by the binary storage of the computer, but it is not necessarily wrong

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

    Output:

    3.2
    3.3

  • terms of settlement

    • 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)  #The result of 1 + 1 is 2, and True means 1
print(f2 + 1)  #The result of 0 + 1 is 1, and False indicates 0

Output:

2
1

String type

  • Strings are also called immutable character sequences
  • You can use single quotation marks' ', double quotation marks'', three quotation marks' ', or' '' '
  • The string defined by single quotation marks and double quotation marks must be on one line
  • The string defined by three quotation marks can be distributed on multiple consecutive lines
str1 = 'Life is short, I use it python'
str2 = "Life is short, I use it python"
str3 = '''Life is short,
I use python'''
str4 = """Life is short,
I use python"""

print(str1,type(str1))
print(str2,type(str2))
print(str3,type(str3))
print(str4,type(str4))

Output result:

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

Only three quotation marks can be used for multiple lines, and the output result is also multiple lines

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')   #When str type and int type are connected, an error is reported and type conversion is required
print('My name is'+name+ 'this year'+str(age)+'year') #str() function performs type conversion and converts it to str type

<class 'str'> <class 'int'>
My name is Zhang San. I'm 20 years old

  • Convert other types to str types

    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))) #Convert str to int type and string to numeric string
print(int(f1),type(int(f1))) #Converting float to int type will intercept the integer part and round off the decimal part
# print(int(s2),type(int(s2))) #An error is reported when str is converted to int because the string is a decimal string
print(int(ff),type(int(ff))) #Convert Boolean value to int,True to 1, and False to 0
# print(int(s3),type(int(s3))) #If str is converted to int, an error is reported. The string must be a number and 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)))  #Converted to float type, True corresponds to 1.0
print(float(fb),type(float(fb)))  #Converted to float type, False corresponds to 0.0
# print(float(s3),type(float(s3)))  #Error, not a numeric string
print(float(i),type(float(i)))   #Converted to float type and added 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 can be conditionally converted to each other, and the function int() str() float()

Comments in python

A single line # begins with a comment and ends with a newline

Multi line comment code between a pair of three quotation marks (three single quotation marks and three double quotation marks are OK)

Chinese code declaration comments: add Chinese declaration comments at the beginning of the file to specify the coding format of the source file

How to operate: create a new python file, the first line at the beginning of the file, without spaces, plus

#coding:gbk

It can also be utf-8

Then you will know that this is a comment file. Open it with notepad and find that the format is ANSI when saving

6, Input function input() in python

Function: receive input from the user

Return value type: the type of the input value is str

Value storage: use = to 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 input type changes to str and then becomes a concatenated string

  • Type conversion

    • If integer type and floating-point type are required, str type needs to be converted through int() function or float() function

      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 not only output, but also obtain the output result conversion and operation

7, Operator

Common operators: arithmetic operator (standard arithmetic operator, remainder operator, power operator), assignment operator, comparison operator, Boolean operator, bit operator

Arithmetic operator

  • Addition operation

    • print(1 + 1) # Addition operation
      

      Output:

      2

  • Subtraction operation

    • print(2 - 1) # Subtraction operation
      

      Output:

      1

  • Multiplication

    • print(2*4)   # Multiplication
      

      Output:

      8

  • Division operation

    • print(2/4)   # Division operation
      

      output

      0.5

  • Division operation

    • print(11//2) # quotient, integer division
      

      Output:

      5

  • Remainder operation

    • print(11%2)   #Remainder operation
      

      Output:

      1

  • exponentiation

    • print(2**3) #exponentiation 
      

      Output:

      8, that is, find the third power of 2

  • Special case of division

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

      Output:

      -3
      -3
      -5
      5

      Reason: one positive and one negative, rounded down

  • Special case of remainder

    • print(9%-4)   #Formula: remainder = divisor divisor * quotient 9 - (- 4) * (- 3) = - 3
      print(17%-4)
      

      Output:

      -3
      -3

      The quotient here should be the quotient of division

Assignment Operators

=

Execution order: right to 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

The essence of chain assignment is that 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

Note: 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 exchange:',a,b)
#exchange
a,b=b,a
print('After exchange:',a,b)

Output:

Before exchange: 10 20
 After exchange: 20 10

Note: the function does not need the transfer of the third variable to realize the exchange of values, which can be compared with other languages

Comparison operator

  • Compare the results of variables or expressions in size, true and false

  • type

  • >,<,>=,<=,!=
    ==  #Comparison of object value
    is, is not   #Comparison of object IDS
    
print('---------Comparison operator----------')
a,b=10,20
print('a>b Are you?',a>b)
print('a<b Are you?',a<b)
print('a>=b Are you?',a>=b)
print('a<=b Are you?',a<=b)
print('a==b Are you?',a==b)
print('a!=b Are you?',a!=b)

Output:

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

be careful:

A = is called the assignment operator and a = = is called the comparison operator

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

==The value is compared, and the comparison ID is, is not

exceptional 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

Proof: when it is a number, in fact, a and B point to the id of the same space

The list type does 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

List waiting study

Bitwise Operators

Bit and&  The corresponding digits are all 1, and the result digit is 1, otherwise it is 0
 Bit or | The corresponding digits are all 0, and the result digit is 0, otherwise it is 1
 Left shift operator<<  Discard the overflow at high level and make up 0 at low level
 Shift right operator>>  Low overflow discard, high make up 0

Operator priority

First: **

Second: *,/,//,%  

Third:+,-

The above are arithmetic operators, with priority first

Fourth: <<  >>

Fifth:&

sixth: |

Bitwise operator priority second echelon

Seventh: >,<,>=,<=,==,!=

Comparison operator third echelon

Eighth: and

Article 9: or

Fourth echelon: Boolean operator

last:=  Assignment Operators 

Topics: Python Pycharm