0% found this document useful (0 votes)
61 views

Lesson 1 Basic Concepts

Python is an interpreted, interactive, object-oriented programming language. This document discusses Python fundamentals like interpreters, compilers, keywords, literals, data types, functions, and numeral systems. It also provides examples of basic Python concepts like comments, print statements, and input functions. Finally, it outlines some key applications of Python like GUI programming, databases, and its scalability.

Uploaded by

CHOI Hunter
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Lesson 1 Basic Concepts

Python is an interpreted, interactive, object-oriented programming language. This document discusses Python fundamentals like interpreters, compilers, keywords, literals, data types, functions, and numeral systems. It also provides examples of basic Python concepts like comments, print statements, and input functions. Finally, it outlines some key applications of Python like GUI programming, databases, and its scalability.

Uploaded by

CHOI Hunter
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 110

Python Programming

Lesson 1: Basic Concepts


Topics
• Python Fundamental concepts
• Interpreter
• Compiler
• Language elements, lexis, syntax and semantics
• Python keywords, Instructions and indenting
• Literals
• Boolean, integer, floating-point numbers, scientific notation and strings
• comments
• the print() function
• the input() function
• numeral systems (binary, octal, decimal, hexadecimal)
• numeric operators: ** * / % // + –
• string operators: * +
• assignments and shortcut operators
Python Fundamental Concept
Python Programming
Introduction
• Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
• It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source
code is also available under the GNU General Public License (GPL).
• Python is named after a TV Show called ëMonty Pythonís Flying Circusí and not
after Python-the snake.
• Python 3.0 was released in 2008.
• Although this version is supposed to be backward incompatibles, later on many of
its important features have been backported to be compatible with version 2.7.
Python Programming
What is Python Programming Language?
• Python is a high-level, interpreted, interactive and object-oriented scripting
language.
• Python is designed to be highly readable.
• It uses English keywords frequently where as other languages use punctuation,
and it has fewer syntactical constructions than other languages.
Python Programming
Key Advantages of Python Programming Language
• 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.
• Python is Object-Oriented − Python supports Object-Oriented style or 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.
Python Programming
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++, COM, ActiveX, CORBA, and Java.
Python Programming
Hands-On 1: Hello, World!
Python Programming
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-read − Python code is more clearly defined and visible to the eyes.
• 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.
Python Programming
Applications of Python
• 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 Programming
What is a New in Python 3
• The __future__ module
• Python 3.x introduced some Python 2-incompatible keywords and features that can be
imported via the in-built __future__ module in Python 2.
• It is recommended to use __future__ imports, if you are planning Python 3.x support for
your code.

For example, if we want Python 3.x's integer division behavior in Python 2,


add the following import statement.
from __future__ import division
Python Programming
What is a New in Python 3
• The print Function
• Most notable and most widely known change in Python 3 is how the print function is used.
Use of parenthesis () with print function is now mandatory. It was optional in Python 2.

print "Hello World" #is acceptable in Python 2


print ("Hello World") # in Python 3, print must be followed by ()
• The print() function inserts a new line at the end, by default. In Python 2, it can be
suppressed by putting ',' at the end. In Python 3, "end =' '" appends space instead of
newline.

print x, # Trailing comma suppresses newline in Python 2


print(x, end=" ") # Appends a space instead of a newline in Python 3
Python Programming
What is a New in Python 3
• Reading Input from Keyboard
• Python 2 has two versions of input functions, input() and raw_input(). The input() function
treats the received data as string if it is included in quotes '' or "", otherwise the data is
treated as number.

>>> x = input('something:’)
>>> x = raw_input("something:“)
something:10 #entered data is treated as number
>>> x something:10 #entered data is treated as string even without ‘’
>>> x
10
'10'
>>> x = input('something:’)
>>> x = raw_input("something:“)
something:'10' #entered data is treated as string something:'10' #entered data treated as string including ‘’
>>> x
>>> x
'10’
"'10'"
Python Programming
What is a New in Python 3
• Reading Input from Keyboard
• In Python 3, raw_input() function is deprecated. Further, the received data is always
treated as string.

>>> x = input("something:")
something:10
>>> x >>> x = raw_input("something:") # will result NameError
'10’ Traceback (most recent call last):
File "<pyshell#3>", line 1, in
>>> x = input("something:") <module>
something:'10' #entered data treated as string with x = raw_input("something:")
or without ‘’ NameError: name 'raw_input' is not defined
>>> x
"'10'"
Python Programming
What is a New in Python 3
• Integer Division
• In Python 2, the result of division of two integers is rounded to the nearest integer. As a
result, 3/2 will show 1.
• In order to obtain a floating-point division, numerator or denominator must be explicitly
used as float. Hence, either 3.0/2 or 3/2.0 or 3.0/2.0 will result in 1.5
• Python 3 evaluates 3 / 2 as 1.5 by default, which is more intuitive for new programmers.
• Unicode Representation
• Python 2 requires you to mark a string with a u if you want to store it as Unicode.
• Python 3 stores strings as Unicode, by default. We have Unicode (utf-8) strings, and 2 byte
classes: byte and byte arrays.
Python Programming
What is a New in Python 3
• xrange() Function Removed
• In Python 2 range() returns a list, and xrange() returns an object that will only generate the
items in the range when needed, saving memory.
• In Python 3, the range() function is removed, and xrange() has been renamed as range().
In addition, the range() object supports slicing in Python 3.2 and later.
• raise exception
• Python 2 accepts both notations, the 'old' and the 'new' syntax; Python 3 raises a
SyntaxError if we do not enclose the exception argument in parenthesis.

raise IOError, "file error" #This is accepted in Python 2


raise IOError("file error") #This is also accepted in Python 2
raise IOError, "file error" #syntax error is raised in Python 3
raise IOError("file error") #this is the recommended syntax in Python 3
Python Programming
What is a New in Python 3
• Arguments in Exceptions
• In Python 3, arguments to exception should be declared with 'as' keyword.

except MyError, err : # In Python 2


except MyError as err: # In Python 3

• next() Function and .next() Method


• In Python 2, next() as a method of generator object, is allowed. In Python 2, the next()
function, to iterate over generator object, is also accepted.
• In Python 3, however, next(0 as a generator method is discontinued and
raises AttributeError.

gen = (letter for letter in 'Hello World') # creates generator object


next(my_generator) #allowed in Python 2 and Python 3
my_generator.next() #allowed in Python 2. raises AttributeError in Python 3
Python Programming
What is a New in Python 3
• 2to3 Utility
• Along with Python 3 interpreter, 2to3.py script is usually installed in tools/scripts folder. It
reads Python 2.x source code and applies a series of fixers to transform it into a valid
Python 3.x code.

Here is a sample Python 2 code (area.py): To convert into Python 3 version:

def area(x,y = 3.14): $2to3 -w area.py


a = y*x*x
print a Converted code :
return a
def area(x,y = 3.14): # formal parameters
a = area(10) a = y*x*x
print "area",a print (a)
return a

a = area(10)
print("area",a)
Interpreter vs Compiler
Python Programming
Interpreter vs Compiler

Interpreter Compiler
Translates program one statement at a time. Scans the entire program and translates it as a
whole into machine code.
It takes less amount of time to analyze the source It takes a large amount of time to analyze the
code but the overall execution time is slower. source code but the overall execution time is
comparatively faster.
No intermediate object code is generated, hence Generates intermediate object code which further
are memory efficient. requires linking, hence requires more memory.
Continues translating the program until the first It generates the error message only after scanning
error is met, in which case it stops. Hence the whole program. Hence debugging is
debugging is easy. comparatively hard.
Programming languages like Python, Ruby use Programming languages like C, C++, Java use
interpreters. compilers.
Programming Language Elements
Python Programming
Programming Language
• A programming language is a set of commands, instructions, and other syntax use to
create a software program.
• Programming Language elements:
• Lexis
• A lexis or lexicon is the complete set of all possible words in a language or its vocabulary.

• Syntax
• Refers to the spelling and grammar of a programming language or the structure of the program.

• Semantics
• Describes the relation between the sense of the program and the computational model or the processes a
computer follows when executing a program.
Basic Syntax
Python Programming
Python Identifiers
• A Python identifier is a name used to identify a variable, function, class, module or other
object.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters such as @, $, and % within identifiers.
• Python is a case sensitive programming language. Thus, Firstname and firstname are two
different identifiers in Python.
Python Programming
Python Naming Convention
• Class names start with an uppercase letter.
• All other identifiers start with a lowercase letter.
• Starting an identifier with a single leading underscore indicates that the identifier is private.
• Starting an identifier with two leading underscores indicates a strong private identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-defined
special name.
Python Programming
Python Reserve Keywords
and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda Yield
except
Python Programming
Lines and Indentation
• Python does not use braces({}) to indicate blocks of code for class and function definitions
or flow control.
• Blocks of code are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.
• All the continuous lines indented with the same number of spaces would form a block.
Python Programming
Multiple-Line Statements
• Statements in Python typically end with a new line.
• Python, however, allows the use of the line continuation character (\) to denote that the
line should continue.
Python Programming
Multiple-Line Statements
• The statements contained within the [], {}, or () brackets do not need to use the line
continuation character.
Python Programming
Quotation in Python
• Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends the string.
• The triple quotes are used to span the string across multiple lines.
Python Programming
Comments in Python
• A hash sign (#) that is not inside a string literal is the beginning of a comment.
• All characters after the #, up to the end of the physical line, are part of the comment and
the Python interpreter ignores them.
Python Programming
Comments in Python
• You can comment multiple lines as follows:
Python Programming
Comments in Python
• Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comments:
Python Programming
Using Blank Lines
• A line containing only whitespace, possibly with a comment, is known as a blank line and
Python totally ignores it.
• In an interactive interpreter session, you must enter an empty physical line to terminate a
multiline statement.
Python Programming
Waiting for the Users
• The following line of the program displays the prompt and, the statement saying “Press the
enter key to exit”, and then waits for the user to take action
Python Programming
Multiple Statement on a Single Line
• The semicolon ( ; ) allows multiple statements on a single line given that no statement
starts a new code block
Python Programming
Multiple Statement Group as Suites
• Groups of individual statements, which make a single code block are called suites in
Python.
• Compound or complex statements, such as if, while, def, and class require a header line and
a suite.
• Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and
are followed by one or more lines which make up the suite.
Variables, Constants and Literals
Python Programming
Variables
• A variable is a named location used to store data in the memory.
• Unlike other programming languages, Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
• Variables do not need to be declared with any particular type and can even change type
after they have been set.
• String variables can be declared either by using single or double quotes
• The equal sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable.
Python Programming
Variables Example
Python Programming
Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously.
Python Programming
Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously.
Python Programming
Constants
• A constant is a type of variable whose value cannot be changed.
• It is helpful to think of constants as containers that hold information which cannot be
changed later.
Python Programming
Assigning a Value to Constant
• In Python, constants are usually declared and assigned in a module.
• Here, the module is a new file containing variables, functions, etc. which is imported to the
main file.
• Inside the module, constants are written in all capital letters and underscores separating
the words.
Python Programming
Literals
• Literal is a raw data given in a variable or constant.
• In Python, there are various types of literals they are as follows:
• Numeric Literals
• String Literals
• Boolean Literals
• Special Literals
Python Programming
Numeric Literals
• Numeric Literals are immutable (unchangeable). 
• Numeric Literals can belong to three (3) different numerical types: Integer, Float, and
Complex.
Python Programming
String Literals
• A string literal is a sequence of characters surrounded by quotes.
• We can use both single, double, or triple quotes for a string.
• And, a character literal is a single character surrounded by single or double quotes.
Python Programming
Boolean Literals
• A Boolean literal can have any of the two values: True or False
Python Programming
Special Literals
• Python contains one special literal i.e. None
• We use it to specify that the field has not been created.
• The None keyword is used to define a null value, or no value at all.
Python Programming
Literal Collections
• There are four different literal collections List literals, Tuple literals, Dictionary literals, and
Set literals.
Python Programming
Standard Data Types
• The data stored in memory can be of many types.
• For example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters.
• Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them.
• Python has five standard data types:
• Number
• String
• List
• Tuple
• Dictionary
Python Programming
Numbers
• Number data types store numeric values.
• Number objects are created when you assign a value to them.
• You can also delete the reference to a number object by using the del statement.
• You can delete a single object or multiple objects by using the del statement.
• Syntax: del var1[, var2[,var3[…,varN]]]
• Python supports three different numerical types:
• int (signed integers)
• float (floating point real values)
• complex (complex numbers)
• All integers in Python3 are represented as long integers.
Python Programming
Numbers

int float complex

10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
-0490 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j

A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are
real numbers and j is the imaginary unit.
Python Programming
Strings
• Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
• Python allows either pair of single or double quotes.
• Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at
0 in the beginning of the string and working their way from -1 to the end.
• The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator.
Python Programming
Strings
Python Programming
Iteration Through a String
• We can iterate through a string using a for loop. 
Python Programming
String Membership
• We can test if a substring exists within a string or not, using the keyword in.
Python Programming
String – Built-in Functions to Work With
• Various built-in functions that work with sequence work with strings as well.
• Some of the commonly used ones are enumerate() and len().
• The enumerate() function returns an enumerate object. It contains the index and value of
all items in the strings as pairs. This can be useful for iteration.
• Similarly, len() returns the length (number of characters) of the string.
Python Programming
Escape Sequence
• An escape sequence starts with a backslash and is interpreted differently.
• If we use a single quote to represent a string, all the single quotes inside the string must be
escaped. Similar is the case with double quotes. 
• One way to get around this problem is to use triple quotes.
Python Programming
List of Escape Sequences
Escape Sequence Description
\newline Backslash and newline ignored

\\ Backslash

\' Single quote

\" Double quote

\a ASCII Bell

\b ASCII Backspace

\f ASCII Formfeed

\n ASCII Linefeed

\r ASCII Carriage Return

\t ASCII Horizontal Tab

\v ASCII Vertical Tab

\ooo Character with octal value ooo

\xHH Character with hexadecimal value HH


Python Programming
List of Escape Sequences Example 2
Python Programming
Raw String to Ignore Escape Sequence
• Sometimes we may wish to ignore the escape sequences inside a string. 
• To do this we can place r or R in front of the string.
• This will imply that it is a raw string and any escape sequence inside it will be ignored.
Python Programming
Common String Methods
• There are numerous methods available with the string object. 
• The format(), lower(), upper(), join(), split(), find(), replace() etc.
Python Programming
Lists
• Lists are the most versatile of Python's compound data types.
• A list contains items separated by commas and enclosed within square brackets ([]).
• To some extent, lists are similar to arrays in C.
• One of the differences between them is that all the items belonging to a list can be of
different data type.
• The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1.
• The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.
Python Programming
Lists Example
Python Programming
Tuples
• A tuple is another sequence data type that is similar to the list.
• A tuple consists of a number of values separated by commas.
• Unlike lists, however, tuples are enclosed within parentheses.
• The main differences between lists and tuples are:
• Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while
tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
• Tuples can be thought of as read-only lists.
Python Programming
Tuples Example
Python Programming
Dictionary
• Python's dictionaries are kind of hash table type.
• They work like associative arrays or hashes found in Perl and consist of key-value pairs.
• A dictionary key can be almost any Python type, but are usually numbers or strings.
• Values, on the other hand, can be any arbitrary Python object.
• Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([])
• Dictionaries have no concept of order among elements.
• It is incorrect to say that the elements are "out of order"; they are simply unordered.
Python Programming
Dictionary Example
Python Programming
Data Type Conversion
• To convert between types, you simply use the type name as a function.
• There are several built-in functions to perform conversion from one data type to another.
• These functions return a new object representing the converted value.

Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
Python Programming
Data Type Conversion

Function Description
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key, value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Print() and Input() Functions
Python Programming
Print() Function
• The Print() function prints the specified message to the screen, or other standard output
device.
• The message can be a string, or any other object, the object will be converted into a string
before written to the screen.
• Syntax:
print(object(s), sep=separator, end=end, file=file, flush=flush)

• Parameter Values:
• object(s) - Any object, and as many as you like. Will be converted to string before printed
• sep='separator’ - Optional. Specify how to separate the objects, if there is more than one. Default is ' ‘
• end='end’ - Optional. Specify what to print at the end. Default is '\n' (line feed)
• file - Optional. An object with a write method. Default is sys.stdout
• flush - Optional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
Python Programming
Print() Function Example
Python Programming
Print() Function – Output Formatting
• Sometimes we would like to format our output to make it look attractive.
• This can be done by using the str.format() method.
• This method is visible to any string object.
• The curly braces are used as placeholders.
• We can specify the order in which they are printed using numbers(tuple index).
• We can even use keyword arguments to format the string.
• We can also format strings like the old sprintf() style used in C Programming language. We
use the % operator to accomplish this.
Python Programming
Print() Function – Output Formatting Example 1
Python Programming
Print() Function – Output Formatting Example 2
Python Programming
Print() Function – Output Formatting Example 3
Python Programming
Print() Function – Output Formatting Example 4
Python Programming
Input() Function
• The Input() function allows user input.
• Syntax:
input(prompt)

• Parameter Values:
• prompt - A String, representing a default message before the input.
Python Programming
Input() Function Example
Expressions
Python Programming
Expressions
• Expression is the building block of computations
• Expression is made up of operands and operators
• Operators are the constructs, which can manipulate the value of operands.
Python Programming
Type of Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Programming
Arithmetic Operators
• Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Description Example Expression
+ Addition Add two operands or unary plus x+y
- Subtraction Subtract right operand from the left or unary minus x–y
* Multiplication Multiply two operands x*y
Division Divide left operand by the right one (always results
/ into float) x/y

Modulus Modulus - remainder of the division of left operand


% by the right x%y

** Exponentiation Exponent - left operand raised to the power of right x ** y

// Floor division Floor division - division that results into whole x // y


number adjusted to the left in the number line
Python Programming
Arithmetic Operators
Python Programming
Assignment Operators or Shorthand Operators
• Assignment operators are used to assign values to variables:
Operator Example Expression Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Python Programming
Comparison Operators
• These operators compare the values on either side of them and decide the relation among
them.
• They are also called Relational operators.
Operator Name Description Example Expression
== Equal Equal to - True if both operands are equal x == y

!= Not equal Not equal to - True if operands are not equal x != y


Greater than Greater than - True if left operand is greater than the
> x>y
right

< Less than Less than - True if left operand is less than the right x<y
Greater than or Greater than or equal to - True if left operand is
>= equal to x >= y
greater than or equal to the right
Less than or equal Less than or equal to - True if left operand is less than
<= to or equal to the right x <= y
Python Programming
Comparison Operators
Python Programming
Logical Operators
• Logical operators are used to combine conditional statements.

Operator Name Description Example Expression

and Logical AND True if both the operands are true x and y

or Logical OR True if either of the operands is true x or y

True if operand is false (complements the


not Logical NOT not x
operand)
Python Programming
Logical Example
Python Programming
Boolean Logic
• The Boolean type is the only variable that can only represent one of two values: true or
false
• This type is often used to record the result of a comparison or logical operation.
• Truth Table:
and or ^

True and True True or True True ^ True

True and False True or False True ^ False

False and True False or True False ^ True

False and False False or False False ^ False


Python Programming
Identity Operators
• Identity operators compare the memory locations of two objects.
• They are used to check if two values (or variables) are located on the same part of the
memory.
• Two variables that are equal does not imply that they are identical.

Operator Meaning Example

is True if the operands are identical (refer to the same object) x is True

is not True if the operands are not identical (do not refer to the same object) x is not True
Python Programming
Identity Operators Example
Python Programming
Membership Operators
• They are used to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x


Python Programming
Membership Operators Example
Python Programming
Operators Precedence
• The following table lists all operators from highest precedence to the lowest.
Operator

**

~+-
* / % //

+-

>> <<
&

^|
<= < > >=

<> == !=

= %= /= //= -= += *= **=
is is not

in not in

not or and
Precision Handling
Thank you.
Python Programming
Floating-Point Number Precision Handling
• Python in its definition allows to handle precision of floating point numbers in several ways
using different functions.
• Most of them are defined under the “math” module.
• Some most used operations:
• trunc() :- This function is used to eliminate all decimal part of the floating point
number and return the integer without the decimal part.
• ceil() :- This function is used to print the least integer greater than the given number.
• floor() :- This function is used to print the greatest integer smaller than the given
integer.
Python Programming
Floating-Point Number Precision Handling Example
Python Programming
Floating-Point Number Precision Handling
• There are many ways to set precision of floating point value.
• Ways to set precision of floating point value:
• Using “%” :- “%” operator is used to format as well as set precision in python. This is similar to “printf”
statement in C programming.
• Using format() :- This is yet another way to format the string for setting precision.
• Using round(x,n) :- This function takes 2 arguments, number and the number till which we want
decimal part rounded.
Python Programming
Floating-Point Number Precision Handling
Namespace and Scope
Python Programming
Namespace
• To simply put it, a namespace is a collection of names.
• In Python, you can imagine a namespace as a mapping of every name you have defined to
corresponding objects.
• Different namespaces can co-exist at a given time but are completely isolated.
• A namespace containing all the built-in names is created when we start the Python
interpreter and exists as long as the interpreter runs.
• Each module creates its own global namespace.
• These different namespaces are isolated. Hence, the same name that may exist in different
modules do not collide.
• Modules can have various functions and classes.
• A local namespace is created when a function is called, which has all the names defined in
it. Similar, is the case with class. 
Python Programming
Namespace
Python Programming
variable Scope
• Here, the variable a is in the global namespace.
• Variable b is in the local namespace of
outer_function() and c is in the nested local
namespace of inner_function()
• When we are in inner_function(), c is local to us, b is
non-local and a is global.
• We can read and assign new values to c but can
only read b and a from inner_function().
• If we try to assign as a value to b, a new variable b is
created in the local namespace which is different
than non-local b.
• The same thing happens when we assign a value
to a
Python Programming
variable Scope
• However, if we declare a as global, all the reference
and assignment go to the global a.
• Similarly, if we want to rebind the variable b, it must
be declared as non-local.
Python Programming
variable Scope
Python Programming
variable Scope
End of Lesson 1
Thank you.

You might also like