Python Basic Tutorial
Python Basic Tutorial(2019.01.26 @ SCUT)
- Python Basic Tutorial(2019.01.26 @ SCUT)
Prerequisites
You can know more about conda package manager in the documentation.
Python tutorial ( Forked from CS231)
Standard Input & Output
The input()
built-in function read a line from standard input with trailing newline stripped.
The print()
built-in function usually used to print something to standard output with adding a trailing newline.
1 | something = input() |
Basic data types
Like most languages, Python has a number of basic types including integers, floats, booleans, and strings. These data types behave in ways that are familiar from other programming languages.
Numbers
Integers and floats work as you would expect from other languages:
1 | x = 3 |
Note that unlike many languages, Python does not have unary increment (x++
) or decrement (x--
) operators.
Python also has built-in types for complex numbers; you can find all of the details in the documentation.
Booleans
Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (&&
, ||
, etc.):
1 | t = True |
Strings
Python has great support for strings:
1 | hello = 'hello' # String literals can use single quotes |
String objects have a bunch of useful methods; for example:
1 | s = "hello" |
Note: strings in python are readonly objects
1 | hello = 'hello' |
You can find a list of all string methods in the documentation.
None
The sole value of the type NoneType
. None
is frequently used to represent the absence of a value.
Type casting
1 | print(int(1.5)) # Convert floating point into integer truncates towards zero |
You can konw more about Python built-in types in the documentation.
Quiz #1: Calclating A + B + C
Containers
Python includes several built-in container types: lists, dictionaries, sets, and tuples.
Lists | [value, ]
A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
1 | a = list() |
As usual, you can find all the gory details about lists in the documentation.
Slicing: In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:
1 | nums = list(range(5)) # range is a built-in function that creates a list of integers |
We will see slicing again in the context of numpy arrays.
Loops: You can loop over the elements of a list like this:
1 | animals = ['cat', 'dog', 'monkey'] |
If you want access to the index of each element within the body of a loop, use the built-in enumerate
function:
1 | animals = ['cat', 'dog', 'monkey'] |
List comprehensions: When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:
1 | nums = [0, 1, 2, 3, 4] |
You can make this code simpler using a list comprehension:
1 | nums = [0, 1, 2, 3, 4] |
List comprehensions can also contain conditions:
1 | nums = [0, 1, 2, 3, 4] |
Quiz #2: Fibonacci numbers
Dictionaries | {key: value, }
A dictionary stores (key, value) pairs, similar to a Map
in Java or an object in Javascript. You can use it like this:
1 | a = dict() |
You can find all you need to know about dictionaries in the documentation.
Loops: It is easy to iterate over the keys in a dictionary:
1 | d = {'person': 2, 'cat': 4, 'spider': 8} |
If you want access to keys and their corresponding values, use the items
method:
1 | d = {'person': 2, 'cat': 4, 'spider': 8} |
Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:
1 | nums = [0, 1, 2, 3, 4] |
Sets | {element, }
A set is an unordered collection of distinct elements. As a simple example, consider the following:
1 | a = set() |
As usual, everything you want to know about sets can be found in the documentation.
Loops: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:
1 | animals = {'cat', 'dog', 'fish'} |
Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:
1 | from math import sqrt |
Quiz #3: Remove repeated values
Tuples | (value, )
A tuple is an (immutable) ordered list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:
1 | d = {(x, x + 1): x for x in range(10)} # Create a dictionary with tuple keys |
The documentation has more information about tuples.
Control flow
Condition
Python use if
statement to perform condition control flow.
1 | x = int(input("Please enter an integer: ")) |
There can be zero or more elif
parts, and the else
part is optional. The keyword ‘elif
’ is short for ‘else if’, and is useful to avoid excessive indentation. An if … elif … elif …
sequence is a substitute for the switch
or case
statements found in other languages.
Truth value testing : Any object can be tested for truth value, for use in an if
or while
condition or as operand of the Boolean operations below. The following values are considered false:
None
False
- zero of any numeric type, for example,
0
,0L
,0.0
,0j
. - any empty sequence, for example,
''
,()
,[]
. - any empty mapping, for example,
{}
. - most of others are true.
Loops
The for
statement in Python differs a bit from other programming languages, Python’s for
statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
1 | # Loop over list: |
The while
statement is used for repeated execution as long as an expression is true.
1 | i = 0 |
A break
statement will terminate the loop.
1 | # judge whether a number is a prime number |
A continue
statement executed in the first suite skips the rest of the suite and continues with the next item.
1 | for num in range(2, 10): |
The pass
statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
1 | if True: |
You can know more about loops from offical documents , and more about Python’s simple statements in documents too
Functions
Python functions are defined using the def
keyword. For example:
1 | def sign(x): |
We will often define functions to take optional keyword arguments, like this:
1 | def hello(name, loud=False): |
There are a number of built-in functions (like len()
) in Python, you can konw more about them in the documentation.
There is a lot more information about Python functions in the documentation.
Quiz #4 : Implement sqrt()
function
Classes
The syntax for defining classes in Python is straightforward:
1 | class Greeter(object): |
You can read a lot more about Python classes in the documentation.
File Input & Output
Interact with files in Python is much easier than other languages , you can simply use open()
built-in function.
1 | # wirte content into a file |
Quiz #5: Char count
Download data file here. Calclate all characters’ frequencies and save them into charcount.txt
file like following.
1 | char counts |
Exceptions
1 | def zero_division_fails(): |
You can know more about errors and exceptions in Python in the documentation.
END
You can read a lot more about Python in official Python Tutorial.
Thank You.