I. Differences between input () and raw_input ()
Code
1 >>> buck = input("Enter your name: ")
2 Enter your name: liu
3
4 Traceback (most recent call last):
5 File "<pyshell#1>", line 1, in <module>
6 buck = input("Enter your name: ")
7 File "<string>", line 1, in <module>
8 NameError: name 'liu' is not defined
9 >>> buck = raw_input('Enter your name: ')
10 Enter your name: liu
As shown in the preceding example, raw_input () regards the input as a string, while input is not. Input () judges the type based on the input, of course, if you want to enter a string, you must quote it with money.
Ii. Output Problems
If we define an integer and output it with the string at the same time, as shown below:
Code
>>> n = 20
>>> print('the num is '+20)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
print('the num is '+20)
TypeError: cannot concatenate 'str' and 'int' objects
As you can see, the plus sign cannot be used directly. There are three solutions:
First, you can convert n to a string using the STR () built-in function:
>>> n = str(n)
>>> print('the num is '+ n)
the num is 20
The second type is the plus sign. The key is under the ESC key, for example:
>>> b = 20
>>> print('the num is '+ `b`)
the num is 20
The third is to use placeholders, which are similar to the placeholders in C language, but note that the % instead of comma is used to connect strings with other types of data.
>>> print('the num is %d ' % b)
the num is 20
Iii. Sequences. This is a bit like an array. below is its definition and truncation (slicing)
Code
>>> example = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> example[:8]
[0, 1, 2, 3, 4, 5, 6, 7]
>>> example[-5:]
[5, 6, 7, 8, 9]
>>> example[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> example[1:8:2]
[1, 3, 5, 7]
>>> example[::-2]
[9, 7, 5, 3, 1]