Introduction to Programming
with Python(202-1-9041)
Lecture 1: Introduction to Python
1
2
Welcome to
”Introduction to programming with python”
course !
• We will learn to program in Python.
• Goal: enable you to use programming as a tool to solve
“real world” problems.
• Work is required!
3
Course Staff
Lectures
Zion Sicsic [email protected]
Alon 37, Room 520
Office hours: Monday 16:00-17:30
Recitations:
Hanan Zaichyk [email protected]
Alon 37, Room 226
Office hours: Tuesday 14:00-16:00
4
Administration
Website:
https://www.cs.bgu.ac.il/~ipp201
What’s there:
• Lectures
• Recitations
• Homework guidelines
• Assignments
• Code examples
• Announcements
5
A Personal Note on HW
It will take you time and
effort to make the code
work.
But
There is no other way to
learn how to program
6
Exam
• Final grade is composed out of homework (30%) and
final exam (70%)
• You must pass the exam to pass the course
• Written exam
• Includes all course material:
• Lectures, recitations, and HW
7
Course Objectives
Develop basic programming and algorithmic skills
Remember: we learn programming, not how computer hardware works !
8
Syllabus
• Python programming basics
• Lists, dictionaries and other data types
• Functions
• Sort & Search algorithms
• Exceptions
• Recursion
• Object-Oriented Programming
• Scientific Calculations using NumPy , SciPy & Matplotlib
• Modules
• Introduction to computational complexity
• Data Analysis
• Image Processing
9
Resources
• Course slides and pointers to relevant bibliography.
• Recommended resources:
• Book: Think Python, by Allen B. Downey
http://greenteapress.com/thinkpython/thinkpython.html
• Manual: Python 3.6 documentation
http://docs.python.org/3.6 (the official language
manual)
10
Preface
• We assume no prior knowledge.
• However, we advance fast.
• The only way to keep on track is to practice!
11
Today
• Brief background
• Python basics:
• Variables
• Numbers
• Strings
12
Computers understand only machine language.
Basically looks like a sequence of 1’s and 0’s.
Very inconvenient to work with and non-intuitive.
All other computer languages were created for human
convenience.
The computer does not understand C/Python/Java,
it must be “translated” into machine language
In this course, we do not care how the computer does that
Machine Code (Language)
13
Programming Languages Basics
• A computer program is a sequence of text instructions
that can be “understood” by a computer and executed.
• A programming language is a machine-readable
artificial language designed to express computations
that can be performed by a computer.
Over 500 different computer languages
are listed by Wikipedia
Computer Program
• A sequence of instructions designed to achieve a
specific purpose
• The instructions are executed sequentially. No instruction is executed before the previous is completed
14
Running Programs
• The transformation from high level to machine level
languages comes in two flavors:
– Interpreters,
– Compilers.
• The interpreter is a machine level program, which
interprets and executes the high level program, line
by line.
• The Compiler translates the complete high level
program to a machine level program
15
16
Compiler
(C, C++)
17
Interpreter
(Python, Matlab)
a Word on Writing Code
• Getting a program to work as planned is an
interesting process
• It can be not just interesting, but frustrating as well.
• Planning what your program should do, and how it is
going to do it, is crucial.
• It is very tempting to skip such planning and go
straight to writing lines of code.
• We strongly advise you not to skip the planning stage
• Take care: the simple but worst method is “trial and error”
18
19
Language Selection and Python
Python (since 1991):
• Quick development
• Easy to learn
• Huge community
• Short development-execution rounds
• Fast enough for most applications
• Cross-platform
Guido van Rossum
20
Python is Good for Your Future..
Python is widely used in industry (Google, Yahoo!,
YouTube, BitTorrent, Intel, IDF, NASA)
Take a look at Python's community conference
• Short development-execution rounds
• Huge community
• Fast enough for most applications
• Cross-platform
21
Programming Environment
22
Using Anaconda
• run idle.exe to open the Idle terminal.
• The executable file is located in
INSTALL_DIR\Anaconda\Scripts, INSTALL_DIR stands for
the installation directory, usually C:\ or C:\Program Files
• It is recommended to create a shortcut on your desktop.
This is how idle shell looks like:
• A video on working with IDLE:
http://www.youtube.com/watch?v=lBkcDFRA958
My First Python Program:
Hello World!
23
Hello World
• The first line of code taught in all programming
languages is a print
• The text to the right of the prompt is the command to
the Python interpreter.
• The text in the next line is the value returned by the
interpreter
• print is a built-in Python function (colored purple by
the interpreter).
• We will later see that Python has a collection of
reserved words
24
Read, eval, print
• An interaction with the interpreter has 3 steps:
• Read: the interpreter reads the sequence of characters
we type following the prompt
• Eval: the interpreter evaluates (computes) the code
that was read, and produces a result (and perhaps
additional effect)
• Print: the interpreter prints the result as a sequence of
characters, then prints the prompt for the next
interaction
25
Memory
• The computer memory is composed of a long list of
bits (0 and 1)
• Bits are grouped into bytes (8 bits) and words (4
bytes, 8 on 64-bit systems)
• Every byte is numbered sequentially
• This number is called an address
26
What are Variables ?A location in the computer’s memory
A variable:
- has a name
- holds a value
- has type – according to its value
- The variable's name is a sequence of letters and
digits, starting with a letter.
This is how data is handled
27
Why do We Need Variables?
• Computer programs manipulate data
• Data is given as input or calculated throughout the program
• To access them later, variables must be remembered
• Thus, variables are stored in the memory
• Variable name memory address
28
Why Do We Need Different Types?
• Saving memory
• Execution speed
29
Trueb
Variables and Assignments
>>> n = 10
>>> m = (10 + 4) * 5
The left-hand side is a variable.
The right-hand side is an expression.
The interpreter:
1. evaluates the expression
2. assigns its value to the variable.
10 70
n m
31
Hands On
Numbers and their Types
>>> 4
4
>>> type(4)
<class 'int'> # integers type
>>> 3.14159
3.14159
>>> type(3.14159)
<class 'float'> # floating point ("reals") type
What type is 8/5 ? , 8/5.0 ? 8//5? Let’s check…
Variables Assignments:
Changing the value of a variable:
>>> n = 11
>>> n
11
Changing the type of a variable:
>>> n = 1.3141
>>> n
1.3141
Variables can be used in expressions:
>>>2*n+1
Variables and Assignments – Cont.
Referring to undefined variables leads to runtime error
>>> check_this
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
check_this
NameError: name 'check_this' is not defined
35
Arithmetic Operators
Operator Use Description
+ x + y Adds x to y
- x - y Subtracts x from y
* x * y Multiplies x by y
** x ** y X to the power y
/ x / y Divides x by y
// x / / y Floor divides x by y (rounded to the next smallest whole
number)
% x % y Computes the remainder of dividing x by y
36
Playing with Variables
>>> a = 3
>>> a
3
>>> b = 5
>>> b
5
>>> c = a + b
>>> c
8
>>> c = c * 2
>>> c
16
>>> b**a
125
>>> first = (a + b) * 2
>>> second = a + b * 2
>>> first, second
(16, 13)
>>> b / a
1.66666666666667
>>> b % a
2
Strings
• Strings are text sequences.
• An ordered list of characters
“Hello world”
37
38
String Type
Immutable
Strings Access
39
>>> a=‘Hello’
>>> a[1:3]
'el'
>>> a[1:]
'ello'
>>> a[-4:-2]
'el'
>>> a[:-3]
'He'
>>> a[-3:]
'llo’
H e l l o
0 1 2 3 4 5
-5 -4 -3 -2 -1
40
Strings concatenation
>>> s1 = "He"
>>> s2 = "llo"
>>> s3 = s1 + s2
>>> s3
'Hello'
>>> s4 = s3 + " World"
>>> c = "!"
>>> print(s4, 2020, c)
Hello World 2020 !
41
Strings Structure
42
Strings are Immutable>>> a = "abc"
>>> a[0]='a'
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
a[0]='a'
TypeError: 'str' object does not support item assignment
However, pointing to another string is valid:
>>> a = "abc"
>>> a = “ggg"
Immutable variables cannot be changed after created.
Applying operations on immutable variables usually return
a new variable rather changing the original variable
43
Strings Built In Methodshttps://docs.python.org/release/3.5.4/library/string.html
44
Strings Built In Methodshttp://www.tutorialspoint.com/python/python_strings.htm
• Escape characters: \n (new line) \t (tab)
• Special string operators:Operator Description Example
+ Concatenation - Adds values on either side of the
operator
a + b will give
HelloPython
* Repetition - Creates new strings, concatenating
multiple copies of the same string
a*2 will give HelloHello
][ Slice - Gives the character from the given index a[1] will give e
] : [ Range Slice - Gives the characters from the given
range
a[1:4] will give ell
in Membership - Returns true if a character exists in
the given string
H in a will give 1
not in Membership - Returns true if a character does not
exist in the given string
M not in a will give 1
% Format - Performs String formatting See at next section
45
Strings Built In Methodshttp://www.tutorialspoint.com/python/python_strings.htm
• String Formatting Operator
print("My name is %s and my weight is %d kg "!% ('Zara', 12))My name is Zara and my weight is 12 kg!
• Useful String methods:– len
– find, startswith, endswith
– isalpha, isdigit, islower,…
– join, replace
– strip, rstrip
– split