Python from rookie to expert (8): Print function, assignment and code block

Source: Internet
Author: User
Tags stdin unpack throw exception

1. The magical print function
The print function believes that the reader must be familiar with it, because in the previous chapter, almost every example uses the print function, the function of this function is to output text in the console. However, print can also make some settings when outputting text, and output multi-parameter character strings.

If multiple parameter values are passed into the print function, then the print function will output all the parameter values end to end.

# Output result: a b c d e
print ("a", "b", "c", "d", "e");
We can see that the above line of code outputs a to e, a total of 5 letters. "A b c d e" was output in the Python console. Obviously, these five characters are output end to end. However, these letters are separated by spaces. This is the default delimiter of the print function. It is used to separate multiple output parameter values. This default setting is very useful. For example, when executing the following code, the equal sign (=) Add a space after it.

print ("name =", "Bill")
print ("age =", 30)
The output is as follows:
name = Bill
age = 30

The space before the equal sign (=) is included in the first parameter value.

The print function will add a space in front of the other parameter values except the first parameter value. In this way, in the scene that needs to be separated by spaces, there is no need to add spaces in front of each parameter value.

However, this default setting has advantages and disadvantages. When space separation is not required, the print function will still add spaces. For example, to output the string "Apple, Orange, Banana". Among them, Apple, Orange and Banana are separated by a comma (,), and there is no space between the comma (,) and the English word. If you follow the previous approach, there will be the following code output this line of string.

print ("Apple", ",", "Orange", ",", "Banana")
The output is as follows:
Apple, Orange, Banana

print ("Apple", ",", "Orange", ",", "Banana")
Obviously, there are spaces before and after the comma (,). Of course, you can combine the comma (,) with the previous English word, but there will still be spaces between the comma (,) and the following English word.

print ("Apple", ",", "Orange", ",", "Banana")
There are many ways to solve this problem, for example, you can output the string "Apple, Orange, Banana" in the traditional way of adding strings.

print ("Apple" + "," + "Orange" + "," + "Banana")
Now we want to solve this problem with the unique method of print function, which is to modify the default multi-parameter value separator. Add "sep =", "" at the end of the print function to change the separator from a space to a comma (,). Now you can use the following code to output the string "Apple, Orange, Banana" directly.

print ("Apple", "Orange", "Banana", sep = ",")
Output the result.
Apple, Orange, Banana

When the print function outputs a string, a newline character (\ n) is added to the end of the string by default, so that each time the print function is called to output the string, a new line will be added. However, sometimes we want to call the print function multiple times and output it on the same line. At this time, we can add "end =" "at the end of the print function to make the end of the last output string into a space instead of the original" \ "", of course, you can also set the end character to a string with a length of 0, so that the results of multiple uses of the print function will be connected end to end, without any separator in the middle.

print ("a", end = "");
print ("b", end = "");
print ("c");
Output: abc

The following example demonstrates the print function output multi-parameter value, modify the default multi-parameter value separator, and modify the output string end character method.

# Output multiple parameter values separated by spaces
print ("name =", "Bill")
# Output multiple parameter values separated by spaces
print ("age =", 30)
# Use plus sign (+) to connect strings
print ("Apple" + "," + "Orange" + "," + "Banana")
# Modify the multi-parameter value separator to comma (,), and then output the multi-parameter value
print ("Apple", "Orange", "Banana", sep = ",")
# Modify the multi-parameter value separator to "&" and then output the multi-parameter value
print ("Can", "you", "tell", "me", "how", "to", "get", "to", "the", "nearest", "tube", "station", sep = "&")
# Modify the end of the output string to a space, so that the next time the print function is called, it will output the same line
# Running result: Hello world
print ("Hello", end = "")
print ("world")
# Modify the output string end character to a string with a length of 0, so that the next time the print function is called, the output content will not only be on the same line,
# And will be connected end to end, the result of the operation: abc
print ("a", end = "");
print ("b", end = "");
print ("c");
The results of the program run are shown in the figure below.

enter image description here

2. Interesting assignment operations
In the eyes of many readers, the assignment operation can not be easier, we also used the assignment operation in the previous chapter many times. But the assignment operation in Python is much more interesting. For example, you can assign multiple values to multiple variables at the same time.

>>> x, y, z = 1,2,3
>>> print (x, y, z)
1 2 3
In the above code, 1, 2, and 3 were assigned to x, y, and z variables, respectively, and the values of these three variables were output. Using this feature in the Python language can easily achieve the exchange of values between two variables.

>>> x, y = 20,30
>>> x, y = y, x
>>> print (x, y)
30 20
This operation of assigning multiple values to multiple variables at the same time, the value on the right side of the equal sign (=) and the number of variables on the left side must be equal, otherwise an exception will be thrown.

>>> x, y, z = 1,2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>> x, y = 1,2,3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
This feature of the Python language is called Sequence Unpacking. In fact, any iterable object supports this feature. Detailed information about iterative objects (lists, collections, etc.) will be introduced in later chapters. .

Python also supports Chained Assignments and Augmented Assignments. Chained assignment refers to assigning the same value to multiple variables in succession.

x = y = 20
Incremental assignment refers to a simplified form of an expression that increases or decreases the variable itself (negative increment) by a specified value. For example, x = x + 2, if you use an incremental assignment expression, you can write x + = 2, that is, omit the x to the right of the equal sign (=), and put the plus sign (+) to the left .
In fact, the binary operators introduced earlier all support incremental assignment. For example, x = x 20 can be written as x = 20, and x = x% 3 can be written as x% = 3.

The following example demonstrates the use of sequence unpacking, chain assignment, and incremental assignment.

x, y, z = 1,2,3 # Assignment using sequence unpacking
print (x, y, z)

x, y = y, x # Use sequence unpacking to exchange the values of x and y
print (x, y)

# x, y, z = 1,2 # throw exception
# x, y = 1,2,3 # throw exception

x = y = 20 # Use chain assignment to set x and y
print (x, y)

x * = 2 # incremental assignment
x% = 3 # incremental assignment
print (x)
The results of the program run are shown in the figure below.

enter image description here

"Python from rookie to master" has been reprinted, so stay tuned

image.png

3. Create code blocks with indentation
The code block is not a statement, but the knowledge that must be mastered before learning the conditions and looping statements.

A code block is a group of statements that are executed when the condition is true (true). Place a space in front of the code to indent the statement to create the code block.

Note: Using tab characters can also indent statements to form code blocks. Python interprets a tab character as a move to the position of the next tab character, and a tab character is 8 spaces, but the Python standard recommends the use of space indentation to create code blocks. It is recommended to use 4 space indentation to create code Piece.

Each line of code block should be indented by the same amount. The following pseudo-code (not real Python code) shows how to create code blocks with indentation.

This is a code line
This is another code line:
    This is a block
    continuing the same block
    the last line of this block
We escaped the inner block
Many programming languages use special words or characters to denote the beginning of a code block, and another word or character to denote the end of a code block. For example, Pascal uses begin to denote the start of a code block, and end to denote the end of a code block, while C Style programming languages (such as Java, C #, C ++, etc.) use a pair of braces to indicate the beginning and end of a code block. The Python language is different from these languages. The Python language uses a colon (:) to indicate the beginning of the code block, and each statement in the code block is indented (the same amount of indentation). When rewinding to the same indentation as the fast start statement, it means that the current block has ended. Many integrated development environments (IDEs) will help users easily grasp indentation, so readers do n’t have to worry about incorrect indentation that can cause Python programs to fail to compile.
Original address: http://blog.51cto.com/androidguy/2170943

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.