Python Tutorial
What is Python?
• Interpreted, Object-oriented, High-level programming language • Has high-level built in data structures
Copyright By PowCoder代写 加微信 powcoder
• Has dynamic typing and dynamic binding
• Supports both procedural and object-oriented paradigm
• Downloads, documentation, community support, news and event at: https://www.python.org/
Copyright © 2021 2
What is Python (cont’d)
• Useful for scripting
• Does not have a compilation step
• Various built-in functions/modules allow for fast development
• Compatible with many popular databases like PostgreSQL and MySQL
Copyright © 2021 3
What does Python code look like?
• Simpler than equivalent C, C++, or Java code • Shorter than C, C++, Java
• Offers greater error checking than C
• Simple, easy to learn syntax
• Allows splitting program into modules which can be reused
Copyright © 2021 4
Getting Started with Python Interpreter
• The interpreter usually gets installed at /usr/local/bin/pythonX.Y: /usr/local/bin/python3.7
• The interpreter can be started using python3.7 or later versions (3.8 and 3.9 recommended) or simply python after putting the interpreter path in Unix shell’s search path or the environment variables in Windows.
• Another way to start the interpreter is python –c command [arg] … This executes the statements in ‘command’ script
• The script name and arguments are turned into a list of strings and assigned to the argv variable in the sys module
Copyright © 2021 5
Hello World Example
• sample.py:
’’’sample.py file to print Hello World’’’
print(“Hello World”)
• Run sample.py as python sample.py
Copyright © 2021 6
Comments in Python
• There are two types of comments in Python
# Single-line Shell-style comments
’’’ These are
Multi-line comments.’’’
Copyright © 2021 7
Python Variables
• Python variables can be declared by any name or even alphabets like a, aa, abc, etc.
• Variables are case-sensitive (abc != aBc)
• Global variables can be used anywhere (declared outside a
• Local variables restricted to a function or class
• No keyword called static is present
• Variables assigned values inside a class declaration are class variables
• Variables assigned values in class methods are instance variables
Copyright © 2021 8
Python Variables (cont’d)
• Variables are containers for storing data values
• Python has no command for declaring a variable
• A variable is created the moment you first assign a value to it
• Variables are not statically typed
• Integers can become floats, then can become strings
• Variables take the type of the current value
• If you want to specify the data type of a variable, this can be done with “casting”
• Variable types include :
§ Boolean, Integer § Float, String
§ List, Object
§ NULL, Tuple
§ Dictionary, Set
Copyright © 2021 9
Python Variables (cont’d)
• Assignment by value a = 10
c = [1, 2, 3, 4] # List
d = (1,2) # Tuple
e = {’key’: ’value’} # Dictionary
Copyright © 2021 10
Displaying Variables
• To display a variable, use the print statement; pass the variable name to the print statement, enclosing it in brackets (for python 3.x) or without brackets(for python 2.x):
print(age) #python 3.x
print age #python 2.x
• To display both text strings and variables, pass them to the print statement as individual arguments, separated by commas:
print(“The legal voting age is “, age)
Copyright © 2021 11
Naming Variables
• The following rules and conventions must be followed when naming a variable:
• Variable names must begin with a letter or underscore (_) character
• Variable names may contain alphanumeric characters (uppercase and lowercase letters), numbers, or underscores (_).
• Variable names cannot contain spaces
• Variable names are case sensitive
Copyright © 2021 12
Python Constants
• Constants are special variables that hold values that should not be changed
• Start with letter or underscore (_) followed by letters, numbers or underscores
• Use them for named items that will not change
• Constant names use all uppercase letters
• Constants have global scope
• The constants module of python can be used for some common constants like PI, GRAVITY etc.
• Constants are not really part of Python specification but part of community usage
Copyright © 2021 13
Python Operators
• Standard Arithmetic operators
+, -, *, / (always returns a float value), % (modulus), **
(exponentiation) and // (floor division)
• String concatenation with a ‘+’ character car = “SEAT” + ” Altea”
print(car) would output “SEAT Altea”
• Basic Boolean comparison with “==“
• Using only = will overwrite a variable value (assignment)
• Less than < and greater than >
• <= and >= as above but include equality
• != can be used to check if two variables are not equal
Copyright © 2021 14
Python Operators (cont’d)
• Assignment (=) and combined assignment a = 3;
a += 5; // sets a to 8;
b = “Hello “;
b += “There!”; // sets b to “Hello There!”;
• Bitwise operators (&, |, ^, ~, <<, >>)
a ^ b(Xor: Bits that are set in a or b but not both are set.) ~a (Not: Bits that are set in a are not set, and vice versa.)
All arithmetic and bitwise operators can be combined with the assignment operator
Note: Python DOES NOT support ‘++’ and ‘–’ notation for auto increments and decrement
Copyright © 2021 15
Python Operators (cont’d)
• Logical Operators
• and: returns true if both statements are true (replacement for &&)
If x=3, then x<5 and x<10 returns True
• or: Returns True if one of the statements is true (replacement for ||)
If x = 4, then x<4 or x<5 returns True
• not: Reverse the result, returns False if the result is true
• Identity Operators
• is: Returns true if both variables are the same object
• is not: Returns true if both variables are not the same object
• Membership Operators
• in: Returns True if a sequence with the specified value is present in the
• not in: Returns True if a sequence with the specified value is not present in the object
Copyright © 2021 16
Data Types
Python is a dynamically typed language (similar to JavaScript)
Python supports the following types: • Boolean: True or False
• Numeric types
• Integer: Positive or negative whole numbers, complex numbers (eg., 3 + 5j)
• Float: Any real number • Sequence types
• String: Sequence-type data type allowing for individual character access • List: Ordered collection of one or more data items, could be of different
types, enclosed in square brackets (eg., [1, ‘Hello’, 3.41, True])
• Tuple: Ordered collection of one or more data items, could be of different types, enclosed in parentheses (e.g., (1,2,”Hello”))
• Dictionary: Unordered collection of data in key:value pairs form, enclosed in curly brackets (e.g., {1:"Professor", 2:"Marco",3:"Papa"}
Copyright © 2021 17
Data Types Example
vat_rate = 0.175 /* VAT Rate is numeric */ print(vat_rate * 100 + "%") // throws TypeError print(str(vat_rate * 100) + "%") // outputs "17.5%"
Copyright © 2021 18
Numeric Data Types
• Python supports two numeric data types:
• An integer is a positive or negative whole number with no decimal places (- 250, 2, 100, 10,000) or complex numbers with ‘j’ denoting the imaginary part (2 + 4j)
• A floating-point number is a number that contains decimal places or that is written in scientific notation (-6.16, 3.17, 2.7541)
Copyright © 2021 19
Boolean Values
• A Boolean value is a value of True or False (true and false, in lower case ,are invalid)
• In Python programming, you can only use True or False Boolean values
• In other programming languages, you can use integers such as 1 = True, 0 = False
Copyright © 2021 20
Strings in Python
• A collection of one or more characters, enclosed in single or double quotes • Can use backslash as escape character
• Concatenate strings using ‘+’. Repeat using ‘*’
• Strings can be indexed
a = "Hello "
print(a[0]) # prints H
print(a[-1]) # prints o – reverse indexing
• Strings can be sliced print(a[1:3]) #prints ‘el’
• Strings are immutable
Copyright © 2021 21
Lists in Python
• An ordered collection of one or more data items, not necessarily of same type, enclosed by square [] brackets
• Lists have multiple methods like append(), insert(), remove(), sort(), count(), reverse(), etc. to manipulate the elements of the list
• The del statement allows deletion of elements and even complete lists (converts to empty list) as well as variables (reference error if you try to access the same variable)
Copyright © 2021 22
Sets in Python
• An unordered collection of objects with no duplicate elements, not necessarily of same type, separated by commas, and enclosed by curly {} brackets
• Used for membership tests, eliminating duplicates, union, intersection, difference and symmetric difference
Copyright © 2021 23
Dictionaries in Python
• Dictionaries are like ‘associative arrays’, unordered sequences of key-value pairs
• Indexed using keys that are of immutable types
• General format:
dict = { key1:value1, key2:value2,...keyN:valueN }
• list(dictionaryName) returns list of keys
• Can be created using either {} or dict()
• The key and value can be retrieved at the same time using items() method
Copyright © 2021 24
bar = "Hello"
foo = (foo * 7)
bar = (bar * 7)
bar = (bar + 7)
Variable usage
#Numerical variable
#String variable
#Multiples foo by 7
#VALID expression (bar becomes
#HelloHelloHelloHelloHelloHelloHello #Invalid expression, throws error
Copyright © 2021 25
bar = "Hello" print(bar) print(foo,bar) print("5x5=",foo) print("5x5=foo")
‘print’ example
// Numerical variable
// String variable
// Outputs Hello
// Outputs 25 Hello
// Outputs 5x5= 25
// Outputs 5x5=foo
Notice how print "5x5=foo" outputs ‘foo’ rather than replacing it with 25
Copyright © 2021 26
a_squared = a**c
print(total)
print(a_squared)
// total is 45
// subtraction
// multiplication
// division
// a = a+5 - also works for *= and /=
Arithmetic Operations
Copyright © 2021 27
Concatenation
Use a ‘+’ to join strings into one.
string1="Hello"
string2="Python"
string3= string1 + " " + string2
print(string3)
Output: Hello Python
Copyright © 2021 28
Escaping Characters
• If the string has a set of double quotation marks that must remain visible, use the \ [backslash] before the quotation marks to ignore and display them.
heading="\"Computer Science\""
print(heading)
Output: "Computer Science"
Copyright © 2021 29
Python Control Structures
• Control Structures: the structures within a language that allow us to control the flow of execution through a program or script.
• Grouped into conditional / branching structures (e.g. if/else) and repetition structures (e.g. while loops).
• Example if/elif/else statement: [notice the “:”] if (foo == 0):
print("The variable foo is equal to 0") elif ((foo > 0) && (foo <= 5)):
print("The variable foo is between 1 and 5")
print("The variable foo is equal to",foo)
Copyright © 2021 30
If (condition):
Statements
Statement No ‘Then’ in Python !
If ... Else...
if(user=="John"): print("Hello John.")
print("You are not John.")
Copyright © 2021
General format:
While (condition):
Statements;
While Loops
While(count<3):
print("hello Python. ") count += 1
// count = count + 1
Output: hello Python. hello Python. hello Python.
Copyright © 2021 32
For Loops and range()
• Iterate over a sequence
• The built-in range() function helps iterate over a range of numbers for i in range(5):
print(i) # Prints 0,1,2,3 and 4
• Iterate over elements (for each)
• Used with sequence type data-types like string, lists and tuples.
Word = "Hello"
for letter in word:
print(letter) #PrintsHellocharacterbycharacter General format: for condition:
Statements;
Copyright © 2021 33
Date Display
import datetime
datedisplay=datetime.datetime.now() print(datedisplay.strftime(%Y/%-m/%-d))
# If the date is April 1st, 2012 Output: 2012/4/1 # It would display as 2012/4/1
datedisplay=datetime.datetime.now() print(datedisplay.strftime(%A, %B, %-d, %Y))
# If the date is April 1st, 2012 Output: Wednesday, April 1, 2012 # Wednesday, April 1, 2012
Copyright © 2021 34
Month, Day & Date Format Symbols
%-m (for Linux)
%#m (for Windows)
Day of Month
Day of Month
%-d (for Linux) %#d (for Windows)
Day of Week
Day of Week
Copyright © 2021 35
• Functions MUST be defined before they can be called • Function headers are of the format [notice the ‘:’]
def functionName(arg_1, arg_2, ..., arg_n): • Note that no return type is specified
• Function names are case sensitive (foo(...) != Foo(...) != FoO(...))
• Functions can have default argument values
def functionName(a, b=2, c=[]) # Note: Default argument # values are initialized
# only once
Copyright © 2021 36
# This is a function
def foo(arg_1, arg_2):
arg_2 = arg_1 * arg_2
return arg_2
result_1 = foo(12, 3)
print(result_1)
print(foo(12, 3))
# Store the function
# Outputs 36
# Outputs 36
Functions example
Copyright © 2021 37
Include Files
• Include “hello.py” within another python file as
import hello
from hello import hello #imports the hello() from
• The file hello.py might look like: def Hello():
print("Hello")
• In the aforementioned python file, the Hello() function can be called as hello.Hello()
• Using ‘*’ allows importing all submodules from a package from packageName import *
Copyright © 2021 39
Classes in Python
class className:
• To instantiate a class object, use function notation
• A constructor can be defined as def __init__(self):
• The dot (‘.’) notation can be used to access class variables and methods
• Inheritance can be done as:
class DerivedClassName(moduleName.BaseClassName):
Copyright © 2021 40
Code Examples
• All following code samples from “The Python Tutorial” at: https://docs.python.org/3/tutorial/index.html
Copyright © 2021 41
String Examples
Copyright © 2021 42
List Examples
Copyright © 2021 43
List Examples (cont’d)
Copyright © 2021 44
List Examples (cont’d)
Copyright © 2021 45
Looping examples
Use of range
Copyright © 2021 46
Function example
Copyright © 2021 47
Sets Examples
Copyright © 2021 49
Dictionary Examples
Copyright © 2021 50
Looping Techniques
Copyright © 2021 51
Handling Exceptions
• Use try ... except statement for exception handling
• If no exception occurs, except clause will be skipped. Else, the try clause is
stopped, and the matched exception clause will be executed.
while True: try:
x = int(input("Please enter a number: "))
except ValueError:
again...")
print("Oops! That was no valid number. Try
Copyright © 2021 52
Import Module
• A module is a file containing Python definitions and statement with the suffix ‘.py’ appended
• Import a module by its name import fibo
• Import the methods from a module from fibo import fib,fib2
• Import all that a module defines from fibo import *
Copyright © 2021 53
• Flask is a lightweight WSGI (Web Server Gateway Interface) web application framework
• WSGI is a Python standard defined in PEP 3333 https://www.python.org/dev/peps/pep-3333/
• WSGI specifies a standard interface between web servers and Python web applications or frameworks
• Flask is designed to make getting started quickly and easily, with the ability to scale up to complex applications
• Flask offers suggestions but doesn't enforce any dependencies or project layout
• Documentation at: https://palletsprojects.com/p/flask/
Copyright © 2021 54
Installation
• Use native virtual environment for Python3 $ python3 -m venv venv
• Use third party for any version of Python older than 3.4 (includes 2.7) $ virtualenv venv
$ source venv/bin/activate
• Install Flask in venv
(venv) $ pip3 install flask
Copyright © 2021 55
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello, World"
Flask Hello World
Copyright © 2021 56
Flask Hello World (cont’d)
(venv) $ export FLASK_APP=hello.py
(venv) $ flask run
Serving Flask app ”hello_world" *
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Copyright © 2021 57
app/routes.py
from app import app
@app.route('/’)
@app.route('/index’)
def index():
user = {'username': 'Miguel’}
return ‘’’
Hello, ”’ + user[‘username’] + ”’!
”’
Copyright © 2021 58
app/routes.py: Fake post in view function
‘author’: {‘username’: ‘John’},
‘body’: ‘Beautiful day in
Portland!’
‘author’: {‘username’: ‘Susan’},
‘body’: ‘The Avengers movie was
so cool!’ } ]
render_template(‘index.html’,
title=’Home’, user=user,
posts=posts)
from flask import
render_template
from app import app
@app.route(‘/’)
@app.route(‘/index’)
def index():
user = {‘username’:
posts = [ {
render_template
Copyright © 2021 59
render_template (con’d)
app/templates/index.html
{% if title %}
{% else %}
{% endif %}
Hi, {{ user.username }}!
{% for post in posts %}
{{ post.author.username }} says:
{{ post.body }}
{% endfor %}
Copyright © 2021 60
Web Output
Copyright © 2021 61
Templates are old tech
Pre-Ajax coding patterns:
• Python templates + HTML {% … %}
• PHP+HTML...?>
• ASP (Active Server Pages) + HTML <% ...%> • JSP (Java Server Pages) + HTML <% ... %>
Post-Ajax coding patterns: All RESTful APIs, returning data only (JSON, XML) and no HTML
Copyright © 2021 62
RESTful Service in Flask
from flask import Flask, jsonify
app = Flask(__name__)
{ ‘id’: 1, ‘title’: u’Buy groceries’, ‘description’: u’Milk, Cheese, Pizza, Fruit, Tylenol’, ‘done’: False },
{ ‘id’: 2, ‘title’: u’Learn Python’, ‘description’: u’Need to find a good Python tutorial on the web’, ‘done’: False } ]
if __name__ == ‘__main__’:
app.run(debug=True)
Copyright © 2021 63
RESTful Service in Flask
#retrieve the list of task @app.route(‘/todo/api/v1.0/tasks’, methods=[‘GET’]) def get_tasks():
return jsonify({‘tasks’: tasks})
See: https://flask.palletsprojects.com/en/1.1.x/api/#flask.json.jsonify
Copyright © 2021 64
Copyright © 2021 65
RESTful Service in Flask (2)
from flask import abort
#retrieve a task
@app.route(‘todo/api/v1.0/tasks/
task = [task for task in tasks if task[‘id’] == task_id] if len(task) == 0:
abort(404)
return jsonify({‘task’: task[0]})
Copyright © 2021 66
Copyright © 2021 67
Send Static File
• Put index.html into the static folder (same for CSS and JS files) • Send the static file using send_static_file
• Can also use send_from_directory
app = Flask(__name__)
@app.route(‘/’)
def homepage():
return app.send_static_file(“index.html”)
Copyright © 2021 68
Requests: HTTP for Humans
• Simple HTTP library for Python
• See: https://requests.readthedocs.io/en/master/ •
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com