Unit -2
Python Data,
Expressions and
Statements
Contents of This Unit
● Python interpreter and interactive mode
● Values and types
● Variables
● Expressions
● Statements
● Tuple assignment
● Precedence of operators
● Comments
● Modules and functions
● Function definition and use
● Flow of execution
● Parameters and arguments.
Python
Introduction
Python is a general-purpose interpreted, Python is actually a compiled + interpreted
interactive, object-oriented, and high-level language but compilation process
programming language. It was created by happens implicitly in background it is
Guido van Rossum during 1985- 1990. completely hidden from programmer. It
is just a step which happens and gets
Why python?? deleted.
Python is designed to be highly readable. It
uses English keywords frequently where as
other languages use punctuation, and it has Extension of that compiled python file
fewer syntactical constructions than other is .pyc.
languages.
Why is python so
popular?
Python has huge collection of inbuilt packages
and modules. And huge collection of
packages and modules, you have to
download and installed it in your system.
Python is Interpreted − Python is processed
at runtime by the interpreter. You do not
need to compile your program before
executing it. This is similar to PERL and
PHP.
Python is Interactive − You can actually sit
at a Python prompt and interact with the
interpreter directly to write your programs.
v a n t ag Python is Object-Oriented − Python
Ad supports Object-Oriented style or
es
technique of programming that
encapsulates code within objects.
Python is a Beginner's Language − Python
is a great language for the beginner-level
programmers and supports the
development of a wide range of
applications from simple text processing
to WWW browsers to games.
Characteristics of Python
• It supports functional and structured programming methods as well
as OOP.
• It can be used as a scripting language or can be compiled to byte-
code for building large applications.
• It provides very high-level dynamic data types and supports
dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, ActiveX, CORBA, and Java.
Applications of Python
● Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
● Easy-to-maintain − Python's source code is fairly easy-to-maintain.
● A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
● Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
● Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
● Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
● Databases − Python provides interfaces to all major commercial databases.
● GUI Programming − Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
● Scalable − Python provides a better structure and support for large programs than shell
scripting.
Python interpreter Interpreter
and interactive
mode
Compiler
Translates and executes
instructions in high-level language
program
•Programs written in high-level
languages must be translated into –Used by Python language
machine language to be executed –Interprets one instruction at a time
Compiler : Translates high-level language No separate machine language
program into separate machine language program
program
Source code: statements written
–Machine language program can be executed at by programmer
any time.
–Syntax error: prevents code from
being translated
Compilers and Interpreters
It’s the biggest planet in
the Solar System and the
fourth-brightest object in
the sky
Satur
n
Mars is a cold place. It’s Yes, this is the ringed
full of iron oxide dust, one. It’s a gas giant,
which gives the planet its composed mostly of
reddish cast hydrogen and helium
Many languages require you to compile (translate) your program into a form that the machine understands.
Python is instead directly interpreted into machine instructions.
Using
python
Interactive
&
Script
Mode
•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
•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
Writing Python Programs
and Running Them in
Script Mode Python Scripts
Statements entered in interactive mode are
not saved as a program •When you call a python program from the
•To have a program use script mode command line the interpreter evaluates
each expression in the file
–Save a set of Python statements in a file
•Familiar mechanisms are used to provide
–The filename should have the .py extension
command line arguments and/or redirect
–To run the file, or script, type input and output
python filename •Python also has mechanisms to allow a
at the operating system command python program to act both as a script and
line as a module to be imported and used by
another python program
The IDLE Programming Environment
IDLE (Integrated Development Learning Environment): single program that provides tools
to write, execute and test a program
Automatically installed Built-in text editor with
when Python language features designed to
is installed help write Python
programs
Runs in interactive Integrated debugger with stepping,
mode persistent breakpoints,and call
stack visibility
IDLE is an Integrated DeveLopment
Environment for Python, typically used on Python shell with syntax
Windows highlighting.
Multi-window text editor with syntax
highlighting, auto-completion, smart
indent and other.
Programming
basics
Programming basics
code or source code: The sequence of instructions in a
program.
n
syntax: The set of legal structures and commands that can be
used in a particular programming language.
n
output: The messages printed to the user by a program.
n
console: The text box onto which output is printed.
n Some source code editors pop up the console as an external window, and others contain their own console window.
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)
… 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 Data Type
● 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”””
Data Type
Variables can hold values, and every value has a data-type.
Python is a dynamically typed language; hence we do not need to define the type of the variable
while declaring it.
The interpreter implicitly binds the value with its type.
Eg: a = 5
The variable a holds integer value five and we did not define its type.
Python interpreter will automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program.
Python provides us the type() function, which returns the type of the variable passed.
Types:
Numbers: it is divided into three parts: --->>> int, float, complex
Sequence Type: it is divided into three parts: ---->> list, tuple, str
Boolean: bool [it has only two value True, False]
Set
Dictionary
Variables
Think of a variable as a name attached to a particular object.
In Python, variables need not be declared or defined in advance,
as is the case in many other programming languages.
To create a variable, you just assign it a value and then start using it.
Assignment is done with a single equals sign (=).
At the time of declaration of variable we do not specify its data type. It does not
mean that it does not have it.
name='Amit' #in python single and double both quotes can be used.
salary=120000
here if we print
print(type(name)) # <class str> here str is data type
print(type(salary)) # <class int>here int is data type
Here name and salary are variables;
Variables
Python also allows chained assignment, which makes it possible to assign
the same value to several variables simultaneously:
a=b=c=200;
Here a,b,c variables have same value which is 200.
--> Variables are case sensitive means a and A are different.
Some basic rules while declaring variables:
--> never start variable with digit or any special character except _(underscore)
Some valid variables:
--> a, a_b, num1, num1_num2, _num1
Invalid:
--> 12a, a&b, a b
Expressions
● 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
N ** exponentiation
n
● 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
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
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 Quantity of X and Y
X//y Floored quantity of X and Y
X%y Remainder of X and 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
Statements
A statement is an instruction that the Python interpreter can execute. We have seen two kinds of statements: print and
assignment.
When you type a statement on the command line, Python executes it and displays the result, if there is one. The result of a
print statement is a value. Assignment statements don't produce a result.
A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as
the statements execute.
For example, the script
print 1
x=2
print x
produces the output
Again, the assignment statement produces no output.
Statement
Example :
Declared using Continuation
Character (\):
Instructions written in the source code for execution s = 1 + 2 + 3 + \
4 + 5 + 6 + \
are called statements. There are different types of
7 + 8 + 9
statements in the Python programming language like
Assignment statements, Conditional statements, Declared using parentheses
Looping statements, etc. These all help the user to () :
get the required output. For example, n = 50 is an n = (1 * 2 * 3 + 7 + 8 + 9)
assignment statement.
Declared using square brackets
[] :
footballer = ['MESSI',
'NEYMAR',
Multi-Line Statements: Statements in Python can 'SUAREZ']
be extended to one or more lines using parentheses
Declared using braces {} :
(), braces {}, square brackets [], semi-colon (;),
x = {1 + 2 + 3 + 4 + 5 + 6 +
continuation character slash (\). When the 7 + 8 + 9}
programmer needs to do long calculations and
cannot fit his statements into one line, one can make Declared using semicolons(;) :
use of these characters. flag = 2; ropes = 3; pole
= 4
Tuple
Assignment
Tuples are basically a data type in python. The process of assigning values to a tuple is
These tuples are an ordered collection of known as packing. While on the other hand, the
elements of different data types. Furthermore, unpacking or tuple assignment is the process
we represent them by writing the elements that assigns the values on the right-hand side to
inside the parenthesis separated by commas. the left-hand side variables. In unpacking, we
We can also define tuples as lists that we basically extract the values of the tuple into a
cannot change. Therefore, we can call them single variable.
immutable tuples. Moreover, we access
elements by using the index starting from
zero. We can create a tuple in various ways.
Moreover, while performing tuple assignment
we should keep in mind that the number o
variables on the left-hand side and the number o
In python, we can perform tuple assignment
values on the right-hand side should be equal. O
which is a quite useful feature. We can initialise
in other words, the number of variables on the
or create a tuple in various ways. Besides tuple
left-hand side and the number of elements in the
assignment is a special feature in python. We
tuple should be equal. Let us look at a few
also call this feature unpacking of tuple.
examples of packing and unpacking.
Example
Example 1: Tuple with integers as elements
>>> x= (1,2,3)
>>> x
>>>tup = (22, 33, 5, 23)
(1,2,3)
>>> x,y,z= (1,2,3)
>>>tup
>>> x
1
>>> y (22, 33, 5, 23)
2 Example 2: Tuple with mixed data type
>>> z
3 >>>tup2 = ('hi', 11, 45.7)
>>>tup2
uple Packing (Creating Tuples)
('hi', 11, 45.7)
We can create a tuple in various ways by using Example 3: Tuple with a tuple as an element
>>>tup3 = (55, (6, 'hi'),67)
ifferent types of elements. Since a tuple can
ontain all elements of the same data type as >>>tup3
ell as of mixed data types as well. Therefore,
(55, (6, 'hi'), 67)
e have multiple ways of creating tuples.
Example 1
Example 4: Tuple with a list as an element
>>>(n1, n2) = (99, 7)
>>>tup3 = (55, [6, 9], 67)
>>>print(n1)
>>>tup3
99
(55, [6, 9], 67) >>>print(n2)
7
Tuple Assignment (Unpacking) Example 2
>>> (num1, num2, num3, num4, num5) =
Unpacking or tuple assignment is the (88, 9.8, 6.8, 1)
process that assigns the values on the
right-hand side to the left-hand side #this gives an error as the variables on
variables. In unpacking, we basically the left are more than the number of
elements in the tuple
extract the values of the tuple into a
single variable. ValueError: not enough values to unpack
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)
● Python provide two types of comments:
1. single line comment #
2. Multiline comment ''' '''
● Comment : Modules and functions
Module
Module is nothing just a python file.
A module is a file containing Python definitions and statements.
A module can define functions, classes, and variables.
A module can also include runnable code. Grouping related code into a module makes the
code easier to understand and use. It also makes the code logically organized.
Suppose we create a file
**calculator.py <<-- it is a module
def prod(a,b):
return a*b
Now we can import above file as a module in other program
Other.py
import calculator
# we can access prod() now
prod(12,23)
Functions
Function is a group of statements to perform some task.
A function in python is declared by the keyword ‘def’ before the name of the function.
The return type of the function need not be specified explicitly in python.
The function can be invoked by writing the function name followed by the parameter list in
the brackets.
Function Definition:
def messg(): ##<<------- this is function definition
print('Python is very popular language')
messg() ##<<.------ calling of function
Function use:
1. Function can hold n number of statements. By using function we can write very clean
code.
2. Maintenance of function is easy, because all logic run in seperate function.
3. We can reuse our code.
Functions
There are three types of functions in Python:
● Built-in functions, such as help() to ask for help, min() to get
the minimum value, print() to print an object to the
terminal,…
● User-Defined Functions (UDFs), which are functions that
users create to help them out; And
● Anonymous functions, which are also called lambda
functions because they are not declared with the standard
def keyword.
Functions Method
A method refers to a function which is part of a class. You access it with an
instance or object of the class. A function doesn’t have this restriction: it just
refers to a standalone function. This means that all methods are functions, but
not all functions are methods.
Consider this example, where you first define a function plus() and then a
Summation class with a sum() method:
# Define a function `plus()`
def plus(a,b):
return a + b
# Create a `Summation` class
class Summation(object):
def sum(self, a, b):
self.contents = a + b
return self.contents
Functions Method
If you now want to call the sum() method that is part of the Summation class,
you first need to define an instance or object of that class. So, let’s define such
an object:
# Instantiate `Summation` class to call `sum()`
sumInstance = Summation()
sumInstance.sum(1,2)
This instantiation not necessary for when you want to call the function plus()!
You would be able to execute plus(1,2) in the DataCamp Light code chunk
without any problems!
Assigment
● 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)
● 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 Rule
● 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 recommended 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
Our Team
Helena
Patterson
You can replace the star
John Doe on the screen with a Ann Smith
picture of this person
You can replace the star You can replace the star
on the screen with a on the screen with a
picture of this person picture of this person
Thanks!
Do you have any questions?
[email protected]
+91 620 421 838
yourcompany.com
CREDITS: This presentation template was created by
Slidesgo, including icons by Flaticon, and infographics &
images by Freepik.
Please keep this slide for attribution.
Alternative Resources
Resources
Vector
● Hand drawn notebook with pencils and material
● Travel pattern with elements and dash lines
● Hand drawn arrow collection
● Assortment of arrows highlighter
● Cartoon math elements background
● Planning elements sample
● Collection of colored notes with adhesive tap
● Online learning background with variety of hand-drawn items
● Background of mobile phone with hand-drawn items
● Hand drawn timeline infographic template
● Hand drawn template timeline infographic
Photo
● Top view of graphic designer working with graphic tablet and laptop
● Flat lay of back to school concept with copy space
Instructions for use
In order to use this template, you must credit Slidesgo by keeping the Thanks slide.
You are allowed to:
- Modify this template.
- Use it for both personal and commercial projects.
You are not allowed to:
- Sublicense, sell or rent any of Slidesgo Content (or a modified version of Slidesgo Content).
- Distribute Slidesgo Content unless it has been expressly authorized by Slidesgo.
- Include Slidesgo Content in an online or offline database or file.
- Offer Slidesgo templates (or modified versions of Slidesgo templates) for download.
- Acquire the copyright of Slidesgo Content.
For more information about editing slides, please read our FAQs or visit Slidesgo School:
https://slidesgo.com/faqs and https://slidesgo.com/slidesgo-school
Fonts & colors used
This presentation has been made using the following fonts:
Itim
(https://fonts.google.com/specimen/Itim)
Muli
(https://fonts.google.com/specimen/Muli)
#1c4587 #b0d5f7ff #ffe599 #caffca #ffbbaa #eeeeee
Storyset
Create your Story with our illustrated concepts. Choose the style you like the most, edit its colors, pick
the background and layers you want to show and bring them to life with the animator panel! It will boost
your presentation. Check out How it Works.
Pana Amico Bro Rafiki Cuate
Use our editable graphic resources...
You can easily resize these resources without losing quality. To change the color, just ungroup the resource
and click on the object you want to change. Then, click on the paint bucket and select the color you want.
Group the resource again when you’re done. You can also look for more infographics on Slidesgo.
JANUARY FEBRUARY MARCH APRIL MAY JUNE
PHASE 1
Task 1
Task 2
PHASE 2
Task 1
Task 2
JANUARY FEBRUARY MARCH APRIL
PHASE
1
Task 1
Task 2
...and our sets of editable icons
You can resize these icons without losing quality.
You can change the stroke and fill color; just select the icon and click on the paint bucket/pen.
In Google Slides, you can also use Flaticon’s extension, allowing you to customize and add even more icons.
Educational Icons Medical Icons
Business Icons Teamwork Icons
Help & Support Icons Avatar Icons
Creative Process Icons Performing Arts Icons
Nature Icons
SEO & Marketing Icons