Datawhale~Python~Day01~Variables, Operators and Data Types

Variables, Operators and Data Types

If you accidentally report an error group, please review the python basics again! The comment box is my addition to the original note

1. Notes

  • In Python, # denotes a comment, which acts on the entire line.

[Example] Single-line comment

# this is a note
  • ''' ''' or """ """ means interval comment, everything between triple quotes is commented

[Example] Multi-line comment

'''
This is a multi-line comment, enclosed in three single quotes
 This is a multi-line comment, enclosed in three single quotes
 This is a multi-line comment, enclosed in three single quotes
'''
"""
This is a multi-line comment, enclosed in three double quotes
 This is a multi-line comment, enclosed in three double quotes 
This is a multi-line comment, enclosed in three double quotes
"""

2. Operators

arithmetic operators

The operators in python are basically the same as those in other languages.
The division to pay attention to: '//' means rounding; '/' means general division, decimal.
Exponentiation: '**'

operator name Example
+ add 1 + 1
- reduce 2 - 1
* take 3 * 4
/ remove 3 / 4
// Divisible (floor division) 3 // 4
% remainder 3 % 4
** power 2 ** 3

[example]

print(1 + 1)  # 2
print(2 - 1)  # 1
print(3 * 4)  # 12
print(3 / 4)  # 0.75
print(3 // 4)  # 0
print(3 % 4)  # 3
print(2 ** 3)  # 8

comparison operator

operator name Example
> more than the 2 > 1
>= greater or equal to 2 >= 4
< less than 1 < 2
<= less than or equal to 5 <= 2
== equal 3 == 4
!= not equal to 3 != 5

[example]

print(2 > 1)  # True
print(2 >= 4)  # False
print(1 < 2)  # True
print(5 <= 2)  # False
print(3 == 4)  # False
print(3 != 5)  # True

Logical Operators

Note the Yes priority order here, not > and > or

operator name Example
and and (3 > 2) and (3 < 5)
or or (1 > 3) or (9 < 2)
not No not (2 > 1)

[example]

print((3 > 2) and (3 < 5))  # True
print((1 > 3) or (9 < 2))  # False
print(not (2 > 1))  # False

bitwise operators

operator name Example
~ bitwise negation ~4
& bitwise AND 4 & 5
\| bitwise OR 4 \| 5
^ Bitwise XOR 4 ^ 5
<< shift left 4 << 2
>> move right 4 >> 2

[Example] For binary operations, see the explanation in the "Bit Operations" section.

print(bin(4))  # 0b100
print(bin(5))  # 0b101
print(bin(~4), ~4)  # -0b101 -5
print(bin(4 & 5), 4 & 5)  # 0b100 4
print(bin(4 | 5), 4 | 5)  # 0b101 5
print(bin(4 ^ 5), 4 ^ 5)  # 0b1 1
print(bin(4 << 2), 4 << 2)  # 0b10000 16
print(bin(4 >> 2), 4 >> 2)  # 0b1 1

Ternary operator

[example]

x, y = 4, 5
if x < y:
    small = x
else:
    small = y

print(small)  # 4

With the conditional expression of the ternary operator, you can use a single statement to complete the above conditional judgment and assignment operations.

[example]

x, y = 4, 5
small = x if x < y else y
print(small)  # 4

other operators

operator name Example
in exist 'A' in ['A', 'B', 'C']
not in does not exist 'h' not in ['A', 'B', 'C']
is yes "hello" is "hello"
is not no "hello" is not "hello"

[example]

letters = ['A', 'B', 'C']
if 'A' in letters:
    print('A' + ' exists')
if 'h' not in letters:
    print('h' + ' not exists')

# A exists
# h not exists

[Example] Both variables being compared point to immutable types.

a = "hello"
b = "hello"
print(a is b, a == b)  # True True
print(a is not b, a != b)  # False False

[Example] Both variables to be compared point to variable types.

a = ["hello"]
b = ["hello"]
print(a is b, a == b)  # False True
print(a is not b, a != b)  # True False

Notice:
-is, is not compares the memory addresses of the two variables

  • ==, != compare the values ​​of two variables
  • The two variables to be compared point to immutable address types (str, etc.), then is, is not and ==, != are completely equivalent.
  • If the two variables to be compared point to types with variable addresses (list, dict, etc.), there is a difference between the two.
  1. Python is an object-oriented language, all data in python are objects, including addresses (id), values ​​(value) and types (type). is compares whether the id() between the two objects is consistent, and == compares whether the values ​​of the two objects are consistent.
  2. One thing to note here is that data types in python include numeric and container types. Numerical types include int integer objects, float double-precision floating-point objects, and bool logical objects, all of which belong to Scalar; container types include list objects. , tuple tuple object, dict dictionary object, set collection object, etc.
  3. In python, both integers and short strings are in python's cache for reuse, when we create multiple references equal to 1 (here equals 1 for example), in fact all the references we create point to this same object 1. That is to say, the storage of variables adopts the way of reference semantics, and the variable is just a reference, which opens up space and stores the id of the same constant.
# integer
a = 1
b = 1
print(id(a),id(b)) # 140731024118624 140731024118624
print(a is b) # True
print(a == b) # True

# short characters
a = "good"
b = "good"
print(a is b) # True

a = [1,2]
b = [1,2]
print(id(a),id(b)) # 3119733528968 3119732387912
print(a is b) # False
print(a == b) # True

a = "very good morning"
b = "very good morning"
print(a is b) # False

The above comments are the corresponding running results. As you can see, since Python caches integers and short strings, there is only one copy of each object. For example, all references to the integer 1 point to the same object. Even with an assignment statement, you just create a new reference, not the object itself. Long strings and other objects can have multiple identical objects, and new objects can be created using assignment statements.
Inspired by garbage collection mechanism

operator precedence

Also need to memorize here, arithmetic operations, shift operations, bit operations, logical operations

  • Unary operators are better than binary operators. For example 3**-2 is equivalent to 3**(-2).
  • Arithmetic operation first, then shift operation, and finally bit operation. For example, 1 < < 3 + 2 & 7 is equivalent to (1 < < (3 + 2)) & 7
  • The logical operations are finally combined. For example, 3 < 4 and 4 < 5 are equivalent to (3 < 4) and (4 < 5)

[example]

print(-3 ** 2)  # -9
print(3 ** -2)  # 0.1111111111111111
print(1 << 3 + 2 & 7)  # 0
print(-3 * 2 + 5 / -2 - 4)  # -12.5
print(3 < 4 and 4 < 5)  # True

3. Variables and assignment

  • Before using a variable, you need to assign a value to it.
  • Variable names can include letters, numbers, and underscores, but variable names cannot start with a number.
  • Python variable names are case-sensitive, foo != Foo.

[example]

teacher = "The program life of the old horse"
print(teacher)  # The program life of the old horse

[example]

first = 2
second = 3
third = first + second
print(third)  # 5

[example]

myTeacher = "The program life of the old horse"
yourTeacher = "Pony's program life"
ourTeacher = myTeacher + ',' + yourTeacher
print(ourTeacher)  # The program life of the old horse, the program life of the pony

4. Data Types and Conversions

type name Example
int Integer <class 'int'> -876, 10
float floating point<class 'float'> 3.149, 11.11
bool boolean<class 'bool'> True, False

integer

[Example] The value of a can be seen through print(), and the class (class) is int.

a = 1031
print(a, type(a))
# 1031 <class 'int'>

Everything in Python is an object, and integers are no exception. As long as it is an object, it has corresponding attributes and methods.

dir(object): Check all objects!

[example]

b = dir(int)
print(b)

# ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__',
# '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__',
# '__float__', '__floor__', '__floordiv__', '__format__', '__ge__',
# '__getattribute__', '__getnewargs__', '__gt__', '__hash__',
# '__index__', '__init__', '__init_subclass__', '__int__', '__invert__',
# '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',
# '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__',
# '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
# '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
# '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
# '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
# '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__',
# 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag',
# 'numerator', 'real', 'to_bytes']

It is enough to have a general impression of them, how to use them, what parameters are required, and you need to check the documentation. See an example of bit_length().

[Example] Find the binary representation of an integer and return its length.

a = 1031
print(bin(a))  # 0b10000000111
print(a.bit_length())  # 11

float

[example]

print(1, type(1))
# 1 <class 'int'>

print(1., type(1.))
# 1.0 <class 'float'>

a = 0.00000023
b = 2.3e-7
print(a)  # 2.3e-07
print(b)  # 2.3e-07

Sometimes we want to keep n digits after the decimal point of a floating point type. This can be done using the Decimal object from the decimal package and the getcontext() method.

import decimal
from decimal import Decimal

There are many widely used packages in Python, you can import whatever you use. Packages are also objects, and their properties and methods can also be viewed with the dir(decimal) mentioned above.

[Example] getcontext() shows that the default precision value of Decimal objects is 28 digits (prec=28).

a = decimal.getcontext()
print(a)

# Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
# capitals=1, clamp=0, flags=[], 
# traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)
print(b)

# 0.3333333333333333333333333333

[Example] Make 1/3 reserve 4 bits, and use getcontext().prec to adjust the precision.

decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print(c)

# 0.3333

Boolean type

A boolean variable can only take two values, True and False. When using Boolean variables in numeric operations, use 1 and 0 to represent True and False.

[example]

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

In addition to directly assigning True and False to variables, you can also use bool(X) to create variables, where X can be

  • Basic Types: Integer, Float, Boolean
  • Container types: strings, tuples, lists, dictionaries, and sets

[Example] bool acts on basic type variables: as long as X is not integer 0 or floating point 0.0, bool(X) is True, and the rest are False.

print(type(0), bool(0), bool(1))
# <class 'int'> False True

print(type(10.31), bool(0.00), bool(10.31))
# <class 'float'> False True

print(type(True), bool(False), bool(True))
# <class 'bool'> False True

[Example] bool acts on container type variables: as long as X is not an empty variable, bool(X) is True, and the rest are False.

print(type(''), bool(''), bool('python'))
# <class 'str'> False True

print(type(()), bool(()), bool((10,)))
# <class 'tuple'> False True

print(type([]), bool([]), bool([1, 2]))
# <class 'list'> False True

print(type({}), bool({}), bool({'a': 1, 'b': 2}))
# <class 'dict'> False True

print(type(set()), bool(set()), bool({1, 2}))
# <class 'set'> False True

To determine whether the value of bool(X) is True or False, it depends on whether X is empty. If it is empty, it is False, and if it is not empty, it is True.

  • For numeric variables, both 0 and 0.0 are considered empty.
  • For container variables, it is empty if there are no elements in it.

get type info

  • type(object) Get type information

[example]

print(type(1))  # <class 'int'>
print(type(5.2))  # <class 'float'>
print(type(True))  # <class 'bool'>
print(type('5.2'))  # <class 'str'>
  • isinstance(object, classinfo) Determines whether an object is of a known type.

[example]

print(isinstance(1, int))  # True
print(isinstance(5.2, float))  # True
print(isinstance(True, bool))  # True
print(isinstance('5.2', str))  # True

Note:

  • type() does not consider subclasses to be a superclass type, regardless of inheritance.
  • isinstance() will consider the subclass to be a superclass type, considering the inheritance relationship.

If you want to determine whether two types are the same, it is recommended to use isinstance().

type conversion

  • Convert to integer int(x, base=10)
  • Convert to string str(object='')
  • Convert to float float(x)

[example]

print(int('520'))  # 520
print(int(520.52))  # 520
print(float('520.52'))  # 520.52
print(float(520))  # 520.0
print(str(10 + 10))  # 20
print(str(10.1 + 5.2))  # 15.3

5. print() function

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
  • Format the object as a string representation and output it to the stream file object file. All non-keyword arguments are converted to string output in str() mode;
  • The keyword parameter sep is to implement the separator. For example, when multiple parameters are output, you want to output the separator character in the middle;
  • The keyword parameter end is the character at the end of the output, the default is the newline character \n;
  • The keyword parameter file is the file that defines the stream output, which can be the standard system output sys.stdout, or it can be redefined as another file;
  • The keyword parameter flush is to immediately output the content to the stream file without caching.

[Example] When there is no parameter, the line will be changed after each output.

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
    print(item)

# This is printed without 'end'and 'sep'.
# apple
# mango
# carrot
# banana

[ex amp le] at the end of each output, the parameter set by end is used to end, and there is no default line feed

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
    print(item, end='&')
print('hello world')

# This is printed with 'end='&''.
# apple&mango&carrot&banana&hello world

[ex amp le] seperation is a parameter set by sep between the item value and'Other string' Since the end parameter is not set, the default is a newline after output interpretation, that is, the default value of the end parameter is \n.

shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
    print(item, 'another string', sep='&')

# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string

references:

  • https://www.runoob.com/python3/python3-tutorial.html
  • https://www.bilibili.com/video/av4050443
  • https://mp.weixin.qq.com/s/DZ589xEbOQ2QLtiq8mP1qQ
  • https://www.cnblogs.com/OliverQin/p/7781019.html

Exercise questions:

  1. How to annotate code in python?
  2. What operators does python have and what is the precedence of these operators?
  3. What is the difference between is, is not and ==, != in python?
  4. What data types are included in python? How to convert between these data types?

answer:

  1. Single-line comment#; multi-line comment, three quotation marks (single and double quotation marks are acceptable) """ """
  2. Basic operators, precedence: arithmetic operations, shift operations, bit operations, logical operations
  3. The former compares the id of the object, and the latter compares the value of the object
  4. Numeric and container types, float, int, str,bool; list,tuple,dict…
    The conversion of numeric data can be forced directly by using several variable names, such as int(3.22)

Tags: Python

Posted by scnov on Thu, 30 Jun 2022 22:02:36 +0530