bsdnerds logo

bsdnerds.org

Learn Python (Introduction For Beginners)

This article introduces Python programming for beginners. If you are learning Python, this is a good starting resource.

All of this article uses the Python interactive shell, it covers the absolute basics.
To start the Python interactive shell, open a terminal and type Python.

Quick Q/A

1: What is Python’s built-in object type?

Some of the data types that Python has defined.

2: Python’s built-in object types include the following.

Integers, floating-point numbers, strings, lists, dictionaries, collections.

3: what is Python built-in functions?

Functions already defined by Python.

4: Python has built-in functions.

Commonly used built-in functions introduced.

Book: Python Crash Course, 125+ exercises, videos and book

Python functions

The following code was all written and run in cmd’s Python interactive interface. “Start->Run (cmd)->python” to enter the Python interactive interface

On Mac OS X and Linux you can open a terminal and type python <enter>.
If that doesn’t work, see how to run.

python interactive shell5.1 type(object)

Returns an object type, for example.

>>> type(2)

<class 'int'>

You can see that this method returns 2 as an int type of data

Python detects the data type automatically. If we write something non-numeric, it recognizes that’s another data type.

>>> type('a')

<class 'str'>

5.2 help(object)

Returns a help document for an object, such

>>>> help(id)

This then show some explanation like:

Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.

    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)

Press q to return to the Python shell

5.3 round (number [, ndigits ])

Rounds a number

  • number: any number
  • ndigits: Retain a few digits

For example.

>>> round(0.1+0.2, 2)

0.3

Returns 0.3.

If we print directly (0.1 + 0.2), the result returned is 0.30000000000000004.

>>> print(0.1 + 0.2)

0.30000000000000004

We know that 0.1+0.2=0.3, but it becomes 0.30000000000000004 due to the binary conversion, so we can round it up.

python round example The possible operators are:
  • Add (+)
  • minus (-)
  • multiplied by (*)
  • divided by (/);
  • take the balance (%)
  • quotient (//)

Strings

Strings are a collection of one more characters, wrapped in a pair of single or double quotes, such as:

name="Napoleon" 
 addr='Paris, France'

TIP: Single and double quotation marks should appear in pairs. as follows

'What's your name'

The reason for this is that the computer recognizes three more single quotes, and the first two are paired with the last one, which is not consistent with the principle of pairing. So how should it be resolved? It can be like this.

"what's your name"

Or so.

'what "s your name'

This way there are no errors. Don’t use single quotes if the outermost one is inside single quotes, and vice versa.

2.1 The + sign in a string is a join/splice character

For example.

n="python"
m="book"
n+m

Output “pythonbook”

And this “pythonbook” is actually a new object, not n or m.

2.2 len(str/object)

Returns the length of the string, for example

>>> n = "python"
>>> len(n)
6
>>> len("python")
6

The results returned are all 6.

python strings

2.3 Indexing of strings

‘str’ in object

Returns a boolean value, true if present or false, for example

>>> n = "python"
>>> 'p' in n
True

Returns true, proves that the character ‘p’ exists in the string n

str.index('str')

Returns the subscript of a string. Searching from left to right returns the first subscript encountered for the character. As follows.

>>> str = "python book"   
>>> str.index("o")
4

The result is an int value, with the 4 expression ‘o’ subscripted to the position in this string, and the subscript starting at 0.

2.4 Character slicing

The string can be slices to the str[startIndex:endIndex:stepLength ]

str string

  • startIndex starts slice (first character from left is 0, first character from right is -1)

  • endIndex end slice

  • StepLength Step length or size. The default is 1 if not specified.

Examples are as follows:

>>> r = "python book"
>>> r
'python book'
>>> len(r)
11
>>> r[0]
'p'
>>> r[-1]
'k'
>>> r[1:9]
'ython bo'
>>> r[0:9:1]
'python bo'
>>> r[0:9:2]
'pto o'
>>> r[:9:2]
'pto o'
>>> r[2::]
'thon book'
>>> r[:]
'python book'
>>> r[::-1]
'koob nohtyp'
>>> r[::-2]
'ko otp'
>>>

Tip: String slicing (intercepting) is actually copy creating a new object that has no effect on the original string object.

There is another way to do this, str.split(obj/str) cuts strings according to a certain rule, the following example is cut according to a space and returns a list of strings as follows

>>> str = "python book"
>>> str
'python book'
>>> str.split(" ")
['python', 'book']

string placeholder (computing)

>>> "I like {0} and {1}".format("python", "phpcice")
'I like python and phpcice'

Tip: The {0} and {1} in this code is equivalent to a placeholder, which can be understood as occupying a space or a position.

Setting the length of placeholder characters, and setting text alignment

As follows.

>>> "I like {0:10} and {1:>15}".format("python", "phpcice")
'I like python     and         phpcice'

Tip: an important function dir(object)

See what member functions and objects are available for an object

Lists

A list can contain any element, and the same list can contain a variety of different elements, but usually only one.

The list is ordered, so it has the operational characteristics of a sequence.

Lists can modify elements by assignment, while strings cannot. e.g., list lst[0]="12" successful, string str[0]="12" fails

The basic operation functions of the list such as indexing, slicing, etc. are the same as the string.

Definition: listName = [object] as follows.

lst = [1,2,3,4,5,6]

Common functions of the list

3.1 Adding elements to the list

Add an element at the end.

list.append(element)

Parameters: list name; element To be added

Examples are as follows.

>>> lst = [1,2,3,4,5,6]
>>> lst
[1, 2, 3, 4, 5, 6]
>>> lst.append("7")
>>> lst
[1, 2, 3, 4, 5, 6, '7']

Insert an element in front of the index.

list.insert(index, element)

Parameters: list name; index where to insert the card, i.e. subscript; element to be inserted

Examples are as follows.

>>> lst
[1, 2, 3, 4, 5, 6, '7']
>>> lst.insert(1,12)
>>> lst
[1, 12, 2, 3, 4, 5, 6, '7']

Extending the list with iteratable objects

list.extend(iterable)

Parameters: list source list name; iterable iterable element, e.g. string “12348565”

Examples are as follows.

>>> lst
[1, 12, 2, 3, 4, 5, 6, '7']
>>> str = "abcdef"
>>> lst.extend(str)
>>> lst
[1, 12, 2, 3, 4, 5, 6, '7', 'a', 'b', 'c', 'd', 'e', 'f']

python lists and functions3.2 Removing elements from the list

Deletes a specified element and returns the value of the deleted element.

list.pop(element)

Deletes the last element of the list by default when no parameters are filled

Examples are as follows.

>>> lst
[1, 12, 2, 3, 4, 5, 6, '7', 'a', 'b', 'c', 'd', 'e', 'f']
>>> lst.pop(7)
'7'
>>> lst
[1, 12, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 'e', 'f']
>>> lst.pop()
'f'
>>> lst
[1, 12, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 'e']

Deletes a specified element with no return value. Elements must be specified

list.remove(element)

Examples are as follows.

>>> lst
[1, 12, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 'e']
>>> lst.remove('e')
>>> lst
[1, 12, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd']

Delete the entire list of elements.

list.clear()

Examples are as follows.

>>> lst
[1, 12, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd']
>>> lst.clear()
>>> lst
[]

tip: list=[] also achieves the clear effect, but they are fundamentally different. list=[] reassigns an empty list to achieve the effect, this list is no longer the previous list, it is a new list with a different memory address than the previous list. But the front and back of the CLEAR are pointing to the same address.

>>> lst = [1,2,3,4]
>>> lst = []
>>> lst
[]

3.3 List ordering

list.sort()

Only the same element can be sorted. The default is ascending order. If you want to descend the order, you need to put the parameter reverse=True. list.sort( reverse=True)

Examples are as follows.

>>> lst = [2,1,9,4,3,15,21,36,11,5]
>>> lst
[2, 1, 9, 4, 3, 15, 21, 36, 11, 5]
>>> lst.sort()
>>> lst
[1, 2, 3, 4, 5, 9, 11, 15, 21, 36]
>>> lst.sort(reverse=True)
>>> lst
[36, 21, 15, 11, 9, 5, 4, 3, 2, 1]

list.reverse()

Reverse-ordering, i.e., the entire list of elements is reversed.

Examples are as follows.

>>> lst
[36, 21, 15, 11, 9, 5, 4, 3, 2, 1]
>>> lst.reverse()
>>> lst
[1, 2, 3, 4, 5, 9, 11, 15, 21, 36]

Tuple

The list is defined in parentheses [] and the tuple in parentheses ().

When there is only one element, a comma “,” must be added after the element.

A tuple is an immutable object: you cannot modify element values.

4.1 Defining the tuple

>>> t = (1,2, "python",[1,2,3])
>>> type(t)
<class 'tuples'>

The main difference is the parenthesis, for tuples use () instead of [].

Lists are mutable (changable), but tuples are immutable.

difference between tuples and lists in python

Dictionaries

A dictionary is a set of key-value pairs. Each key has a unique value.

5.1 Definition of dictionaries

>>> d = {'name':'Patricia','age':'22','city':'San Jose'}
>>> d
{'name': 'Patricia', 'age': '22', 'city': 'San Jose'}
>>>> dict(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}

Tip: A dictionary stores values in the form of key-value pairs. key cannot be repeated, key is usually an immutable key and uniquely identifies an element.

5.2 Basic operations of the dictionary

Get the value of a key-value pair by key, such as.

>>> d['name']
'Patricia'

Modify the specified element value by key as follows.

>>> d
{'name': 'Patricia', 'age': '22', 'city': 'San Jose'}
>>> d['name'] = "Raymond"
>>> d
{'name': 'Raymond', 'age': '22', 'city': 'San Jose'}

Update/add elements

dictName.update(object), for example.

>>> d
{'name': 'Raymond', 'age': '22', 'city': 'San Jose'}
>>> d.update(sal="6000")
>>> d
{'name': 'Raymond', 'age': '22', 'city': 'San Jose', 'sal': '6000'}

Delete element

del dictName[key]

Delete specified element, no return value

>>> d
{'name': 'Raymond', 'age': '22', 'city': 'San Jose', 'sal': '6000'}
>>> del d['sal']
>>> d
{'name': 'Raymond', 'age': '22', 'city': 'San Jose'}

dictName.pop(key)

Deletes the specified element and returns the value of the deleted element.

>>> d
{'name': 'Raymond', 'age': '22', 'city': 'San Jose'}
>>> d.pop('city')
'San Jose'
>>> d
{'name': 'Raymond', 'age': '22'}
>>> d.pop('city','no longer exists')
'It doesn't exist anymore.'
>>> d
{'name': 'Raymond', 'age': '22'}

dictName.popitem()

Delete the element at the end of the dictionary and return the remaining dictionary element.

Tip: This method removes one element at random in Python before 3.6 and the last element in the dictionary after 3.6.

>>> d.popitem()
('age', '22')

5.3 Two important approaches to the dictionary

When we look at a key value that doesn’t exist, the code will report an error, which could terminate our program or cause some unforeseen error, as follows.

>>> d['aa']

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

KeyError: 'aa'

How should it be resolved?

dictName.get(key,tipStr)

Parameters: key tipStr of the key dictionary element Returns a prompt to the user if the key is not found. If you don’t fill out TIPStr, there’s no prompt.

This way the program does not report errors and also has good interaction.

>>> d.get('aa')   
>>> d.get('aa','none of this element')

‘There is no such element.’

There is another method to the same effect, as follows.

dictName.setdefault(key,tipStr)

>>> d.setdefault('aa','created without')
''No so created''    
>>> d    
{'name': 'Raymond', 'age': '22', 'city': 'San Jose', 'sal': '6000', 'aa': 'none so created' }

The difference is that when no corresponding key is found, a new element is created based on the searched key and the prompt. If the prompt is not filled, a corresponding element is also created with the value None.

>>> d.setdefault('bb')   
>>> d
{'name': 'Raymond', 'age': '22', 'city': 'San Jose', 'sal': '6000', 'aa': 'none so created', 'bb': None}

5.4 The difference between a dictionary and a list

The differences:

  • Dictionaries are not sequences.
  • From Python 3.6: the dictionary is in order
  • Dictionaries have key-value pairs

The similarities:

  • Both are container-like objects.
  • Both are variable objects.

Sets

6.1 Definition of a set

Definition of a variable set

>>> s = set([1,2,3,4,5,1,2])
>>> s
{1, 2, 3, 4, 5}
>>> type(s)
<class 'set'>
>>> s2 = {"python",2,3}
>>> type(s2)
<class 'set'>

Definition of an immutable set

The immutable collection contains the basic operations of add, pop, remove, etc. for the collection.

>>> f3 = frozenset('panruihe')
>>> f3
frozenset({'h', 'p', 'r', 'i', 'a', 'e', 'n', 'u'})

6.2 Basic operation of the variable set.

Adding elements
The example of set.add(object) is as follows.

>>> s2
{3, 2, 'python'}
>>> s2.add('php')
>>> s2
{3, 2, 'python', 'php'}

Delete element

set.pop()

Delete the first element, for example.

>>> s2
{3, 2, 'python', 'php'}
>>> s2.pop()
3
>>> s2
{2, 'python', 'php'}

set.remove(element)

Delete the specified element, for example.

>>> s2
{2, 'python', 'php'}
>>> s2.remove(2)
>>> s2
{'python', 'php'}

set.discard(element)

Delete the specified element, for example.

>>> s2
{'python', 'php'}
>>> s2.discard('php')
>>> s2
{'python'}

Tip: Both remove and discard delete specified elements, so what’s the difference between them? remove removes a non-existent element, while discard removes a non-existent element without reporting an error. As follows.

>>> s2
{'python'}
>>> s2.remove('php')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'php'
>>> s2.discard('php')

What’s next?

There are many Python tutorials online like:

Book: