Unit - 1
Introduction & Components of Python
By Prof. Yogesh Jorwekar
M.E. (Computer)
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Compilers and Interpreters
• Programs written in high-level
languages must be translated into
machine language to be executed
• Compiler: translates high-level
language program into separate
machine language program
– Machine language program can be executed
at any time
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Compilers and Interpreters
(cont’d.)
• Interpreter: translates and executes
instructions in high-level language
program
– Used by Python language
– Interprets one instruction at a time
– No separate machine language program
• Source code: statements written by
programmer
– Syntax error: prevents code from being translated
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Compilers and Interpreters
(cont’d.)
Executing a high-level program with an interpreter
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Compiling and interpreting
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
[Link] [Link]
Python is instead directly interpreted into machine instructions.
interpret
source code output
[Link]
5
Using Python
• Python must be installed and
configured prior to use
– One of the items installed is the Python
interpreter
• Python interpreter can be used in two
modes:
– Interactive mode: enter statements on
keyboard
– Script mode: save statements in Python script
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Interactive Mode
• When you start Python in interactive
mode, you will see a prompt
– Indicates the interpreter is waiting for a
Python statement to be typed
– Prompt reappears after previous statement is
executed
– Error message displayed If you incorrectly
type a statement
• Good way to learn new parts of Python
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Writing Python Programs and
Running Them in Script Mode
• Statements entered in interactive mode
are not saved as a program
• To have a program use script mode
– Save a set of Python statements in a file
– The filename should have the .py extension
– To run the file, or script, type
python filename
at the operating system command line
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Python Scripts
• When you call a python program from the
command line the interpreter evaluates each
expression in the file
• Familiar mechanisms are used to provide
command line arguments and/or redirect input
and output
• Python also has mechanisms to allow a python
program to act both as a script and as a module
to be imported and used by another python
program
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The IDLE Programming
Environment
• IDLE (Integrated Development Learning
Environment): single program that
provides tools to write, execute and
test a program
– Automatically installed when Python language
is installed
– Runs in interactive mode
– Has built-in text editor with features designed
to help write Python programs
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
IDLE Development Environment
• IDLE is an Integrated DeveLopment Environ-ment
for Python, typically used on Windows
• Multi-window text editor with syntax highlighting,
auto-completion, smart indent and other.
• Python shell with syntax highlighting.
• Integrated debugger
with stepping, persis-
tent breakpoints,
and call stack visi-
bility
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Programming basics
code or source code: The sequence of instructions in a program.
syntax: The set of legal structures and commands that can be used
in a particular programming language.
output: The messages printed to the user by a program.
console: The text box onto which output is printed.
Some source code editors pop up the console as an external window,
and others contain their own console window.
12
The Basics
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = ‘Hello’ # Another one.
z = 3.45
if z == 3.45 or y == ‘Hello’:
x=x+1
y = y + ‘ World’ # String concat.
print (x)
print (y)
Enough to Understand the Code
Indentation matters to code meaning
Block structure indicated by indentation
First assignment to a variable creates it
Variable types don’t need to be declared.
Python figures out the variable types on its own.
Assignment is = and comparison is ==
For numbers + - * / % are as expected
Special use of + for string concatenation and % for
string formatting (as in C’s printf)
Logical operators are words (and, or, not)
not symbols
The basic printing command is print
Basic Datatypes
Integers (default for numbers)
z = 5 // 2 # Answer 2, integer division
Floats
x = 3.456
Strings
Can use “” or ‘’ to specify with “abc” == ‘abc’
Unmatched can occur within the string: “matt’s”
Use triple double-quotes for multi-line strings or
strings than contain both ‘ and “ inside of them:
“““a‘b“c”””
Whitespace
Whitespace is meaningful in Python:
especially indentation and placement of
newlines
Use a newline to end a line of code
Use \ when must go to next line prematurely
No braces {} to mark blocks of code, use
consistent indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
Colons start of a new block in many
constructs, e.g. function definitions, then
clauses
Comments
Start comments with #, rest of line is ignored
Can include a “documentation string” as the
first line of a new function or class you define
Development environments, debugger, and
other tools use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive integer
and returns facorial of n.”””
assert(n>0)
if n==1 return 1 else n*fact(n-1)
Assignment
Binding a variable in Python means setting a name to
hold a reference to some object
Assignment creates references, not copies
Names in Python do not have an intrinsic type, objects
have types
Python determines the type of the reference automatically
based on what data is assigned to it
You create a name the first time it appears on the left
side of an assignment expression:
x=3
A reference is deleted via garbage collection after any
names bound to it have passed out of scope
Python uses reference semantics (more later)
Assignment
You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
This makes it easy to swap values
>>> x, y = y, x
Assignments can be chained
>>> a = b = x = 2
Naming Rules
Names are case sensitive and cannot start with
a number. They can contain letters, numbers,
and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
There are some reserved words:
and, assert, break, class, continue, def,
del, elif, else, except, exec, finally, for,
from, global, if, import, in, is, lambda,
not, or, pass, print, raise, return, try,
while
Naming conventions
The Python community has these recommend-
ed naming conventions
joined_lower for functions, methods and,
attributes
joined_lower or ALL_CAPS for constants
StudlyCaps for classes
camelCase only to conform to pre-existing
conventions
Attributes: interface, _internal, __private
Accessing Non-Existent Name
Accessing a name before it’s been
properly created (by placing it on the left
side of an assignment), raises an error
>>> y
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
Expressions
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
42
Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication,
division
% modulus, a.k.a. remainder
** exponentiation
precedence: Order in which operations are computed.
* / % ** have a higher precedence than + -
1 + 3 * 4 is 13
Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16
24
Boolean Operations — and, or, not Operation
x or y
x and y
not x
Comparisons
Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity
25
Numeric Types — int, float
Operation Result
x+y sum of x and y
x-y difference of x and y
x*y product of x and y
x/y quotient of x and y
x // y floored quotient of x and y
x%y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
float(x) x converted to floating point
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y
26
Math commands
Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
To use many of these commands, you must write the following at
the top of your Python program:
from math import *
27