Python 01
Python 01
PYTHON LANGUAGE
Lecture 01:
Introduction to Python
Kai-Feng Chen
National Taiwan University
1
PYTHON:
AN INTRODUCTION
■ Quote from Wikipedia: “Python is a widely used general-purpose,
high-level programming language. Its design philosophy
emphasizes code readability, and its syntax allows programmers to
express concepts in fewer lines of code than would be possible in
languages such as C. The language provides constructs intended to
enable clear programs on both a small and large scale.”
■ The core philosophy (as called “The Zen of Python”):
▫ Beautiful is better than ugly.
▫ Explicit is better than implicit.
▫ Simple is better than complex. In short:
Must be simple and beautiful
▫ Complex is better than complicated.
▫ Readability counts.
2
PYTHON:
AN INTRODUCTION (II)
■ Python development was started in December 1989.
■ Python's principal author: Guido van Rossum.
■ The origin of the name comes from Monty Python (Monty
Python's Flying Circus, a British television comedy show),
not the elongated legless animal.
4
“HELLO WORLD” IN
C/C++
Well, the common starting point for any programming language.
#include <cstdio>
int main()
{
printf("hello world!\n");
} helloworld.cc
5
“HELLO WORLD” IN
PYTHON
print('hello world!')
helloworld.py
6
fi
THE COMPILER (& LINKER)
■ A compiler reads the source code and translates it before the
program starts running; the translated program is the object code
or the executable.
■ Once a program is compiled, it can be executed it repeatedly
without further translation.
8
PYTHON,
THE INTERPRETER
■ Python is considered an interpreted language because Python
programs are executed by an interpreter.
▫ Rapid turn around: no needs of compilation and linking as in C
or C++ for any modi cation.
▫ Hybrid Python programs are compiled automatically to an
intermediate form called bytecode, which the interpreter then
reads.
▫ This gives Python the development speed of an interpreter
without the performance loss in purely interpreted languages.
▫ However for serious speed limited computations you still need
to use C, or even Fortran.
9
fi
PYTHON,
THE INTERPRETER (II)
■ There are actually two ways to use the interpreter:
interactive mode and script mode.
■ Running your program in script mode:
▫ As we did in the previous “hello world” example: put your
code into a le, process it with the python interpreter.
▫ The Unix/Linux “#!” trick:
#!/usr/bin/env python
print('hello world!') helloworld.py
10
fi
fi
PLAY WITH PYTHON
INTERACTIVELY (I)
■ Let’s try some simple Python commands in the interactive mode:
% python
>>> 2+2
4
>>> # I’m a comment. I will not do anything here.
... 2+2 # anything after ‘#’ is a comment.
4
>>> 6/3
2.0
>>> (50-5*6)/4
5.0 Use the python interpreter as a calculator!
>>> 6/-3 The regular precedence is followed:
-2.0
>>> 2**8 ⇐ this is exponentiation (28) (,) ⇒ ** ⇒ *,/,// ⇒ % ⇒ +,-
256
>>> 10%3 ⇐ this is modulus
1
11
PLAY WITH PYTHON
INTERACTIVELY (II)
■ Float point number versus integer:
>>> 8/3
2.6666666666666665 ⇐ automatically convert to oat since python 3
>>> 8//3 ⇐ integer divide
2
>>> 9998//9999 ⇐ round to integer
0
>>> 8/3.
2.6666666666666665
>>> 8/(6.6/2.2)
2.666666666666667
>>> 8/3+1
3.6666666666666665
>>> round(3.1415927,3) ⇐ rounding off to 3rd digit
3.142
12
fl
PLAY WITH PYTHON
INTERACTIVELY (III)
■ You can assign a variable with “=”:
>>> width = 20
>>> height = 5*9
>>> area = width * height
>>> area
900
13
PLAY WITH PYTHON
INTERACTIVELY (IV)
■ Complex number is also supported. The imaginary part can be
written with a suf x “j”.
>>> a = 2j
>>> a*a
(-4+0j)
>>> b = complex(3,4) ⇐ Using the function complex(real, imag)
>>> a+b
(3+6j)
>>> 8j/3j
(2.6666666666666665+0j) ⇐ Complex numbers are always oat.
>>> b.real + b.imag ⇐ Exact the real/imaginary part
7.0 with .real and .imag
>>> abs(b) ⇐ absolute value
5.0
14
fi
fl
FIRST VISIT WITH
STRINGS
■ Python supports for strings are actually very powerful. See several
examples below:
>>> 'I am a string!'
'I am a string!'
>>> "me too!"
'me too!'
>>> 'anything quoted with two \' is a string.'
"anything quoted with two ' is a string."
>>> "\" also works."
'" also works.'
>>> "pyt" 'hon' ⇐ Two string literals next to each other
'python' are automatically concatenated
>>> sentence = 'I am a string variable.'
>>> sentence
'I am a string variable.'
15
FIRST VISIT WITH
STRINGS (II)
■ More: multiline strings
>>> lines = "line1\nline2\nline3"
>>> print lines
line1
line2
line3
>>> reply = '''I ⇐ Use ''' or """ to start/end multiline strings.
... also have
... 3 lines'''
>>> print reply
I
also have
3 lines
16
FIRST VISIT WITH
STRINGS (III)
■ More: operators “+”, “*”, and type conversions
>>> 'oh'+'my'+'god'
'ohmygod'
>>> 'It\'s s'+'o'*20+' delicious!!'
"It's soooooooooooooooooooo delicious!!"
>>> '1234'+'1234'
'12341234'
>>> int('1234')+int('1234')
2468
>>> float('1234')/100
12.34
>>> a = b = 2
>>> str(a)+' plus '+str(b)+' is '+str(a+b)
'2 plus 2 is 4'
We will talk more on python strings afterwards.
17
VALUES AND TYPES
19
TYPES & MORE (II)
■ Few more complicated (but very useful) types are also supported.
Will be discussed in a near future lecture.
>>> type(3<4)
<class 'bool'>
>>> type(open('tmpfile','w'))
<class '_io.TextIOWrapper'>
>>> type([1,2,3,4,['five',6.0]])
<class 'list'>
>>> type((1,2,'three',4))
<class 'tuple'>
>>> type({'name':'Chen','phone':33665153})
<class 'dict'>
>>> type({'a','b','c'})
<class 'set'>
20
VARIABLES
>>> pi = 3.1415926536
>>> last_message = 'what a beautiful day'
22
INTERMISSION
23
fi
A STEP TOWARD
PROGRAMMING
■ A program is a sequence of instructions that speci es how to
perform a mathematical/symbolic computation.
■ This is a simple example of mathematical computation:
s = t = 1.
for n in range(1,21):
t /= n ⇐ t /= n is equivalent to t = t/n
s += t
print ("1/0!+1/1!+1/2!+1/3!+...+1/20! =",s)
1/0!+1/1!+1/2!+1/3!+...+1/20! = 2.71828182846
24
fi
THE PRINT STATEMENT
■ As you already seen in the “hello world!” program, as well as the
previous example, the print statement simply present the output to
the screen (your terminal).
■ A couple of examples:
>>> print('show it now!')
show it now!
>>> print(1,2,(10+5j),-0.999,'STRING') ⇐ connect w/ comma
1 2 (10+5j) -0.999 STRING
>>> print(1,2,3,4,5)
1 2 3 4 5
>>> print(str(1)+str(2)+str(3)+str(4)+str(5))
12345
Remark: for python 2, the ‘print’ was not a function, you
can use something like print ‘hello world!’.
25
STRUCTURE OF
A PROGRAM
■ Input:
get data from the keyboard, a le, or some other device.
■ Output:
display data on the screen or send data to a le or other device.
■ Math:
perform basic mathematical operations like addition and
multiplication.
■ Conditional execution:
check for certain conditions and execute the appropriate code.
■ Repetition:
perform some action repeatedly, usually with some variation.
27
SYNTAX ERRORS
■ Syntax refers to the structure of a program and the rules about that
structure.
■ Python can only execute a program if the syntax is correct;
otherwise, the interpreter displays an error message.
■ An example:
>>> y = 1 + 4x
File "<stdin>", line 1
y = 1 + 4x
^
SyntaxError: invalid syntax You probably already see a
>>> couple of syntax errors in
your previous trials.
28
RUNTIME ERRORS
■ A runtime error does not appear until after the program has
started running.
■ These errors are also called exceptions because they usually
indicate that something exceptional (and bad) has happened.
■ The following “ZeroDivisionError” only occur when it runs.
>>> a = b = 2
>>> r = ((a + b)/(a - b))**0.5 * (a - b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
29
SEMANTIC ERRORS
30
fi
fi
SEMANTIC ERRORS
s = t = 1.
for n in range(1,21):
t /= n
s += t
print ("1/0!+1/1!+1/2!+1/3!+...+1/20! =",s)
1/0!+1/1!+1/2!+1/3!+...+1/20! = 1.0
2.71828182846
31
DEBUGGING
■ It is very dif cult to write a bug free program at the rst shot.
■ Programming and debugging can be the same thing.
Programming is the process of debugging a program until it does
exactly what you want.
■ Having a good programming/coding habit suf ciently helps.
■ Re-run a buggy program never helps!
32
fi
fi
fi
SOME COMMON ISSUES
■ As observed from previous lectures, there were some common
issues from the students…
■ Issue #1: How to use the interpreter mode –– starting the
interpreter mode you can just type “python” in your terminal or
in your command line window:
In the slides of this
lecture, this is always
shown in a blue box.
% python
>>> 2+2
4
>>>
33
SOME COMMON ISSUES
(CONT.)
■ In the interpreter mode, the python interpreter can be used as a
calculator, ie. if you type in any math operations it will show the
answer on the screen directly.
■ If you type in any variable, the value of the variable will be shown.
■ If you type in any function, the return value of the function will be
shown.
% python
>>> 2+2
4
>>> x = 123
>>> x ⇐ this is a variable
123
>>> type(x) ⇐ this is a function
<class 'int'>
34
SOME COMMON ISSUES
(CONT.)
■ Issue #2: How to use the script mode –– put your code into a le
(mostly named with .py, any text editor can be used!), and execute
in the terminal command “python xxx.py”.
■ if you use the Unix/Linux “#!” trick in your code, then you do not
need to type in “python xxx.py”, but just “xxx.py”, if you have
added the executable permission to the le.
⇐ the #! trick
35
fi
fi
SOME COMMON ISSUES
(CONT.)
■ In the script mode, you cannot do what we did in interpreter
mode. You cannot just type the math calculations, or variables, or
functions to show the output. You have to use the “print” at least.
36
SOME COMMON ISSUES
(CONT.)
■ Issue #3: But I’m using an IDE from Anaconda … if this is the
case, you have both “modes” available in a single screen:
script mode
37
SOME COMMON ISSUES
(CONT.)
■ Issue #4: Why I double-clicked my xxx.py, it just shows
something quickly and disappeared quickly? –– You are likely
using a windows system. The default action when a .py le is
double-clicked will be just “run it”. Since your program runs very
fast, your program terminate and the command line window also
closed right away, so you cannot see the output.
- Solution #1: start a command line window by yourself and run
the program by typing the commands.
- Solution #2: always use your IDE to load your .py code and run.
- Solution #3: add the following two lines to the end of your code:
import msvcrt
msvcrt.getch() ⇐ this will wait for a key (Windows only!).
38
fi