Python based variables

Posted by erick_w on Fri, 14 Jan 2022 20:54:07 +0100

I think it is the "secret" of learning Python well to lay a solid foundation and practice basic skills. Lao Tzu once said: the nine story platform starts from building soil. This article mainly uses some simple small examples to briefly describe the variables related to the basis of Python. It is only for learning and sharing. If there are deficiencies, please correct them.

What are variables?

A variable is an amount whose value can change during program execution. The corresponding is a constant, which refers to the amount whose value cannot change during the execution of the program. Variables and constants are names that are easy to remember and recognize in order to obtain and set the value of the corresponding address in memory.

Common variable types in Python

The commonly used variable types in Python mainly include number, string, list, tuple and dictionary, as shown in the following figure:

Naming rules for variables

In Python, the naming rules of variables are as follows:

  1. Variable names cannot start with numbers
  2. Variable names cannot contain special symbols
  3. Variable names should be meaningful. Avoid naming variables with a,b,c
  4. If you must use more than one word in a variable name, separate it with an underscore
  5. In most cases, variable names should be lowercase
  6. If you use a single letter for naming, avoid using lowercase L or uppercase O

Wrong or unfriendly variable naming

Incorrect or unfriendly variable naming, for example:

>>> 1name='Alan.hsiang'
SyntaxError: invalid syntax
>>> a=1
>>> b=2
>>> b*c=3
SyntaxError: can't assign to operator
>>> b$c=2
SyntaxError: invalid syntax
>>> 

Friendly variable naming

An example of friendly variable naming is as follows:

>>> name='Alan.hsiang'
>>> name_age="Alan.hsiang 's age is 20"
>>> age =20

Number type (number)

In Python 3, the number types supported are as follows:

int integer, including positive integer, negative integer and 0, which can be represented by binary, octal, decimal and hexadecimal.

An example of an int type is as follows:

>>> num1=2   #decimal system
>>> num1
2
>>> num2=0b101  #Binary
>>> num2
5
>>> num8=0o24  #octal number system
>>> num8
20
>>> num16=0x3F  #hexadecimal
>>> num16
63
>>> 

float floating point type, including two parts: integer part and decimal part. Pass integer It can also be expressed by scientific counting.

An example of a float type is as follows:

>>> float_num1=2.345 # Common representation
>>> float_num1
2.345
>>> float_num2 =1.23e9 #Scientific counting method
>>> float_num2
1230000000.0
>>> 

bool boolean type, which represents a logical value. There are only two values: true and false.

Examples of bool types are as follows:

>>> b_var1=True  # Be case sensitive
>>> b_var1
True
>>> b_var2=False  # Be case sensitive
>>> b_var2
False
>>> 

Note: True and False are keywords that are case sensitive and cannot be misspelled. Examples of errors are as follows:
>>> b_var3=true
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    b_var3=true
NameError: name 'true' is not defined
>>> b_var4=false
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    b_var4=false
NameError: name 'false' is not defined
>>> 

Complex complex type, expressed in 3+4j format.

The example of complex is as follows:

>>> c_num=complex(3,4)
>>> c_num
(3+4j)
>>> 

Use of type method

The type method is mainly used to judge the data type of the current variable, as shown below:

>>> type(num1)
<class 'int'>
>>> type(float_num1)
<class 'float'>
>>> type(b_var1)
<class 'bool'>
>>> type(c_num)
<class 'complex'>
>>> 

Python mathematical operators

The general mathematical operators supported by Python are as follows:

General mathematical operators, for example:

>>> a=5
>>> b=2
>>> a+b
7
>>> a*b
10
>>> a**b
25
>>> a/b
2.5
>>> a//b
2
>>> a%b
1
>>> 

Python comparison operator

The comparison operators supported by Python are as follows:

Comparison operator, for example:

>>> a=20
>>> b=10
>>> a==b
False
>>> a!=b
True
>>> a>b
True
>>> a<b
False
>>> a>=b
True
>>> a<=b
False
>>> 

Python assignment operator

Python supports assignment operators as follows:

Assignment operator, for example:

>>> c=a+b
>>> c
30
>>> c+=a
>>> c
50
>>> c-=a
>>> c
30
>>> c*=a
>>> c
600
>>> c/=a
>>> c
30.0
>>> c%=a
>>> c
10.0
>>> c**=a
>>> c
1e+20
>>> c//=a
>>> c
5e+18
>>> 

Python logical operators

The logical operators supported by Python are as follows:

Logical operators, for example:

>>> a and b # If a is True, the value calculated by b is returned
10
>>> a or b # If a is True, the value of a is returned; otherwise, the value of b is returned
20
>>> not a # Returns False if a is True
False
>>> 

Python member operator

The member operator supported by Python is used to test whether members are included in sequences, including strings, lists, tuples, etc., as shown below:

Member operator, for example:

>>> list=[4,5,6,7,8,9,0]
>>> 5 in list
True
>>> 3 in list
False
>>> 3 not in list
True
>>> 5 not in list
False
>>> 

Python identity operator

Identity operator, used to compare the storage units of two objects, as follows:

Identity operator, for example:

>>> a=b
>>> a is b
True
>>> a is not b
False
>>> b=3
>>> a is b
False
>>> a is not b
True
>>> 

String type (string)

String type is one of the most commonly used data types. You can use quotation marks (single or double quotation marks) to create strings. Characters in a string can contain, characters, letters, Chinese characters, special symbols, etc.

Create string

Python creates strings very simply by assigning a value of string type to a variable. Examples are as follows:

>>> str1 = 'apple'
>>> str1
'apple'
>>> str2 = "apple"
>>> str2
'apple'
>>> str3 = "apple'color is red"
>>> str3
"apple'color is red"
>>> str4 = 'apple is very "good"'
>>> str4
'apple is very "good"'
>>> 

Note: Python supports the definition of strings in English single quotation marks and double quotation marks, mainly to avoid the inclusion of quotation marks in the string content.

An example of a string error is as follows:

>>> str5= 'apple'is good'
SyntaxError: EOL while scanning string literal
>>> str6 = 'apple' hahaha'
SyntaxError: invalid syntax
>>> str7 = 'abc'
SyntaxError: invalid character in identifier
>>> 

Multiline string

If the string has more than one line, it needs to be defined with three single quotation marks or double quotation marks. As follows:

>>> str8 = '''hello everyone
 I am Alan.hsiang
 I am a man
 I am lazy'''
>>> print(str8)
hello everyone
 I am Alan.hsiang
 I am a man
 I am lazy
>>> str8
'hello everyone\n I am Alan.hsiang\n I am a man\n I am lazy'
>>> 

Access string

In Python, you can access one or more characters in a string through a sequence number, starting with 0.

>>> str4 = 'apple is very "good"'
>>> str4[0]  # Forward access
'a'
>>> str4[2]
'p'
>>> str4[-1]  # Reverse access
'"'
>>> str4[-2]
'd'
>>> str4[1:2] #Slice access, starting with 1 and ending with 2, excluding 2
'p'
>>> 

Update string

The content of the string is read-only and cannot be updated. If you have to update, you can convert it into a list, modify it, and then convert it into a string. This is a compromise method. As follows:

>>> list1=list(str1)
>>> list1
['a', 'p', 'p', 'l', 'e']
>>> list1[0]='A'
>>> list1
['A', 'p', 'p', 'l', 'e']
>>> str1 = "".join(list1)
>>> str1
'Apple'
>>> 

During conversion, if the following error is reported, it is because the list was declared as a variable before, so the built-in function cannot be accessed. Therefore, please also note that variable names should be standardized and keywords cannot be used.

>>> list2 = list(str1)
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    list2 = list(str1)
TypeError: 'list' object is not callable

List type (list)

What is a list?

List is a very important data structure in Python. It is composed of a series of elements arranged in a specific order. Developers can create a list containing letters and numbers, or add any element to the list. The data types between elements can be different. Each element in the list is assigned an index to represent the position of the element in the list. Index starts at 0. In Python programs, lists are represented in English brackets, and the elements of the list are separated by commas.

How do I create a list?

The creation of the list is also very simple. It is created through the format of variable = [element 1, element 2,..., element n], as shown below:

>>> fruits = ['apple','pear','banana']
>>> print(fruits)
['apple', 'pear', 'banana']
>>> type(fruits)
<class 'list'>
>>> list2 = []
>>> list3 = [1,2,3,'a','b',4,5]
>>> print(list3)
[1, 2, 3, 'a', 'b', 4, 5]
>>> 

How do I access the list?

The list is accessed through the index and can be accessed through the format of list name [index]. As follows:

>>> fruits[1]
'pear'
>>> list3[3]
'a'
>>> 

Note: the index of the list starts at 0.

If the content of the list to be accessed exceeds the range of the list, the following error will be reported:

>>> list3[7]
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    list3[7]
IndexError: list index out of range

Python lists support not only positive indexes but also negative indexes, as shown below:

>>> list3[-1]
5
>>> list3[-2]
4
>>> 

Similarly, the list can be accessed by slicing, as shown below:

>>> list3[1:4] # Start position, end position, including start, excluding end
[2, 3, 'a']
>>> 

Tuple type (tuple)

In Python programs, tuples can be regarded as special lists. Unlike lists, the elements in tuples cannot be changed. Not only can the data items in the tuple be changed, but also data items can not be added and deleted. When you need to create a set of immutable data, you usually put the data in tuples.

How do I create and access tuples?

In Python programs, tuples enclose data in parentheses, and the elements are separated by commas. You can also create empty tuples. The details are as follows:

>>> t1 = ('a','b','c')
>>> t1
('a', 'b', 'c')
>>> type(t1)
<class 'tuple'>
>>> t1[1]
'b'
>>> t1[1]='B' # If you try to modify the element content of a tuple, an error will be reported
Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    t1[1]='B' # If you try to modify the element content of a tuple, an error will be reported
TypeError: 'tuple' object does not support item assignment
>>> 

When there is only one element in a tuple, you need to add a comma after the tuple, as shown below:

>>> t2 = (2) # If there is only one element without a comma, it is not a tuple
>>> type(t2)
<class 'int'>
>>> t3= (2,) # If there is only one element, add a comma to represent a tuple
>>> type(t3)
<class 'tuple'>
>>> 

Tuples, like lists, support index and slice access, as shown below:

>>> t1[1]
'b'
>>> t1[1:3]
('b', 'c')
>>> 

Use built-in methods to manipulate tuples

Common built-in methods for tuples are as follows:

  1. len() gets the length of tuples, that is, the number of elements.
  2. max() gets the maximum value of the element in the tuple.
  3. min() gets the minimum value of the element in the tuple.

Tuples use built-in functions, as shown below:

>>> t1 = ('a','b','c')
>>> t1
('a', 'b', 'c')
>>> len(t1)
3
>>> max(t1)
'c'
>>> min(t1)
'a'
>>> 

Dictionary type (Dictionary)

What is a dictionary?

A dictionary is a data set surrounded by braces {} and declared and existing in the form of "key: value" pairs. The biggest difference between a dictionary and a list is that the dictionary is disordered and its member position is only symbolic. In a dictionary, members are accessed through keys, but not through their position.

Create and access Dictionaries

Any Key value pair can be stored in the dictionary. The Key in each Key value pair must be unique and immutable, but the value does not. The Key value can take any data type. The format is as follows: dict1={key1:value1,key2:value2}

An example of creating and operating a dictionary is as follows:

>>> dict1={'a':1,'b':2}
>>> dict2={} # Empty dictionary
>>> type(dict1)
<class 'dict'>
>>> dict2['apple']='big' # Add element
>>> dict2['orange']='small' # Add element
>>> dict2
{'apple': 'big', 'orange': 'small'}
>>> dict1['a'] =-1 # Modify the value of the element
>>> dict1
{'a': -1, 'b': 2}
>>> del dict1['a'] # Delete key value
>>> dict1
{'b': 2}
>>> 

Dictionary related built-in functions

The built-in functions related to the dictionary are as follows:

  1. len() finds the number of dictionary elements
  2. str() converts the dictionary to a string.

Built in functions, for example:

>>> len(dict2)
2
>>> str(dict2)
"{'apple': 'big', 'orange': 'small'}"
>>> 

remarks

Embracing trees grow at the slightest—— Laozi Laozi

Topics: Python