Python 101
Web Programming Course
SUT • Fall 2018
Outline
-
Introduction
-
Getting Started
-
Python Basics
-
Standard Data Types
-
Operators
-
-
Control Structures
Introduction
Python
- Python is an interpreted high-level programming language for general-purpose programming
- Created by Guido van Rossum and first released in 1991
- Emphasizes code readability
-
It combines the power of systems languages, such
as C and Java, with the ease and rapid development of scripting languages, such as Ruby
Language Features
-
Simple and Minimalistic
-
Easy to Learn
-
High-level Language
-
Portable
-
Extensible
-
Embeddable
-
Extensive Libraries
-
Free, Open Source, ... and Fun!
Programming Paradigms
-
Beautiful is better than ugly
-
Explicit is better than implicit
-
Simple is better than complex
- Complex is better than complicated
- Flat is better than nested
-
Sparse is better than dense
-
Readability counts
-
Special cases aren't special enough to break the rules.
Although practicality beats purity.
-
Errors should never pass silently.
Unless explicitly silenced
-
In the face of ambiguity, refuse the temptation to guess
-
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch. -
Now is better than never
Although never is often better than *right* now.
-
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea
More on Medium
-
Python 2.0 was released in 2000, with many new
features added
-
Python 3.0, adjusting several aspects of the core language, was released in 2008
-
Python 3.0 is backwards-incompatible
-
Python 2.x is legacy, Python 3.x is the present and
future of the language
-
Python porting progress
-
We use Python 3.x in this course
Getting Started
Install
$ sudo apt-get install python3
....
$ python3
% python3
Python 3.6.7rc1 (default, Sep 27 2018, 09:51:25)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
exit()
$ipython3
% ipython3
Python 3.6.7rc1 (default, Sep 27 2018, 09:51:25)
Type "copyright", "credits" or "license" for more information.
IPython 5.5.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
-
Download Python from http://python.org
-
install
-
Python's interactive interpreter is one of the most powerful tools used in everyday Python development
- It enables you to test a few lines of code without
needing to create, edit, save, and run a source
file - Not only it verifies your code’s correctness, but it
also enables inspecting data structures or
altering key values, prior to adding it to your
source files
-
Python shell evaluates the expression entered
after prompt and displays the result
In [1]: 2 + 5
Out[1]: 7
In [2]: 2 ** 100
Out[2]: 1267650600228229401496703205376
In [3]: print(3 * 10)
30
In [4]:
First Program
- A Python program (or script) is a sequence of
Python statements that goes into a text file,
having a .py extension - This is our first Python program:
-
- People usually judge the quality of a
programming language by the simplicity of the
Hello World! program
print('Hello World!')
Comments
- Comments in Python are denoted with the hash mark (#)
- Comments are also used to prevent working
code from executing - Typical usage in configuration files to
disable/enable options
# hello.py
# By: Behnam Hatami-Varzaneh
print('Hello World!')
# short comment
Python Basics
Variables
- Python is a dynamically typed language
- Variables can be thought of as names that refer
to otherwise anonymous objects, which contain
the actual values involved - Any given variable can have its value altered at
any time
In [1]: x = 2
In [2]: x
Out[2]: 2
In [3]: x = 'Ali'
In [4]: x
Out[4]: 'Ali'
Basic Data Types
- Boolean
- Strings
- Numbers
- None
In [1]: type(True)
Out[1]: bool
In [2]: type('Hello')
Out[2]: str
In [3]: type(5)
Out[3]: int
In [4]: type(5.2)
Out[4]: float
Operators
- Basic Operators
- Arithmetic (+, - , *, /, %, //, **)
- Assignment (=, +=, -=, *= /=, %=, **= , //=)
- Comparison (<, >, <=, >=, ==, !=)
- Logical (and, or, not)
- Notes:
- + on strings does string concatenation
- * on (string, int) repeats string
Type Conversion
- Python has strong typing (unlike JavaScript)
In [5]: 'Ali' + 0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-877cabd96baa> in <module>
----> 1 'Ali' + 0
TypeError: must be str, not int
- We need to use type converter functions
In [1]: '123' + str(45)
Out[1]: '12345'
In [2]: int('123') + 45
Out[2]: 168
Input
- We can use input function to get user input
- The return value is always a string
In [1]: radius = input('Enter radius: ')
Enter radius: 123.5
In [2]: r = float(radius)
In [3]: area = 3.14159 * r ** 2
In [4]: print('The area is:', area)
The area is: 47916.3160775
Control Structures
Control Structures
- Conditionals
- if, else, elif
- Loops
- for
- while
Conditionals
- Like other languages, Python features if and else
statements - Python’s “else-if” is spelled elif
ans = input("Enter 'y' or 'n': ")
if ans == 'y':
print("Entered 'y'")
elif ans == 'n':
print("Entered 'n'")
else:
print('Invalid key pressed!')
Truth Value Testing
- Any object can be tested for truth value, for use
in a condition - The following values are considered False
- None
- False
- zero of any numeric type, e.g., 0, 0.0, 0j.
- any empty sequence or dictionary, e.g., '', (), [], {}
- All other values are considered True
While Loop
- The while loop continues to execute the same
body of code until the conditional statement is
no longer True - We can use break and continue inside the loops
i = 0
while i < 10:
print(i)
i += 1
For Loop
- The for loop in Python is much simpler that other
C-like languages
- We can use range() function to produce a list of
numbers
for x in ['Ali', 'Mahsa', 'Navid', 'Zahra']:
print('Hello ' + x + '!')
for i in range(10):
print(i)
Title Text
Python 101
By Behnam Hatami
Python 101
python / Web Programming Course @ SUT, Fall 2018
- 1,487