[basic learning of Python] 02 introduction to python (number, string, list)

Posted by obscurr on Wed, 22 Dec 2021 12:31:20 +0100

1. Write in front

  • In the code examples that will appear in later articles, the code with a prompt (> > >) runs in IDLE, and the code with a prompt (> > >) acts as an input line, otherwise it is an output line.
  • python comments start with a # sign and end at the end of the line. Comments are used to clarify the code and will not be interpreted by the interpreter, so you don't need to type comments when typing the following examples.
  • This is just a brief introduction. The purpose is not to feel too sudden when you encounter relevant examples in future learning. Strings and lists will be introduced in more detail later.

2. Figures

2.1 type

When the type of integer (e.g. 1, 4, 6) is int, the type with decimal part (e.g. 3.0, 4.5, 6.35) is float.

2.2 operators

Python's addition, subtraction, multiplication and division operators are the same as those in other languages, and we all understand them. Directly on the code.

>>> 5 + 3
8
>>> 6 - 2
4
>>> 12 * 2
24
>>> 12 / 6
2.0

Of course, synthesis expressions are also supported, where parentheses (()) are used to group

>>> 5 + 3 - 2
6
>>> (6 - 3) * 3
9
>>> 9 / 2 + 1
5.5

It is worth noting that python's division is slightly different from other languages, Many programming languages generally use floor division. Floor division means that the calculation result takes the largest integer smaller than the quotient. In other words, it means discarding the decimal part (for example, 5 / 2 = 2). However, in python, the division operation (/) always returns a floating-point number, even if two integers are divided. You can use the / / operator to represent the floor division. Use the% operator to calculate the remainder.

>>> 5 / 2
2.5
>>> 5 // 2
2
>>> 5 % 2
1

In python, you can use the * * operator to calculate the power

>>> 6 ** 2
36
>>> 3 ** 3
27

The equal sign (=) operator is used to assign values to variables

>>> a = 2
>>> b = 3
>>> a + b
5

The equal sign (=) operator can also implement multiple assignments

>>> a, b = 0, 1
>>> a
0
>>> b
1

Of course, if you try to use a variable without assigning a value to it, you will be prompted with an error

>>> i = 5
>>> i + j
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    i + j
NameError: name 'j' is not defined

When the expression contains operations of multiple mixed type operands, python will convert integers to floating-point numbers.

>>> 5 + 3 * 2.5
12.5

In the interactive interpreter, the result of the last operation is assigned to the operator.

>>> a = 3
>>> b = 5
>>> a + b
8
>>> a + _
11

3. String

Like other languages, python can manipulate strings. When creating a string, you can add quotation marks around the characters, which can be single quotation marks or double quotation marks. The effect is the same.

>>> 'python project'
'python project'
>>> "python project"
'python project'

However, the quotation marks around the string must be the same, not single quotation marks and double quotation marks.

>>> 'python project"
SyntaxError: EOL while scanning string literal

If single or double quotation marks appear in the string to be output, the following occurs

>>> 'I'm python'
SyntaxError: invalid syntax

At this time, we will use the escape character (\) to escape the quotation marks in the string, or use quotation marks different from those in the string to represent the string.

>>> 'I\'m python'
"I'm python"
>>> "I'm python"
"I'm python"

The output statement of python is the print() function, which generates more readable output, that is, omitting the quotation marks around and printing out the escaped special characters.

>>> 'I Love You'
'I Love You'
>>> print('I Love You')
I Love You

In this way, the backslash is very easy to use, but when we print C:\python\name

>>> print('C:\python\name')
C:\python
ame

The printing result is unexpected because the backslash and the following character n just form a newline (\ n). At this time, you can use another backslash to transfer the backslash

>>> print('C:\python\\name')
C:\python\name

However, if there are many such backslashes in a string, it will be too troublesome to use this method. However, don't be afraid. You can use the original string. The original string only needs to add the letter R or R in front of the string

>>> print(r'C:\python\name')
C:\python\name

If we want to implement continuous cross line input, we can use triple quotation marks ('' ''... '' or ''... ' "")

>>> print("""
	    Sympathize with farmers

      Hoe standing grain gradually pawning a midday,
      Sweat drips down the soil.
      Who knows Chinese food,
      Every grain is hard.
""")

	    Sympathize with farmers

      Hoe standing grain gradually pawning a midday,
      Sweat drips down the soil.
      Who knows Chinese food,
      Every grain is hard.

Strings can be spliced with a + sign and repeated with a * sign

>>> 'hello' + 'world'
'helloworld'
>>> 'hello' * 3
'hellohellohello'

The string can be indexed (subscript access). The first character index is 0, the second character index is 1,..., and so on. The index can also be plural. The last character index is - 1, the penultimate character index is - 2,..., and so on. Note that there is no - 0

>>> strWord = 'hello world'
>>> strWord[2]
'l'
>>> strWord[4]
'o'
>>> strWord[-1]
'd'

The string in python cannot be modified because it is an immutable object, so an error will be prompted when assigning an index position to the string

>>> strWord = 'hello world'
>>> strWord[i] = 'n'
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    strWord[i] = 'n'
TypeError: 'str' object does not support item assignment

The built-in function len() can return the length of the string (the built-in function will be described in detail in subsequent articles)

>>> strWord = 'hello world'
>>> len(strWord)
11

4. List

In Python, multiple composite data types can be obtained by combining some values. The most commonly used list can be obtained by a set of values (elements) enclosed in square brackets and separated by commas. A list can contain different types of elements, but usually each element type is the same. Unlike a string, a list is a variable object, and its value can be changed.
Create list

>>> numList = [1, 2, 3, 4, 5, 6]

Create a list containing different element types

mixList = [1, 2, 'Li Xiaodao DXL', 5.67, [1, 2, 3]]

Add an element to the list
You can use the append() method (the list function will be explained in more detail in the following article)

>>> numList = [1, 2, 3, 4, 5, 6]
>>> numList.append(15)
>>> numList
[1, 2, 3, 4, 5, 6, 15]

Get element from list
Like strings, lists also support index operations in the same way as strings. The difference is that the list can assign a value to the index position

>>> strList = ['pyhton', 'C++', 'Java', 'C#']
>>> strList[2]
'Java'
>>> strList[-1]
'C#'
>>> strList[1] = 'C'
>>> strList
['pyhton', 'C', 'Java', 'C#']

Find list length
The built-in function len() can also be used on the list to find the length of the list

>>> strList = ['pyhton', 'C++', 'Java', 'C#']
>>> len(strList)
4

Topics: Python Programming string list