Learning notes of Python: Programming: from introduction to practice_ Chapter 2 variables and simple data types

Posted by BigE on Thu, 03 Feb 2022 06:11:06 +0100

Chapter 2 variables and simple data types

2.1 run hello_world.py

Run file hello_world.py, at the end py indicates that this is a python program, so the editor will use the Python interpreter to run it. The Python interpreter reads the entire program and determines the meaning of each word in it. For example, when you see the word print, the interpreter will print the contents in the brackets to the screen, regardless of what the contents in the brackets are.

When writing a program, the editor highlights different parts of the program in various ways. For example, it knows that print is the name of a function, so it displays it in blue; It knows "Hello Python world!" It is not Python code, so it is displayed in orange. This function is called grammatical prominence.

2.2 variables

Let's try hello_ world. Use a variable in py.

message = "Hello Python world!" 
print(message)

Run this program and see how it turns out. You will find that the output is the same as before:

Hello Python world! 

We added a variable called message. Each variable stores a value -- the information associated with the variable. Here, the stored value is the text "Hello Python world!".

Let's further extend the program: modify hello_world.py to make it print another message. For this, in hello_world.py, and then add the following two lines of code:

message = "Hello Python world!" 
print(message)

message = "Hello Python Crash Course world!" 
print(message) 

Now if you run this program, you will see two lines of output:

Hello Python world! 
Hello Python Crash Course world! 

2.2.1 naming and use of variables

Be sure to keep in mind the following rules for variables:
 variable names can only contain letters, numbers and underscores. Variable names can start with letters or underscores, but not numbers. For example, you can name the variable message_1, but it cannot be named 1_message.

 variable names cannot contain spaces, but underscores can be used to separate words. For example, the variable name is greeting_message works, but the variable name greeting message raises an error.

 do not use Python keywords and function names as variable names, that is, do not use Python to retain words for special purposes, such as print.

 variable names should be short and descriptive. For example, name is better than n, student_name ratio s_n OK, name_length ratio_ of_ persons_ Name good.

 use lowercase l and uppercase O with caution, as they may be mistaken for numbers 1 and 0.

Note: for the time being, lower case Python variable names should be used. Using uppercase letters in variable names will not cause errors, but it is a good idea to avoid using uppercase letters.

2.2.2 avoid naming errors when using variables

We will intentionally write some code that causes errors. Please enter the following code, including the misspelled word mesage:

message = "Hello Python Crash Course reader!" 
print(mesage) 

When there are errors in the program, the Python interpreter will do its best to help you find the problem. When the program cannot run successfully, the interpreter will provide a traceback. Traceback is a record of where the interpreter got into trouble when it tried to run the code. The following is the traceback provided by the Python interpreter when you accidentally misspell the variable name:

Traceback (most recent call last): 
File "hello_world.py", line 2, in <module> 
print(mesage) 
NameError: name 'mesage' is not defined 

The interpreter indicates that the file hello_ world. Error in line 2 of Py; It lists this line of code to help you
Quickly find errors; It also pointed out what kind of mistakes it found. Here, the interpreter finds a
Name error and indicate that the printed variable mesage is not defined: Python cannot recognize the variable name you provided. A wrong name usually means two things: either you forget to assign a value to a variable before using it, or you enter the variable name incorrectly.

2.3 string

A string is a series of characters. In Python, strings are enclosed in quotation marks, which can be single quotation marks or double quotation marks, as shown below:

"This is a string." 
'This is also a string.' 

This flexibility allows you to include quotation marks and apostrophes in strings:

'I told my friend, "Python is my favorite language!"' 
"The language 'Python' is named after Monty Python, not the snake." 
"One of Python's strengths is its diverse and supportive community."

2.3.1 use the method to modify the case of the string

name = "ada lovelace" 
print(name.title()) 

Save this file and run it again. You will see the following output:

Ada Lovelace

The lowercase string "ada lovelace" is stored in the variable name. In the print() statement, the method title() appears after this variable. Methods are operations that Python can perform on data. In name In title(), the period after name (.) Let Python perform the operation specified by the method title() on the variable name. Each method is followed by a pair of parentheses because methods usually require additional information to complete their work. This information is provided in parentheses. The function title() requires no additional information, so the parentheses after it are empty.

title() displays each word in uppercase, that is, each word separated by spaces in the string is displayed in uppercase only.

There are several other useful case handling methods:

name = "Ada Lovelace" 
print(name.upper()) 
print(name.lower()) 

The output of these codes is as follows:

ADA LOVELACE 
ada lovelace 

The method lower() is useful when storing data. Many times, you can't rely on users to provide the correct case, so you need to convert strings to lowercase first and then store them. When you need to display this information later, convert it to the most appropriate case.

2.3.2 merge (splice) strings

first_name = "ada" 
last_name = "lovelace" 
full_name = first_name + " " + last_name 
print(full_name) 

Python uses the plus sign (+) to merge strings. In this example, we use + to merge first_name, space and last_ The complete result of name is as follows:

ada lovelace 

This method of merging strings is called splicing. Through splicing, the information stored in variables can be used to create a complete message.

You can use splicing to create a message, and then store the whole message in a variable:

first_name = "ada" 
last_name = "lovelace" 
full_name = first_name + " " + last_name 
message = "Hello, " + full_name.title() + "!" 
print(message) 

These codes display a well formed simple greeting:

Hello, Ada Lovelace! 

2.3.3 use tabs or line breaks to add white space

In programming, white space generally refers to any non printing characters, such as spaces, tabs and line breaks.

To add tabs to a string, use the character combination \ t, as shown in the following code:

>>> print("Python") 
Python 
>>> print("\tPython") 
	Python

To add a newline character to a string, use a character combination \ n:

>>> print("Languages:\nPython\nC\nJavaScript")
Languages: 
Python 
C 
JavaScript

You can also include both tab and newline characters in the same string. The string "\ n\t" moves Python to the next line and adds a tab at the beginning of the next line.

>>> print("Languages:\n\tPython\n\tC\n\tJavaScript") 
Languages: 
	Python 
	C 
 	JavaScript 

2.3.4 delete blank

Whitespace is important because you often need to compare whether two strings are the same.

Python can find extra whitespace at the beginning and end of a string. To ensure that there is no whitespace at the end of the string, use the method rstrip().

>>> favorite_language = 'python '
>>> favorite_language 
'python ' 
>>> favorite_language.rstrip()
'python' 
>>> favorite_language
'python ' 

For the variable favorite_ After language calls the method rstrip(), this extra space is deleted. However, this deletion is only temporary. Next, ask favorite again_ When you enter the value of language, you will find that the string still contains redundant white space as when you enter it.

To permanently delete the whitespace in this string, you must save the result of the deletion operation back to the variable:

>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip()
>>> favorite_language
'python' 

You can also eliminate the whitespace at the beginning of the string or at both ends of the string. To do this, use the methods lstrip() and strip(), respectively:

>>> favorite_language = ' python '
>>> favorite_language.rstrip()
' python' 
>>> favorite_language.lstrip()
'python ' 
>>> favorite_language.strip() 
'python' 

2.3.5 avoid syntax errors when using strings

When the program contains illegal Python code, it will lead to syntax errors. For example, if an apostrophe is included in a string enclosed in single quotes, it will cause an error. This is because it causes Python to treat the content between the first single quotation mark and apostrophe as a string and the rest of the text as Python code, causing an error.

message = "One of Python's strengths is its diverse community." 
print(message) 

The apostrophe is between two double quotes, so the Python interpreter can correctly understand this string:

One of Python's strengths is its diverse community. 

However, if you use single quotation marks, Python will not be able to correctly determine the end position of the string:

message = 'One of Python's strengths is its diverse community.' 
print(message) 

And you will see the following output:

 File "apostrophe.py", line 1 
 message = 'One of Python's strengths is its diverse community.' 
SyntaxError: invalid syntax

2.3.6 print statement in Python 2

In Python 2, the syntax of the print statement is slightly different:

>>> python2.7 
>>> print "Hello Python 2.7 world!" 
Hello Python 2.7 world! 

In Python 2, you don't need to put what you want to print in parentheses. Technically, print in Python 3 is a function, so parentheses are essential. Some Python 2 print statements also contain parentheses, but their behavior is slightly different from that in Python 3. Simply put, in Python 2 code, some print statements contain parentheses and some do not.

2.4 figures