Notes on basic Python learning.
1. Installation of Python
Download link for Python:
https://www.python.org/downloads/
Simply download and install the package for your corresponding platform.
2. Using Python or Python3
1. Set up the environment configuration file: <span>sudo vi /etc/profile</span>, this is for global variables affecting all users. Generally, you only need to modify:
vi ~/.bash_profile
export PATH="$PATH:/usr/local/bin/python"
source ~/.bash_profile
echo $PATH
2. When using the system’s Python, type Python in the terminal; when using Python3, type Python3.
3. Several Advantages of Python
- Software quality emphasizes readability, consistency, and software quality, with better reusability and maintainability than traditional languages; supports advanced reuse mechanisms for software development, OOP;
- Improves development efficiency, with concise code that does not require compilation and can run immediately;
- Portability of programs (cross-platform);
- Support from the standard library; includes many pre-compiled and portable functional modules;
- Component integration; flexible integration mechanisms; not just a standalone tool;
- Enjoy simplicity and fun; usability and powerful built-in tools make programming enjoyable rather than tedious repetitive work.
Among these, quality and efficiency are two strong advantages of Python, which are the main reasons for choosing to use Python.
- Interpreted language Python is interpreted, so there is no need to recompile the entire system to incorporate modifications.
- Disadvantages of Python The disadvantage of Python is its performance, which is not as fast as conventional compiled languages like C or C++, but it is fast enough for the vast majority of applications.
4. Running .py Files
For example, write a file with a .py suffix and type the following content:
1. Directly run
# first Python script
import sys
print(sys.platform)
print(2 ** 100)
x = 'Spam!'
print(x * 8)
Save it as test.py, then navigate to the directory of the file in the terminal and execute the command:
<span>$ python test.py</span>
If there are no syntax errors, you will see the output. You can also use stream redirection to save the input information to a text file, so the output will not be visible in the terminal, as shown in the following command:
<span>$ python test.py > out.txt</span>
2. Importing and Reloading Modules
>>> import test
darwin
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!
>>> import test
>>> import test
When importing another module, you do not need to write the suffix (.py). The command will execute once upon import, but will not execute again afterward. You need to use the reload function to reload it, as follows:
>>> from imp import reload # In 3.0, this statement is required; in 3.0 and later, reload is not a built-in function but is in the imp standard library
>>> reload(test)
darwin
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!
<module 'test' from 'test.pyc'>
>>>
3. Using exec to Run Module Files
>>> exec(open('test.py').read())
darwin
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!
>>>
Start the file from the interactive prompt without needing to import and reload; each run is the latest code.
<span>Disadvantages:</span>
The exec mechanism works as if the code was pasted at the place it was called, which has the potential to overwrite current variables by default.
While import runs the file only once per process (the cost is that it needs to be reloaded after each modification).
4. Getting User Input
<span>input()</span> and <span>raw_input()</span>
Using functions (note the distinction):
input("Please enter a number:")
>>>> input("Please enter your name:")
Please enter your name:Java
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'Java' is not defined
>>>> raw_input("Please enter your name:")
Please enter your name:iter
'iter'
The difference: raw_input automatically adds quotes to the string and will not throw an error.
In interactive mode, use if to judge, such as:
>>>> if time % 60 == 0 : print "on the hour"
5. Functions
Functions can be standard functions or user-defined functions. Standard functions are built-in functions in Python, while user-defined functions can be declared using def, similar to methods in Java, but with some differences in usage. For example, the power operator:
>>>2**3
>>>8
You can use: pow(2,3) as a substitute, similar to abs(), floor(), etc., which are standard functions known as built-in functions.
6. Modules
You can use import to import modules, such as:
>>> import math
>>> math.floor(32.9)
32.0
Using "from module import function", such as:
>>> from math import sqrt
>>> sqrt(9)
3.0
This way, you can use the function directly without using the module name.
7. Running Python
1) Generally, you can execute using the Python command:
$ python hello.py
2) Set Python to run like a normal program by adding:
#!/usr/bin/python
The execution command path for Python varies based on installation path. You can execute directly as follows (assuming in the current directory):
hello.py or ./hello.py
8. String Usage Tips in the Terminal
Long strings that need to span multiple lines can use ”’ or “””, such as:
>>> print '''jjkjk
... fdfdf.
... fdfdf'''
jjkjk
fdfdf.
fdfdf
>>>>
Output the raw string, i.e., without formatting it, by adding r before the string:
>>> print "hello,
world!"
hello,
world!
>>> print "hello,\nworld!"
hello,
world!
>>> print "hello,
world!"
hello,
world!
>>> print r"hello,
world!"
hello,
world!
9. Comments in Python
Python comments are completely different from Java comments.
# Single line comment
'''
This is a multi-line comment, using single quotes.
This is a multi-line comment, using single quotes.
This is a multi-line comment, using single quotes.
'''
"""
This is a multi-line comment, using double quotes.
This is a multi-line comment, using double quotes.
This is a multi-line comment, using double quotes.
"""
10. Lists and Arrays
In data structures, the most basic sequence, mainly learning the two most commonly used built-in sequences in Python: <span>list</span> and <span>tuple</span>. The difference: lists can be modified, while tuples cannot be modified.
The other four types are: <span>string</span>, <span>Unicode string</span>, <span>buffer object</span>, and <span>xrange object</span>.
1. Slicing (Splitting Strings)
Slicing means extracting from a list based on index, left closed and right open.
The format is as follows:
numbers = [1,2,3,4,5,6,7,8,9,10]
# Step (third), cannot be 0
print numbers[0:10:2]
# Counting from the end
print numbers[-6:-2]
You can use built-in functions like append, insert, remove, pop, count, etc., to manipulate lists.
>>> numbers = [1,2,3,4,5,6,7,8,9,10]
>>> print(numbers[0:10:2]) # The third parameter is the step, cannot be 0, can be negative to extract from right to left
[1, 3, 5, 7, 9]
>>> print(numbers[8:4])
[]
>>> print(numbers[8:4:-2]) # When the step is negative, extract from right to left. Note that the left index must be greater than the right index
[9, 7]
>>> print(numbers[3:4:-2])
[]
>>> print(numbers[-6:-2]) # From the 6th to the 2nd from the end (not included)
[5, 6, 7, 8]
>>> print(numbers[6:-2]) # From the 6th to the 2nd from the end (not included)
[7, 8]
When the index value is empty:
>>> print(numbers[:3]) # From the start to the element at index 3
[1, 2, 3]
>>> print(numbers[5:]) # From index 5 to the last element
[6, 7, 8, 9, 10]
>>> print(numbers[-3:]) # From the 3rd last index to the last element
[8, 9, 10]
>>> print(numbers[:]) # Extract (copy) the entire list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Two sequences can be added to form a new sequence:
>>> [1,2] + [3,4]
[1, 2, 3, 4]
2. None Value Representation
For example: [None, None, None]
3. Membership – in
>>> person = ['man','women','haha']
>>> 'man' in person
True
>>> 'dongwu' in person
False
4. Deleting Members – del
names = ['aa','bb','cc']
names[1] = 'dd'
# Deleting an element
del names[2]
print names
5. List Initialization
List initialization can be done using list = [] to initialize an empty list. You can also use multiplication to initialize a list with multiple repeated values, such as:
>>> [None] * 5
[None, None, None, None, None]
>>> ['Python'] * 5
['Python', 'Python', 'Python', 'Python', 'Python']
List functions such as len(), min(), max() can be used.
>>> len(numbers)
10
>>> min(numbers)
1
>>> max(numbers)
10
6. List Functions
Convert immutable strings to lists for modification and then convert back to strings. This involves using the list function.
>>> str1 = 'Hello Python!'
>>> l1 = list(str1) # Convert to list
>>> print(l1)
['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!']
>>> ''.join(l1) # Convert list back to string
'Hello Python!'
List basic operations
>>> name = [2,4,5]
>>> name[1] = 3 # Modify the value at a specific index
>>> name
[2, 3, 5]
>>> del name[2] # Delete the value at a specific index
>>> name
[2, 3]
7. Slicing Assignment
Slicing is a very powerful feature.
>>> test = list('Hell')
>>> test
['H', 'e', 'l', 'l']
>>> test[2:] = list('yPython')
>>> test
['H', 'e', 'y', 'P', 'y', 't', 'h', 'o', 'n']
>>> num = [1,4]
>>> num[1:1] = [2,3]
>>> num
[1, 2, 3, 4]
>>> num[1:3] = []
>>> num
[1, 4]
8. List Methods
List methods are also frequently used, so you must be familiar with them. Here is a table showing them.
| Method Name | Method Description | Notes |
|---|---|---|
| append | Add a new object to the end of the list | |
| count | Count the number of occurrences of an element in the list | |
| extend | Add multiple values from another list to the list at once | What is the difference from list concatenation? |
| index | The index of the first matching item of a certain element | |
| insert | Insert an object into the list | |
| pop | Remove an element from the list (default is the last one) and return its value | LIFO (Last In First Out) |
| remove | Remove the first matching item of a certain value from the list | |
| reverse | Reverse the elements in the list | |
| sort | Sort the elements of the list | Check out the new sort algorithm, how to sort dictionaries |
Similar to sorting in Java, you can also customize sorting rules, such as Python’s sorted function, which can use cmp, key, and reverse parameters to achieve advanced sorting.
>>> nbs = [1,7,8,2,4,5,3]
>>> nbs
[1, 7, 8, 2, 4, 5, 3]
>>> nbs.sort() # Default ascending order
>>> nbs
[1, 2, 3, 4, 5, 7, 8]
>>> nbs.sort(key=len)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> x = ['12e','ee','w']
>>> x.sort(key=len) # Sort by length attribute - ascending
>>> x
['w', 'ee', '12e']
>>> nbs.sort(reverse=True) # Reverse sorting
>>> nbs
[8, 7, 5, 4, 3, 2, 1]
You can use the compare method to implement custom sorting methods, such as ascending or descending.
>>> cmp(12,1)
>>> nbs.sort(cmp)
Tuples (Immutable Sequences)
Tuples are created with parentheses + commas, such as (11,33), adding a comma automatically makes it a tuple.
>>> 12,22
(12, 22)
>>> 12
12
>>> 12,
(12,)
Usage scenarios for tuples (when to use immutable tuples instead of lists):
- Tuples can be used as keys in mappings (and members of sets), while lists cannot.
- Tuples exist as return values in many built-in functions and methods. Generally, lists may better meet all the needs for sequences.
Connecting two tuples.
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# The following operation to modify tuple elements is illegal.
# tup1[0] = 99
# Create a new tuple
tup3 = tup1 + tup2
# Access elements
print "tup1[0]: ", tup1[0]
# Delete tuple
del tup
Usage scenarios and significance of tuples
- Used as keys in mappings, while lists cannot.
- Exist as return values in many built-in functions and methods.
Generally, lists will better meet the requirements for sequences. In development, lists are also used more frequently. Choose a reasonable data structure based on actual needs.
11. Strings
It is important to know that strings are immutable.
1. String Formatting
Use %s to represent, and when you need to display a percentage sign, use %%.
>>> format = 'where is %s,in the %s'
>>> values = ('TEST','room')
>>> print format % values
where is maojy,in the room
Template string:
>>> from string import Template
>>> str1 = Template('$x,glorious $x!')
>>> str1.substitute(x='slurm')
'slurm,glorious slurm!'
If part of the word needs to be replaced:
>>> str1 = Template('${x}glorious $x!')
>>> str1.substitute(x='slurm')
'slurmglorious slurm!'
>>>
You can also use <span>f"{}"</span> to format strings:
>>> name = 'niuma'
>>> code = 8888
>>> print(f"this is:{name},code:{code}")
this is:niuma,code:8888
print '%10f' % pi
print '%10.2f' % pi
print '%010.2f' % pi
print '%.*s' % (5,'guido van Rossum')
2. String Methods
Common string methods include:
find, returns the leftmost index; returns -1 if not found; can specify starting and ending points
join, adds elements to the queue
>>> dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>>> print dirs
('', 'usr', 'bin', 'env')
<span>lower</span>, returns the lowercase version of the string
<span>replace</span>, find and replace
<span>split</span>, split the string
<span>strip</span>, remove spaces or specified characters
`translate, similar to replace, replaces parts of the string, but translate only processes single characters
Two functions representing strings: <span>str()</span> and <span>repr()</span>
- str(x): converts the value to a reasonable string representation
- repr(x): creates a string that can also use
<span>x</span>(backticks) to represent the value as a valid Python expression. (Note: backticks are no longer used in 3.0).
As shown below, this is very useful when converting some values to string representations.
temp = 100
print("this num is :" + str(temp))
print(("this num is :" + repr(temp)))
print("this num is :" + `temp`)
| Method Name | Function |
|---|---|
| s.find(x) | Find substring in long string and return the leftmost index; returns -1 if not found |
| s.find(x,s,e) | The 2nd and 3rd parameters can specify the search range |
| s.join(l) | Inverse method of split, connects elements in the sequence l (converts to string) |
| l.split(x) | Inverse method of join, splits the string into a sequence, default is to use space as the delimiter |
| s.replace(x,y) | Replace x with y in the string |
| s.strip(x) | No parameters remove spaces on both sides (not including inside), with parameters remove specified characters on both sides |
12. Dictionaries
A data structure that references values by name is called a mapping.
Dictionaries are the only built-in mapping in Python. There is no special order.
1. Creating Dictionaries
There are two ways to create a dictionary: one is using {}, and the other is using the dict() function
# 1 Create using {}
d = {}
d = {"name":"py","age":18}
# 2. You can also create using the dict function
list = [('name':'py'),('age':18)]
d = dict(list)
# Create using keyword arguments
d = dict(name='py',age=18)
phoneBook = {'aa':'12','bb':'34','cc':'56'}
print phoneBook['aa']
# Create using dict function
items = [('name','Java'),('age',28)]
#d = dict(items)
# Or create using keywords
d = dict(name='mjy',age=20)
print d['name’]
del d['age']
d['name'] = 'lalala'
print d
2. String Formatting for Dictionaries
String formatting for dictionaries uses %()s (s is the description element, such as d, etc.)
print ‘my name is %(name)s’ % d
3. List of Dictionary Methods
1. clear clears all items in the dictionary; using the clear method will empty all items, including assigning to other dictionaries
pdc = {}
pdc['name'] = 'maojy'
pdc['age'] = 18
cd = pdc
print cd
print pdc.clear() # return None
print pdc # return {}
#2. copy copies the dictionary
xc={'username':'admin','machines':['foo','bar','baz']}
#yc = xc.copy() # shallow copy
yc = deepcopy(xc) # deep copy
#print yc
yc['username'] = 'java'
yc['machines'].remove('bar')
print yc
print xc
''' Output, when replacing values, the original dictionary does not change, but when modifying in place (like deleting), it will change; to avoid this problem, use deep copy - deepcopy (need to import)
{'username': 'java', 'machines': ['foo', 'baz']}
{'username': 'admin', 'machines': ['foo', 'baz']}
'''
#3. fromkeys creates a new dictionary using given keys, default value is None
fc = {}.fromkeys(['name','age']);
#fc = {}.fromkeys(['name','age'],'(unknown)'); provide default value yourself
#4. get method, returns None if not found, or specified value
print xc.get('username1','N/A')
#5. has_key checks if the dictionary contains the given key
print xc.has_key('name')
#6. items and iteritems, items method returns all dictionary items as a list; iteritems returns an iterator object
print xc.items()
#print xc.iteritems() # convert iterator to a list
print list(xc.iteritems())
#7. keys and iterkeys
# returns keys in the dictionary as a list
print xc.keys()
#8. pop, used to get the value corresponding to the key and remove this key-value pair from the dictionary
print xc.pop('name','N/A')
#9. popitem, similar to pop, but popitem pops a random item; if you want to remove and process items one by one, this method is very effective
print xc.popitem()
#10. setdefault, sets a default value; if the key does not exist, sets the default value, if it exists, returns the original value
aa = {}
aa.setdefault('name','N/A')
print aa
aa['name'] = 'mjy'
aa.setdefault('name','N/A')
print aa
#11 update, updates one dictionary item using another dictionary item
bb = {
'title':'python site',
'url':'http://xxx'
}
cc = {'title':'python language website'}
bb.update(cc)
print bb
#12. values and itervalues return all values in the dictionary as a list
print bb.values()
4. Dictionary Operations
d[k] # Access the value for key k
d[k] = v # Create a key-value pair
del d[k] # Delete the value for k
k in d # Membership check
It is important to note that using in to check membership is more efficient than checking in a list.
5. String Formatting for Dictionaries
As mentioned above, you can use tuples to format strings, and dictionaries can also be used, with even more powerful functionality.
Similar to how some front-end templates pass values for formatting, dictionaries are also used to complete formatting.
>>> d = {"abc":"123","cd":"34","ddc":"456"}
>>> text = "my select is %(ddc)s" % d
>>> text
'my select is 456'
%(key)s can be used to format with the corresponding value from the dictionary.
6. Dictionary Methods
| Method Name | Function | Notes |
|---|---|---|
| d.clear() | Clear all items | |
| y = d.copy() | Copy the dictionary, shallow copy | |
| y=deepcopy(d) | Copy all items, deep copy | Must import deepcopy function |
| d=fromkeys([‘x’]) | Create dict with specified key | Default value is None |
| d.get(key,def) | Find value based on key, default is None if not found, can specify default value | d[key] raises an error if this key does not exist |
| d.items() | Return all items as a list | |
| d.iteritems() | Return an iterator object of items | |
| d.keys() | Return keys as a list | |
| d.iterkeys() | Return an iterator object of keys | |
| d.values() | Return all values as a list | |
| d.itervalues() | Return an iterator object of values | |
| d.pop(’x‘) | Pop the value corresponding to the key and remove this key-value pair | |
| d.setdefault(x,y) | Similar to get, fetch the value corresponding to the key | Sets the corresponding key value if not given |
| d.popitem() | ||
| d.update(x) | Update one dictionary item using another dictionary item |
13. Sets
Sets are equivalent to the Set class in Java, characterized by the fact that elements in the set will not be duplicated, so it can be used in scenarios where duplicate elements are not allowed.
To create a set, you can use set()
>>> se = set()
>>> se.add('ab')
>>> se.add('mn')
>>> se
{'ab', 'mn'}
>>> se.add('ab')
>>> se
{'ab', 'mn'}
Use the add() method to add an element.
Learn the simple basics and several structural types, including strings, lists, dictionaries, tuples, and sets.