SlideShare a Scribd company logo
UNIT-I: BASICS
Python interpreter and interactive
mode – Tokens- Data types –
Numbers and mat functions – Input
and output operations - Comments
– Reserved words – Indentation –
Operators and Expressions –
Precedence and associativity – Type
Conversion – Debugging – Common
errors in Python.
1-1
1. INTRODUCTION
• Python is a high-level, interpreted, interactive and object
oriented-scripting language.
• Python was designed to be highly readable which uses
English keywords frequently where as other languages use
punctuation and it has fewer syntactical constructions than
other languages.
1-2
INTRODUCTION(Cont…)
• Python is Interpreted: This means that it is processed at
runtime by the interpreter and you do not need to compile
your program before executing it. This is similar to PERL and
PHP.
• Python is Interactive: This means that you can actually sit at a
Python prompt and interact with the interpreter directly to
write your programs.
• Python is Object-Oriented: This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.
• Python is Beginner's Language: Python is a great language for
the beginner programmers and supports the development of
a wide range of applications, from simple text processing to
WWW browsers to games.
1-3
Compiling and interpreting
• Many languages require you to compile (translate) your
program into a form that the machine understands.
• Python is instead directly interpreted into machine
instructions.
compile execute
output
source code
Hello.java
byte code
Hello.class
interpret
output
source code
Hello.py
1-4
History of Python
• Python was developed by Guido van Rossum in the late
eighties and early nineties at the National Research Institute
for Mathematics and Computer Science in the Netherlands.
• Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and
other scripting languages.
• Python is copyrighted, Like Perl, Python source code is now
available under the GNU General Public License (GPL).
• Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing it's progress.
1-5
Python Features
• Easy-to-learn: Python has relatively few keywords, simple
structure, and a clearly defined syntax.
• Easy-to-read: Python code is much more clearly defined and
visible to the eyes.
• Easy-to-maintain: Python's success is that its source code is
fairly easy-to-maintain.
• A broad standard library: One of Python's greatest strengths
is the bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode: Support for an interactive mode in which
you can enter results from a terminal right to the language,
allowing interactive testing and debugging of snippets of
code.
1-6
Python Features (cont’d)
• 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.
1-7
Python Environment
• Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.)
• Win 9x/NT/2000
• Macintosh (PPC, 68K)
• OS/2
• DOS (multiple versions)
• PalmOS
• Nokia mobile phones
• Windows CE
• Acorn/RISC OS
• BeOS
• Amiga
• VMS/OpenVMS
• QNX
• VxWorks
• Psion
• Python has also been ported to the Java and .NET virtual machines.
1-8
2. Python interpreter and interactive
mode
1-9
Python - Basic Syntax
• Interactive Mode Programming:
>>> print "Hello, Python!";
Hello, Python!
>>> 3+4*5;
23
1-10
• Script Mode Programming :
Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is
finished. When the script is finished, the interpreter is no
longer active.
For example, put the following in one test.py, and run,
print "Hello, Python!";
print "I love COMP3050!";
The output will be:
Hello, Python!
I love COMP3050!
1-11
3. Tokens
• The smallest unit/element in the python
program/script is known as a Token or a
Lexical unit. Python has following Tokens:
– Keywords
– Identifiers
– Literals
– Operators
– Punctuators
1-12
Reserved Words:
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Keywords contain lowercase letters only.
1-13
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 Manpower and manpower are two different identifiers
in Python.
1-14
Python Identifiers (cont’d)
• Here are following identifier naming convention for Python:
– Class names start with an uppercase letter and all other
identifiers with a lowercase letter.
– Starting an identifier with a single leading underscore
indicates by convention that the identifier is meant to be
private.
– Starting an identifier with two leading underscores
indicates a strongly private identifier.
– If the identifier also ends with two trailing underscores,
the identifier is a language-defined special name.
1-15
Literals
• Literals are the data items that have a fixed
or constant value.
• Literals are essential building elements of
Python programming, expressing fixed
values directly inserted within code.
• They include many data kinds, each serving
a specific role in relaying information to the
interpreter
1-16
Literals: Types
• String Literals: The text written in single, double, or triple
quotes represents the string literals in Python. For example:
“Computer Science”, ‘sam’, etc. We can also use triple quotes to
write multi-line strings. A string literal is a sequence of
characters surrounded by Quotes.
• Example:
• string = 'Hello'
• s = "World"
• A = "'Python is a
• high-level and
• general purpose language'"
•
1-17
Literals: Types
• Character Literals: Character literal is also a
string literal type in which the character is
enclosed in single or double-quotes.
• Example:
• a = 'G'
• b = "W"
1-18
Literals: Types
• Numeric Literals: These are the literals written
in form of numbers. Python supports the
following numerical literals:
– Integer Literal: It includes both positive and
negative numbers along with 0. It doesn’t include
fractional parts. It can also include binary, decimal,
octal, hexadecimal literal.
– Float Literal: It includes both positive and negative
real numbers. It also includes fractional parts.
– Complex Literal: It includes a+bi numeral, here a
represents the real part and b represents the
complex part.
1-19
Literals: Types
• Boolean Literals: Boolean literals have only
two values in Python. These are True and
False.
• Special Literals: Python has a special literal
‘None’. It is used to denote nothing, no
values, or the absence of value.
• Example:
• var = None
• print(var)
1-20
Literals: Types
• Literals Collections
– List, dictionary, tuple, and sets are examples of Python literal
collections.
– List: It is a comma-separated list of components enclosed in square
brackets. These elements can be of any data type and can be
changed.
– Tuple: In round brackets, this is similar to a list having comma-
separated items or values. The values are fixed and can have any
Python data type.
– Dictionary: This data structure is an unordered set of key-value
combinations.
– Set: It is the group of components enclosed in curly braces, "{}"
• Example:
• # A list literal collection
• my_list = [23, "Python", 1.2, 'Character']
1-21
4. Data Types
• Data types are the classification or categorization of data
items. Data types are used to identify the type of data and set
of valid operations which can be performed on it.
1-22
Data Types (cont..)
Python has five standard data types:
• Numbers
• String
• List
• Tuple
• Dictionary
1-23
Python Numbers:
• Number data types store numeric values. They are immutable
data types, which means that changing the value of a number
data type results in a newly allocated object.
• Number objects are created when you assign a value to them.
For example:
var1 = 1
var2 = 10
Python supports four different numerical types:
• int (signed integers)
• long (long integers [can also be represented in octal and
hexadecimal])
• float (floating point real values)
• complex (complex numbers)
1-24
Number Examples:
int long float complex
10 51924361L 0 3.14j
100 -0x19323L 15.2 45.j
-786 0122L -21.9 9.322e-36j
80 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-490 535633629843L -90 -.6545+0J
-0x260 -052318172735L -3.25E+101 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
1-25
Python Strings
• Strings in Python are identified as a contiguous set of
characters in between quotation marks.
• Python allows for either pairs 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 at the end.
• The plus ( + ) sign is the string concatenation operator, and
the asterisk ( * ) is the repetition operator.
1-26
Example:
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to
6th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
1-27
Python 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
difference 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.
1-28
Python Lists (cont..)
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
1-29
Python 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.
1-30
Python Tuples(Cont..)
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
OUTPUT:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
1-31
Python Dictionary:
• Python 's dictionaries are hash table type. They work like
associative arrays or hashes found in Perl and consist of key-
value pairs.
• Keys 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 ( [] ).
1-32
Python Dictionary(cont..)
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
OUTPUT:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
1-33
Boolean Data Type
• Data type with one of the two built-in values, True
or False.
• Boolean objects that are equal to True are truthy
(true), and those equal to False are falsy (false).
• However non-Boolean objects can be evaluated in a
Boolean context as well and determined to be true
or false. It is denoted by the class bool.
• Note – True and False with capital ‘T’ and ‘F’ are
valid booleans otherwise python will throw an error.
1-34
Set Data Type
• In Python, a Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements.
• The order of elements in a set is undefined though it may consist of
various elements.
• Sets can be created by using the built-in set() function with an
iterable object or a sequence by placing the sequence inside curly
braces, separated by a ‘comma’. T
• he type of elements in a set need not be the same, various mixed-
up data type values can also be passed to the set.
• Set items cannot be accessed by referring to an index, since sets are
unordered the items have no index.
• But we can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in the keyword.
1-35
5. NUMBERS AND MATH FUNCTIONS
• Python has a set of built-in math functions, including
an extensive math module. It allows to perform
mathematical tasks on numbers.
1-36
Python - Numbers
• Number data types store numeric values. They are immutable
data types, which means that changing the value of a number
data type results in a newly allocated object.
• Number objects are created when you assign a value to them.
For example:
var1 = 1
var2 = 10
• You can also delete the reference to a number object by
using the del statement. The syntax of the del statement is:
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using
the del statement. For example:
del var del var_a, var_b
Python - Numbers
Python supports four different numerical types:
• int (signed integers): often called just integers or ints, are positive
or negative whole numbers with no decimal point.
• long (long integers ): or longs, are integers of unlimited size,
written like integers and followed by an uppercase or lowercase L.
• float (floating point real values) : or floats, represent real numbers
and are written with a decimal point dividing the integer and
fractional parts. Floats may also be in scientific notation, with E or e
indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
• complex (complex numbers) : are of the form a + bJ, where a and b
are floats and J (or j) represents the square root of -1 (which is an
imaginary number). a is the real part of the number, and b is the
imaginary part. Complex numbers are not used much in Python
programming.
Mathematical Functions(Math functions
Function Returns ( description )
abs(x) The absolute value of x: the (positive) distance between x and zero.
ceil(x) The ceiling of x: the smallest integer not less than x
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y
exp(x) The exponential of x: e
x
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x
log(x) The natural logarithm of x, for x> 0
log10(x) The base-10 logarithm of x for x> 0 .
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts
have the same sign as x. The integer part is returned as a float.
pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from
zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
sqrt(x) The square root of x for x > 0
Random Number Functions:
Function Returns ( description )
choice(seq) A random item from a list, tuple, or string.
randrange ([start,]
stop [,step])
A randomly selected element from range(start, stop,
step)
random() A random float r, such that 0 is less than or equal to
r and r is less than 1
seed([x]) Sets the integer starting value used in generating
random numbers. Call this function before calling
any other random module function. Returns None.
shuffle(lst) Randomizes the items of a list in place. Returns
None.
uniform(x, y) A random float r, such that x is less than or equal to
r and r is less than y
Trigonometric Functions:
Function Description
acos(x) Return the arc cosine of x, in radians.
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
6. INPUT AND OUTPUT OPERATIONS
• In Python, program output is displayed using
the print() function, while user input is obtained
with the input() function. Python treats all input
as strings by default, requiring explicit
conversion for other data types.
1-42
Python Input
• Sometimes, users or developers want to run the programs with their
own data in the variables for their own ease. To execute this, we will
learn to take input from the users, in which the users themselves will
define the values of the variables. The input() statement allows us to do
such things in Python.
• The syntax for this function is as follows:
• input('prompt ')
• Here, prompt is the string we want to display while taking input from
the user. This is optional.
• Python get user input with a message
• # Taking input from the user
• name = input("Enter your name: ")
•
• # Output
• print("Hello, " + name)
• print(type(name))
1-43
Python Output
• Python provides the print() function to display output to the
standard output devices.
• Syntax:
– print(value(s), sep= ‘ ‘, end = ‘n’, file=file, flush=flush)
• Parameters:
– value(s) : Any value, and as many as . Will be converted to string
before printed
– sep=’separator’ (Optional) : Specify how to separate the objects, if
there is more than one.Default :’ ‘
– end=’end’(Optional) : Specify what to print at the end.Default : ‘n’
– file (Optional) : An object with a write method. Default :sys.stdout
– flush (Optional) : A Boolean, specifying if the output is flushed
(True) or buffered (False). Default: False
– Returns: It returns output to the screen.
1-44
7. Comments
• Comments are non executable statements in a
program.
– Single line comment always starts with #
– Multiline comment will be in triple quotes. For
example “’ write a program to find the simple
interest “’.
– Note: Triple apostrophe is called docstrings.
1-45
Single-line comments
• A single-line comment starts and ends in the same line. We use the # symbol to
write a single-line comment.
• Example:
• # create a variable
• name = 'Eric Cartman'
•
• # print the value
• print(name)
• Output
• Eric Cartman
• Here, we have created two single-line comments:
• # create a variable
• # print the value
• We can also use the single-line comment along with the code.
• name = 'Eric Cartman' # name is a string
• Here, code before # are executed and code after # are ignored by the interpreter.
1-46
Multi-line comments
• Python doesn't offer a separate way to write multiline comments.
However, there is other ways to get around this issue.
• We can use # at the beginning of each line of comment on multiple
lines.
• For example,
• # This is a long comment
• # and it extends
• # to multiple lines
• Here, each line is treated as a single comment, and all of them are
ignored.
• Another way of doing this is to use triple quotes, either ''' or """.
• These triple quotes are generally used for multi-line strings. But if
we do not assign it to any variable or function, we can use it as a
comment.The interpreter ignores the string that is not assigned to
any variable or function.
1-47
8. RESERVED WORDS
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no
matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
1-48
RESERVED WORDS(Cont..)
1-49
Keyword Description
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator
9. Indentation
• Indentation in Python refers to the whitespaces
at the start of the line to indicate a block of
code.
• We can create an indentation using space or
tabs.
• When writing Python code, we have to define a
group of statements for functions and loops.
• This is done by properly indenting the
statements for that block.
1-50
Indentation(Cont..)
• The leading whitespaces (space and tabs) at
the start of a line are used to determine the
indentation level of the line.
• We have to increase the indent level to group
the statements for that code block.
• Similarly, reduce the indentation to close the
grouping.
• The four whitespaces or a single tab character
at the beginning of a code line are used to
create or increase the indentation level.
1-51
Indentation(Cont..)
1-52
Indentation(Cont..)
1-53
• Python Indentation Rules
• Below are the rules that one should follow
while using indentation:
– The first line of Python code can’t have an indentation, it will
throw IndentationError.
– We should avoid mixing tabs and whitespaces to create an
indentation. It’s because text editors in Non-Unix systems
behave differently and mixing them can cause the wrong
indentation.
– It is preferred to use whitespace than the tab character.
– The best practice is to use 4 whitespaces for the first
indentation and then keep adding additional 4 whitespaces to
increase the indentation.
10. OPERATORS AND EXPRESSIONS
Python language supports following type of operators.
• Arithmetic Operators
• Comparison Operators
• Assignment Operators
• Unary Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Python Arithmetic Operators:
Operator Description Example
+ Addition - Adds values on either side of the
operator
a + b will give 30
- Subtraction - Subtracts right hand operand
from left hand operand
a - b will give -10
* Multiplication - Multiplies values on either
side of the operator
a * b will give 200
/ Division - Divides left hand operand by
right hand operand
b / a will give 2
% Modulus - Divides left hand operand by
right hand operand and returns remainder
b % a will give 0
** Exponent - Performs exponential (power)
calculation on operators
a**b will give 10 to
the power 20
// Floor Division - The division of operands
where the result is the quotient in which
the digits after the decimal point are
removed.
9//2 is equal to 4 and
9.0//2.0 is equal to 4.0
Python Comparison Operators:
Operato
r
Description Example
== Checks if the value of two operands are equal or not, if
yes then condition becomes true.
(a == b) is not true.
!= Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(a != b) is true.
<> Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
(a <> b) is true. This is
similar to != operator.
> Checks if the value of left operand is greater than the
value of right operand, if yes then condition becomes
true.
(a > b) is not true.
< Checks if the value of left operand is less than the
value of right operand, if yes then condition becomes
true.
(a < b) is true.
>= Checks if the value of left operand is greater than or
equal to the value of right operand, if yes then
condition becomes true.
(a >= b) is not true.
<= Checks if the value of left operand is less than or equal
to the value of right operand, if yes then condition
becomes true.
(a <= b) is true.
Python Assignment Operators:
Operator Description Example
= Simple assignment operator, Assigns values from right
side operands to left side operand
c = a + b will
assigne value of a +
b into c
+= Add AND assignment operator, It adds right operand to
the left operand and assign the result to left operand
c += a is equivalent
to c = c + a
-= Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to left
operand
c -= a is equivalent
to c = c - a
*= Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to left
operand
c *= a is equivalent
to c = c * a
/= Divide AND assignment operator, It divides left operand
with the right operand and assign the result to left
operand
c /= a is equivalent
to c = c / a
%= Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left operand
c %= a is equivalent
to c = c % a
**= Exponent AND assignment operator, Performs exponential
(power) calculation on operators and assign value to the
left operand
c **= a is
equivalent to c = c
** a
//= Floor Division and assigns a value, Performs floor division
on operators and assign value to the left operand
c //= a is equivalent
to c = c // a
Python Bitwise Operators:
Operat
or
Description Example
& Binary AND Operator copies a bit to the
result if it exists in both operands.
(a & b) will give 12
which is 0000 1100
| Binary OR Operator copies a bit if it exists
in either operand.
(a | b) will give 61
which is 0011 1101
^ Binary XOR Operator copies the bit if it is
set in one operand but not both.
(a ^ b) will give 49
which is 0011 0001
~ Binary Ones Complement Operator is unary
and has the effect of 'flipping' bits.
(~a ) will give -60
which is 1100 0011
<< Binary Left Shift Operator. The left
operands value is moved left by the
number of bits specified by the right
operand.
a << 2 will give 240
which is 1111 0000
>> Binary Right Shift Operator. The left
operands value is moved right by the
number of bits specified by the right
operand.
a >> 2 will give 15
which is 0000 1111
Python Logical Operators:
Operat
or
Description Example
and Called Logical AND operator. If both the
operands are true then then condition
becomes true.
(a and b) is true.
or Called Logical OR Operator. If any of the two
operands are non zero then then condition
becomes true.
(a or b) is true.
not Called Logical NOT Operator. Use to
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.
not(a and b) is false.
Python Membership Operators:
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a
sequence, such as strings, lists, or tuples.
Operator Description Example
in Evaluates to true if it finds a variable in the
specified sequence and false otherwise.
x in y, here in results in a 1
if x is a member of
sequence y.
not in Evaluates to true if it does not finds a variable
in the specified sequence and false otherwise.
x not in y, here not in
results in a 1 if x is a
member of sequence y.
Python Identity Operators:
Operator Sample
Expression
Result
is x is y  True if x and y hold a
reference to the same in-
memory object
 False otherwise
is not x is not y  True if x points to an object
different from the object
that y points to
 False otherwise
1-61
Unary operator
• Unary operators are those operators that require a
single operand for computations. Python supports
unary minus operator. The operator ‘-’ is called the
Unary minus operator. It is used to negate the number.
The minus operator is used to represent a negative
value.
• Example:
• b=10
• a=-(b)
• The result of this expression is a=-10, because
variable b has a positive value. After applying unary
minus operator (-) on the operand b, the value
becomes -10, which indicates it as a negative value
1-62
11. Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~ + - Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= +=
*= **=
Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
12. TYPE CONVERSION
• Type conversion is the process of converting
data of one type to another. There are mainly
two types of type conversion methods in
Python:
– Implicit type conversion- Done automatically by
the Python interpreter
– Explicit type conversion- Needs to be done
manually by the programmer.
1-64
Implicit type conversion
• In certain situations, Python automatically converts
one data type to another. This is known as implicit
type conversion. This type of data type conversion
takes place during compilation or during the runtime.
• Example:
– a = 5
– b = 5.5
– sum = a + b
– print (sum)
– print (type (sum)) #type() is used to display the datatype of a variable
• Output:
– 10.5
– <class ‘float’>
1-65
Explicit type conversion
• Explicit type conversion is also known as
typecasting.
• In Explicit Type Conversion, the data type is
manually changed by the user as per their
requirement.
• With explicit type conversion, there is a risk of
data loss since we are forcing an expression to
be changed in some specific data type
1-66
Data Type Conversion:
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.
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. 1-67
13. DEBUGGING
• Debugging is a method that involves testing
of a code during its execution and code
correction.
• During debugging, a program is executed
several times with different inputs to ensure
that it performs its intended task correctly.
• While other forms of testing aims to
demonstrate correctness of the programs,
testing during debugging, on the other hand
is primarily aimed at locating errors.
•
1-68
Preconditions for Effective debugging
• Understand the design and algorithm
• Check correctness
• Code tracing
• Peer reviews
1-69
Principles of Debugging
• Report error conditions immediately
• Maximize useful information and ease of
interpretation
• Minimize useless and distracting
information
• Avoid complex one-use testing code
1-70
Debugging Aids
• Assert statements
• Tracebacks
• General purpose debuggers
• Print Statements
1-71
14. COMMON ERRORS IN PYTHON
• There are several types of errors that can
occur in Python.
• Each type indicates a different kind of problem
in the code, and comprehending these error
types is crucial in creating effective Python
applications.
• The most common types of errors encounter
in Python are syntax errors, runtime errors,
logical errors, name errors, type errors, index
errors, and attribute errors.
1-72
Syntax Errors
• A syntax error occurs in Python when the
interpreter is unable to parse the code due to
the code violating Python language rules, such
as inappropriate indentation, erroneous
keyword usage, or incorrect operator use.
• Syntax errors prohibit the code from running,
and the interpreter displays an error message
that specifies the problem and where it
occurred in the code.
1-73
Runtime Errors
• In Python, a runtime error occurs when the
program is executing and encounters an
unexpected condition that prevents it from
continuing.
• Runtime errors are also known as exceptions
and can occur for various reasons such as
division by zero, attempting to access an
index that is out of range, or calling a
function that does not exist.
1-74
Logical Errors
• A logical error occurs in Python when the
code runs without any syntax or runtime
errors but produces incorrect results due to
flawed logic in the code.
• These types of errors are often caused by
incorrect assumptions, an incomplete
understanding of the problem, or the
incorrect use of algorithms or formulas.
• Unlike syntax or runtime errors, logical errors
can be challenging to detect and fix because
the code runs without producing any error
messages. 1-75

More Related Content

PDF
Python Programing Bio computing,basic concepts lab,,
PDF
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
PPT
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
PPTX
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
PDF
Computer Related material named Phython ok
PPTX
Introduction to Python Programming .pptx
PPTX
Introduction to Python Programming Language
PPT
program on python what is python where it was started by whom started
Python Programing Bio computing,basic concepts lab,,
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
Computer Related material named Phython ok
Introduction to Python Programming .pptx
Introduction to Python Programming Language
program on python what is python where it was started by whom started

Similar to python introduction all the students.ppt (20)

PPT
Python Over View (Python for mobile app Devt)1.ppt
PPT
Py-Slides-1.ppt1234444444444444444444444444444444444444444
PPT
Python slides for the beginners to learn
PDF
GE3151_PSPP_UNIT_2_Notes
PPT
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
PDF
problem solving and python programming UNIT 2.pdf
PDF
Problem Solving and Python Programming UNIT 2.pdf
PDF
Introduction of Python
PPTX
python ppt | Python Course In Ghaziabad | Scode Network Institute
PPT
Python - Module 1.ppt
PPTX
introduction to python programming concepts
PDF
Stu_Unit1_CSE1.pdf
PPTX
PYTHON PROGRAMMING.pptx
PDF
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PPTX
Python Programming 1.pptx
PDF
Python-01| Fundamentals
PPTX
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
PDF
Python Programming
PDF
Python final ppt
PDF
Pythonfinalppt 170822121204
Python Over View (Python for mobile app Devt)1.ppt
Py-Slides-1.ppt1234444444444444444444444444444444444444444
Python slides for the beginners to learn
GE3151_PSPP_UNIT_2_Notes
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
problem solving and python programming UNIT 2.pdf
Problem Solving and Python Programming UNIT 2.pdf
Introduction of Python
python ppt | Python Course In Ghaziabad | Scode Network Institute
Python - Module 1.ppt
introduction to python programming concepts
Stu_Unit1_CSE1.pdf
PYTHON PROGRAMMING.pptx
PYTHON PROGRAMMING NOTES RKREDDY.pdf
Python Programming 1.pptx
Python-01| Fundamentals
2024-25 TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
Python Programming
Python final ppt
Pythonfinalppt 170822121204
Ad

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
Sustainable Sites - Green Building Construction
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
composite construction of structures.pdf
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
Artificial Intelligence
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
DOCX
573137875-Attendance-Management-System-original
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
PPT on Performance Review to get promotions
PPTX
web development for engineering and engineering
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
Geodesy 1.pptx...............................................
Sustainable Sites - Green Building Construction
CYBER-CRIMES AND SECURITY A guide to understanding
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
composite construction of structures.pdf
Foundation to blockchain - A guide to Blockchain Tech
Internet of Things (IOT) - A guide to understanding
Artificial Intelligence
III.4.1.2_The_Space_Environment.p pdffdf
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Operating System & Kernel Study Guide-1 - converted.pdf
573137875-Attendance-Management-System-original
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPT on Performance Review to get promotions
web development for engineering and engineering
Fundamentals of safety and accident prevention -final (1).pptx
CH1 Production IntroductoryConcepts.pptx
Ad

python introduction all the students.ppt

  • 1. UNIT-I: BASICS Python interpreter and interactive mode – Tokens- Data types – Numbers and mat functions – Input and output operations - Comments – Reserved words – Indentation – Operators and Expressions – Precedence and associativity – Type Conversion – Debugging – Common errors in Python. 1-1
  • 2. 1. INTRODUCTION • Python is a high-level, interpreted, interactive and object oriented-scripting language. • Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages. 1-2
  • 3. INTRODUCTION(Cont…) • Python is Interpreted: This means that it is processed at runtime by the interpreter and you do not need to compile your program before executing it. This is similar to PERL and PHP. • Python is Interactive: This means that you can actually sit at a Python prompt and interact with the interpreter directly to write your programs. • Python is Object-Oriented: This means that Python supports Object-Oriented style or technique of programming that encapsulates code within objects. • Python is Beginner's Language: Python is a great language for the beginner programmers and supports the development of a wide range of applications, from simple text processing to WWW browsers to games. 1-3
  • 4. Compiling and interpreting • Many languages require you to compile (translate) your program into a form that the machine understands. • Python is instead directly interpreted into machine instructions. compile execute output source code Hello.java byte code Hello.class interpret output source code Hello.py 1-4
  • 5. History of Python • Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. • Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. • Python is copyrighted, Like Perl, Python source code is now available under the GNU General Public License (GPL). • Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing it's progress. 1-5
  • 6. Python Features • Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. • Easy-to-read: Python code is much more clearly defined and visible to the eyes. • Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain. • A broad standard library: One of Python's greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. • Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code. 1-6
  • 7. Python Features (cont’d) • 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. 1-7
  • 8. Python Environment • Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.) • Win 9x/NT/2000 • Macintosh (PPC, 68K) • OS/2 • DOS (multiple versions) • PalmOS • Nokia mobile phones • Windows CE • Acorn/RISC OS • BeOS • Amiga • VMS/OpenVMS • QNX • VxWorks • Psion • Python has also been ported to the Java and .NET virtual machines. 1-8
  • 9. 2. Python interpreter and interactive mode 1-9
  • 10. Python - Basic Syntax • Interactive Mode Programming: >>> print "Hello, Python!"; Hello, Python! >>> 3+4*5; 23 1-10
  • 11. • Script Mode Programming : Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active. For example, put the following in one test.py, and run, print "Hello, Python!"; print "I love COMP3050!"; The output will be: Hello, Python! I love COMP3050! 1-11
  • 12. 3. Tokens • The smallest unit/element in the python program/script is known as a Token or a Lexical unit. Python has following Tokens: – Keywords – Identifiers – Literals – Operators – Punctuators 1-12
  • 13. Reserved Words: and exec not assert finally or break for pass class from print continue global raise def if return del import try elif in while else is with except lambda yield Keywords contain lowercase letters only. 1-13
  • 14. 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 Manpower and manpower are two different identifiers in Python. 1-14
  • 15. Python Identifiers (cont’d) • Here are following identifier naming convention for Python: – Class names start with an uppercase letter and all other identifiers with a lowercase letter. – Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be private. – Starting an identifier with two leading underscores indicates a strongly private identifier. – If the identifier also ends with two trailing underscores, the identifier is a language-defined special name. 1-15
  • 16. Literals • Literals are the data items that have a fixed or constant value. • Literals are essential building elements of Python programming, expressing fixed values directly inserted within code. • They include many data kinds, each serving a specific role in relaying information to the interpreter 1-16
  • 17. Literals: Types • String Literals: The text written in single, double, or triple quotes represents the string literals in Python. For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes to write multi-line strings. A string literal is a sequence of characters surrounded by Quotes. • Example: • string = 'Hello' • s = "World" • A = "'Python is a • high-level and • general purpose language'" • 1-17
  • 18. Literals: Types • Character Literals: Character literal is also a string literal type in which the character is enclosed in single or double-quotes. • Example: • a = 'G' • b = "W" 1-18
  • 19. Literals: Types • Numeric Literals: These are the literals written in form of numbers. Python supports the following numerical literals: – Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t include fractional parts. It can also include binary, decimal, octal, hexadecimal literal. – Float Literal: It includes both positive and negative real numbers. It also includes fractional parts. – Complex Literal: It includes a+bi numeral, here a represents the real part and b represents the complex part. 1-19
  • 20. Literals: Types • Boolean Literals: Boolean literals have only two values in Python. These are True and False. • Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no values, or the absence of value. • Example: • var = None • print(var) 1-20
  • 21. Literals: Types • Literals Collections – List, dictionary, tuple, and sets are examples of Python literal collections. – List: It is a comma-separated list of components enclosed in square brackets. These elements can be of any data type and can be changed. – Tuple: In round brackets, this is similar to a list having comma- separated items or values. The values are fixed and can have any Python data type. – Dictionary: This data structure is an unordered set of key-value combinations. – Set: It is the group of components enclosed in curly braces, "{}" • Example: • # A list literal collection • my_list = [23, "Python", 1.2, 'Character'] 1-21
  • 22. 4. Data Types • Data types are the classification or categorization of data items. Data types are used to identify the type of data and set of valid operations which can be performed on it. 1-22
  • 23. Data Types (cont..) Python has five standard data types: • Numbers • String • List • Tuple • Dictionary 1-23
  • 24. Python Numbers: • Number data types store numeric values. They are immutable data types, which means that changing the value of a number data type results in a newly allocated object. • Number objects are created when you assign a value to them. For example: var1 = 1 var2 = 10 Python supports four different numerical types: • int (signed integers) • long (long integers [can also be represented in octal and hexadecimal]) • float (floating point real values) • complex (complex numbers) 1-24
  • 25. Number Examples: int long float complex 10 51924361L 0 3.14j 100 -0x19323L 15.2 45.j -786 0122L -21.9 9.322e-36j 80 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j -490 535633629843L -90 -.6545+0J -0x260 -052318172735L -3.25E+101 3e+26J 0x69 -4721885298529L 70.2-E12 4.53e-7j 1-25
  • 26. Python Strings • Strings in Python are identified as a contiguous set of characters in between quotation marks. • Python allows for either pairs 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 at the end. • The plus ( + ) sign is the string concatenation operator, and the asterisk ( * ) is the repetition operator. 1-26
  • 27. Example: str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 6th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string Output: Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST 1-27
  • 28. Python 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 difference 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. 1-28
  • 29. Python Lists (cont..) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists Output: ['abcd', 786, 2.23, 'john', 70.2] abcd [786, 2.23] [2.23, 'john', 70.2] [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] 1-29
  • 30. Python 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. 1-30
  • 31. Python Tuples(Cont..) tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple # Prints complete list print tuple[0] # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints list two times print tuple + tinytuple # Prints concatenated lists OUTPUT: ('abcd', 786, 2.23, 'john', 70.2) abcd (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john') 1-31
  • 32. Python Dictionary: • Python 's dictionaries are hash table type. They work like associative arrays or hashes found in Perl and consist of key- value pairs. • Keys 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 ( [] ). 1-32
  • 33. Python Dictionary(cont..) dict = {} dict['one'] = "This is one" dict[2] = "This is two“ tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # Prints value for 'one' key print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values OUTPUT: This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john'] 1-33
  • 34. Boolean Data Type • Data type with one of the two built-in values, True or False. • Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). • However non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class bool. • Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error. 1-34
  • 35. Set Data Type • In Python, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. • The order of elements in a set is undefined though it may consist of various elements. • Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a ‘comma’. T • he type of elements in a set need not be the same, various mixed- up data type values can also be passed to the set. • Set items cannot be accessed by referring to an index, since sets are unordered the items have no index. • But we can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in the keyword. 1-35
  • 36. 5. NUMBERS AND MATH FUNCTIONS • Python has a set of built-in math functions, including an extensive math module. It allows to perform mathematical tasks on numbers. 1-36
  • 37. Python - Numbers • Number data types store numeric values. They are immutable data types, which means that changing the value of a number data type results in a newly allocated object. • Number objects are created when you assign a value to them. For example: var1 = 1 var2 = 10 • You can also delete the reference to a number object by using the del statement. The syntax of the del statement is: del var1[,var2[,var3[....,varN]]]] You can delete a single object or multiple objects by using the del statement. For example: del var del var_a, var_b
  • 38. Python - Numbers Python supports four different numerical types: • int (signed integers): often called just integers or ints, are positive or negative whole numbers with no decimal point. • long (long integers ): or longs, are integers of unlimited size, written like integers and followed by an uppercase or lowercase L. • float (floating point real values) : or floats, represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250). • complex (complex numbers) : are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). a is the real part of the number, and b is the imaginary part. Complex numbers are not used much in Python programming.
  • 39. Mathematical Functions(Math functions Function Returns ( description ) abs(x) The absolute value of x: the (positive) distance between x and zero. ceil(x) The ceiling of x: the smallest integer not less than x cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y exp(x) The exponential of x: e x fabs(x) The absolute value of x. floor(x) The floor of x: the largest integer not greater than x log(x) The natural logarithm of x, for x> 0 log10(x) The base-10 logarithm of x for x> 0 . max(x1, x2,...) The largest of its arguments: the value closest to positive infinity min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity modf(x) The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float. pow(x, y) The value of x**y. round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0. sqrt(x) The square root of x for x > 0
  • 40. Random Number Functions: Function Returns ( description ) choice(seq) A random item from a list, tuple, or string. randrange ([start,] stop [,step]) A randomly selected element from range(start, stop, step) random() A random float r, such that 0 is less than or equal to r and r is less than 1 seed([x]) Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None. shuffle(lst) Randomizes the items of a list in place. Returns None. uniform(x, y) A random float r, such that x is less than or equal to r and r is less than y
  • 41. Trigonometric Functions: Function Description acos(x) Return the arc cosine of x, in radians. asin(x) Return the arc sine of x, in radians. atan(x) Return the arc tangent of x, in radians. atan2(y, x) Return atan(y / x), in radians. cos(x) Return the cosine of x radians. hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y). sin(x) Return the sine of x radians. tan(x) Return the tangent of x radians. degrees(x) Converts angle x from radians to degrees. radians(x) Converts angle x from degrees to radians.
  • 42. 6. INPUT AND OUTPUT OPERATIONS • In Python, program output is displayed using the print() function, while user input is obtained with the input() function. Python treats all input as strings by default, requiring explicit conversion for other data types. 1-42
  • 43. Python Input • Sometimes, users or developers want to run the programs with their own data in the variables for their own ease. To execute this, we will learn to take input from the users, in which the users themselves will define the values of the variables. The input() statement allows us to do such things in Python. • The syntax for this function is as follows: • input('prompt ') • Here, prompt is the string we want to display while taking input from the user. This is optional. • Python get user input with a message • # Taking input from the user • name = input("Enter your name: ") • • # Output • print("Hello, " + name) • print(type(name)) 1-43
  • 44. Python Output • Python provides the print() function to display output to the standard output devices. • Syntax: – print(value(s), sep= ‘ ‘, end = ‘n’, file=file, flush=flush) • Parameters: – value(s) : Any value, and as many as . Will be converted to string before printed – sep=’separator’ (Optional) : Specify how to separate the objects, if there is more than one.Default :’ ‘ – end=’end’(Optional) : Specify what to print at the end.Default : ‘n’ – file (Optional) : An object with a write method. Default :sys.stdout – flush (Optional) : A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False – Returns: It returns output to the screen. 1-44
  • 45. 7. Comments • Comments are non executable statements in a program. – Single line comment always starts with # – Multiline comment will be in triple quotes. For example “’ write a program to find the simple interest “’. – Note: Triple apostrophe is called docstrings. 1-45
  • 46. Single-line comments • A single-line comment starts and ends in the same line. We use the # symbol to write a single-line comment. • Example: • # create a variable • name = 'Eric Cartman' • • # print the value • print(name) • Output • Eric Cartman • Here, we have created two single-line comments: • # create a variable • # print the value • We can also use the single-line comment along with the code. • name = 'Eric Cartman' # name is a string • Here, code before # are executed and code after # are ignored by the interpreter. 1-46
  • 47. Multi-line comments • Python doesn't offer a separate way to write multiline comments. However, there is other ways to get around this issue. • We can use # at the beginning of each line of comment on multiple lines. • For example, • # This is a long comment • # and it extends • # to multiple lines • Here, each line is treated as a single comment, and all of them are ignored. • Another way of doing this is to use triple quotes, either ''' or """. • These triple quotes are generally used for multi-line strings. But if we do not assign it to any variable or function, we can use it as a comment.The interpreter ignores the string that is not assigned to any variable or function. 1-47
  • 48. 8. RESERVED WORDS Keyword Description and A logical operator as To create an alias assert For debugging break To break out of a loop class To define a class continue To continue to the next iteration of a loop def To define a function del To delete an object elif Used in conditional statements, same as else if else Used in conditional statements except Used with exceptions, what to do when an exception occurs False Boolean value, result of comparison operations finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not for To create a for loop from To import specific parts of a module global To declare a global variable if To make a conditional statement 1-48
  • 49. RESERVED WORDS(Cont..) 1-49 Keyword Description import To import a module in To check if a value is present in a list, tuple, etc. is To test if two variables are equal lambda To create an anonymous function None Represents a null value nonlocal To declare a non-local variable not A logical operator or A logical operator pass A null statement, a statement that will do nothing raise To raise an exception return To exit a function and return a value True Boolean value, result of comparison operations try To make a try...except statement while To create a while loop with Used to simplify exception handling yield To end a function, returns a generator
  • 50. 9. Indentation • Indentation in Python refers to the whitespaces at the start of the line to indicate a block of code. • We can create an indentation using space or tabs. • When writing Python code, we have to define a group of statements for functions and loops. • This is done by properly indenting the statements for that block. 1-50
  • 51. Indentation(Cont..) • The leading whitespaces (space and tabs) at the start of a line are used to determine the indentation level of the line. • We have to increase the indent level to group the statements for that code block. • Similarly, reduce the indentation to close the grouping. • The four whitespaces or a single tab character at the beginning of a code line are used to create or increase the indentation level. 1-51
  • 53. Indentation(Cont..) 1-53 • Python Indentation Rules • Below are the rules that one should follow while using indentation: – The first line of Python code can’t have an indentation, it will throw IndentationError. – We should avoid mixing tabs and whitespaces to create an indentation. It’s because text editors in Non-Unix systems behave differently and mixing them can cause the wrong indentation. – It is preferred to use whitespace than the tab character. – The best practice is to use 4 whitespaces for the first indentation and then keep adding additional 4 whitespaces to increase the indentation.
  • 54. 10. OPERATORS AND EXPRESSIONS Python language supports following type of operators. • Arithmetic Operators • Comparison Operators • Assignment Operators • Unary Operators • Logical Operators • Bitwise Operators • Membership Operators • Identity Operators
  • 55. Python Arithmetic Operators: Operator Description Example + Addition - Adds values on either side of the operator a + b will give 30 - Subtraction - Subtracts right hand operand from left hand operand a - b will give -10 * Multiplication - Multiplies values on either side of the operator a * b will give 200 / Division - Divides left hand operand by right hand operand b / a will give 2 % Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0 ** Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20 // Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0
  • 56. Python Comparison Operators: Operato r Description Example == Checks if the value of two operands are equal or not, if yes then condition becomes true. (a == b) is not true. != Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true. <> Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a <> b) is true. This is similar to != operator. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.
  • 57. Python Assignment Operators: Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand c = a + b will assigne value of a + b into c += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division and assigns a value, Performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a
  • 58. Python Bitwise Operators: Operat or Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12 which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (a | b) will give 61 which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~a ) will give -60 which is 1100 0011 << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240 which is 1111 0000 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is 0000 1111
  • 59. Python Logical Operators: Operat or Description Example and Called Logical AND operator. If both the operands are true then then condition becomes true. (a and b) is true. or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (a or b) is true. not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. not(a and b) is false.
  • 60. Python Membership Operators: In addition to the operators discussed previously, Python has membership operators, which test for membership in a sequence, such as strings, lists, or tuples. Operator Description Example in Evaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y. not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is a member of sequence y.
  • 61. Python Identity Operators: Operator Sample Expression Result is x is y  True if x and y hold a reference to the same in- memory object  False otherwise is not x is not y  True if x points to an object different from the object that y points to  False otherwise 1-61
  • 62. Unary operator • Unary operators are those operators that require a single operand for computations. Python supports unary minus operator. The operator ‘-’ is called the Unary minus operator. It is used to negate the number. The minus operator is used to represent a negative value. • Example: • b=10 • a=-(b) • The result of this expression is a=-10, because variable b has a positive value. After applying unary minus operator (-) on the operand b, the value becomes -10, which indicates it as a negative value 1-62
  • 63. 11. Python Operators Precedence Operator Description ** Exponentiation (raise to the power) ~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@) * / % // Multiply, divide, modulo and floor division + - Addition and subtraction >> << Right and left bitwise shift & Bitwise 'AND' ^ | Bitwise exclusive `OR' and regular `OR' <= < > >= Comparison operators <> == != Equality operators = %= /= //= -= += *= **= Assignment operators is is not Identity operators in not in Membership operators not or and Logical operators
  • 64. 12. TYPE CONVERSION • Type conversion is the process of converting data of one type to another. There are mainly two types of type conversion methods in Python: – Implicit type conversion- Done automatically by the Python interpreter – Explicit type conversion- Needs to be done manually by the programmer. 1-64
  • 65. Implicit type conversion • In certain situations, Python automatically converts one data type to another. This is known as implicit type conversion. This type of data type conversion takes place during compilation or during the runtime. • Example: – a = 5 – b = 5.5 – sum = a + b – print (sum) – print (type (sum)) #type() is used to display the datatype of a variable • Output: – 10.5 – <class ‘float’> 1-65
  • 66. Explicit type conversion • Explicit type conversion is also known as typecasting. • In Explicit Type Conversion, the data type is manually changed by the user as per their requirement. • With explicit type conversion, there is a risk of data loss since we are forcing an expression to be changed in some specific data type 1-66
  • 67. Data Type Conversion: 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. 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. 1-67
  • 68. 13. DEBUGGING • Debugging is a method that involves testing of a code during its execution and code correction. • During debugging, a program is executed several times with different inputs to ensure that it performs its intended task correctly. • While other forms of testing aims to demonstrate correctness of the programs, testing during debugging, on the other hand is primarily aimed at locating errors. • 1-68
  • 69. Preconditions for Effective debugging • Understand the design and algorithm • Check correctness • Code tracing • Peer reviews 1-69
  • 70. Principles of Debugging • Report error conditions immediately • Maximize useful information and ease of interpretation • Minimize useless and distracting information • Avoid complex one-use testing code 1-70
  • 71. Debugging Aids • Assert statements • Tracebacks • General purpose debuggers • Print Statements 1-71
  • 72. 14. COMMON ERRORS IN PYTHON • There are several types of errors that can occur in Python. • Each type indicates a different kind of problem in the code, and comprehending these error types is crucial in creating effective Python applications. • The most common types of errors encounter in Python are syntax errors, runtime errors, logical errors, name errors, type errors, index errors, and attribute errors. 1-72
  • 73. Syntax Errors • A syntax error occurs in Python when the interpreter is unable to parse the code due to the code violating Python language rules, such as inappropriate indentation, erroneous keyword usage, or incorrect operator use. • Syntax errors prohibit the code from running, and the interpreter displays an error message that specifies the problem and where it occurred in the code. 1-73
  • 74. Runtime Errors • In Python, a runtime error occurs when the program is executing and encounters an unexpected condition that prevents it from continuing. • Runtime errors are also known as exceptions and can occur for various reasons such as division by zero, attempting to access an index that is out of range, or calling a function that does not exist. 1-74
  • 75. Logical Errors • A logical error occurs in Python when the code runs without any syntax or runtime errors but produces incorrect results due to flawed logic in the code. • These types of errors are often caused by incorrect assumptions, an incomplete understanding of the problem, or the incorrect use of algorithms or formulas. • Unlike syntax or runtime errors, logical errors can be challenging to detect and fix because the code runs without producing any error messages. 1-75