0% found this document useful (0 votes)
6 views111 pages

Python Introduction

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views111 pages

Python Introduction

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 111

Python Programming

UNIT - I
 Python Basics
 Python Objects-
– Python Objects, Other Built-in Types, Internal Types, Standard Type Operators, Standard
Type Built-in Functions, Categorizing the Standard Types, Unsupported Types.
 Numbers-
– Introduction to Numbers, Integers, Floating Point Real Numbers, Complex Numbers,
Operators, Built-in Functions, Related Modules
 Sequences- Strings, Lists, and Tuples
 Mapping and Set Types
History of Python
History of Python
Guido van Rossum
 Python is easy and powerful because
– It has functional programming language like C.
– It is an Object-oriented programming language like C++ (not from Java)

Java came in 1995; Python in 1991


 Python is easy and powerful because
– It has functional programming language like C.
– It is an Object-oriented programming language like C++ (not from Java)
– Python is also a scripting language like Perl and Shell Scripting are.
– It has the modular programming features - just like Modula3 has.

 The syntax of the Python language in inspired by C and ABC.


Flavours of Python
 CPython - the standard flavour of Python
 Jpython - for Java based applications
 IronPython - for Windows C# applications
 AnacondaPython - for Big Data projects
 PyPy - to develop Python programs that run faster
 RubyPython - for Ruby based applications
 Stackless Python - for running concurrent programs in Python
Python 2 Vs Python 3
 Python 3 is not backward compatible: It'll not support Python2 fully.
– Python2:print 'Hi'
– Python3:print('Hi’)

– Long data type is valid in Python2, but not supported in Python3

 More libraries and packages for Python3 to make it more feature rich than
Python2
 We'll use the Python3 version in the Lab.
Interpreter
 The interpreter will transform the code from the first to the last word by word
 If interpreter find one error it will stop working raising this error
 Like Python
Compiler
 The compiler will transform the whole code
 If the compiler found any error it will continue and when it finish it will raise
all the errors
 Like C#
Python Editors
 Python IDLE
 Pycharm
 Eclipse
 Aptana
 Vistual Studio
 Notepad++
 And more
Comments
Running Python - points to remember
 You can run a single line of Python statement from the Python shell
 If you want to run multiple Python commands together, create a file, save it with the
extension .py
 Python interpreter reads one Python statement at a time, line by line; starts from top
of the file and goes line by line
 One line of Python is interpreted as one Python statement unless postfixed by
backslash \ or bracket []
 If there is any error in the Python program, the interpreter throws error; fix it
and re-
run the program.
 Multiple python statements in a single line - all separated by ;
Variable
Points to remember
 Group of characters enclosed within ' '," ", ''' ''',""" """ called a string in
Python.
 a = 40 means the value 40 stored in the same memory location where the
variable a points to. The address of this memory location is id(a).
 The variable a can be of any data type. In Python, its not required to declare
what type of data the variable will refer to.
 The value a variable points to keeps on changing - Python is dynamically
typed language.
 The Print() command prints the output.
33 keywords & Reserved words
 True, False, None
 and, or, not, is
 if, else, elif
 while, for, break, continue, return, in, yield
 try, except, finally, raise, in, yield
 import, from, as, class, def, pass, global, nonlocal, lambda, del, with
 All keywords start with lower case letter, except first three
OUTPUT:-
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
Identifiers
 Names you give to variables, functions, packages etc.
Rules to follow while naming identifiers
 Valid characters in a name are:
– Numbers 0 to 9
– Small letters a to z
– Capital letters A to Z
– The underscore character _

 Names are case sensitive.


– The function f() and the function F() are different.
– The variable Total and the variable total are different.

 A name cannot start with a digit. e.g. 123abc is invalid identifier.


 No keywords and reserved words . E.g. def is invalid name as it is a reserved word.

 Identifiers can be as long as you want them to be - no length limit


 It's recommended to use short, meaningful names though!
 Identifiers can be as long as you want them to be - no length limit
 It's recommended to use short, meaningful names though!
Special Identifiers
 Private identifiers - Start with single underscore _ e.g. _X
 Strongly private identifiers - start with two underscores e.g. X
 Language specific identifiers - start with two undersores and end with
two underscores e.g X
 _X is a private identifier
 X is a strongly private identifier
 name , file , init , add etc. are the language
specific identifier used in Python; also called magic methods or
Dunder.
the following lists all the attributes and
List of magic methods methods defined in the int class.
Data Types
 A data type, in programming, is a classification that specifies which type of
value a variable has and what type of mathematical, relational or logical
operations can be applied to it without causing an error.
Type Conversion:
 The process of converting the value of one data type (integer, string, float,
etc.) to another data type is called type conversion.
 Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion
 Python automatically converts one data type to another data type. This
process doesn't need any user involvement.
Explicit Type Conversion
 In Explicit Type Conversion, users convert the data type of an object to
required data type. We use the predefined functions like int(), float(),
str(), etc to perform explicit type conversion.
 This type conversion is also called typecasting because the user casts
(change) the data type of the objects.
Almost all operators except the exponent (**)
support the left-to-right associativity.
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


Nested if
while True:
print("Menu Option")
print("+ Addtion")
print("- Substraction") elif (op == '%'):
print("* Multipication") if(b==0):
print("/ Division") print("Division Error")
print("% Remainder") else:
print("** Exponent") print("Rem", a % b)
print("// Floor Value")
op=input("U R OPTION:") elif (op == '**'):
a=int(input("A=")) print("exp", a ** b)
b=int(input("B=")) elif(op=='//'):
if(op=='+'): if (b == 0):
print("Sum",a+b) print("Division Error")
elif(op=='-'): else:
print("Sub", a - b) print("floor div:",
elif (op == '*'): a//b)
print("MUL", a * b) else:
elif (op == '/'): print("Invalid Option Try Again")
if(b==0): if op=='#':
print("Division Error") break;
else:
print("div", a / b)
Built-in function range()
 A for loop is often used in combination with the built-in function
range() function to execute a block of code a specified number of
times.
 The range function generates a sequence of integers.

• range(n) generates the sequence 0, ..., n-1


• range(i, n)generates the sequence i, i+1, i+2, …, n-1
• range(i, n, c)generates the sequence i, i+c, i+2c, i+3c, …, n-1
pip3 install numpy
OUTPUT

OUTPUT
OUTPUT
General format: >>> a = b = 0
while <test1>: # loop test >>> while a < 10:
<statements1> # loop ... a += 3
else: body ... print(a)
<statemen # optional ...
ts2> else 3
# run if 6
loop didn't 9
break
12
# run if
while >>> while True:
becomes ... b += 3
false ... if b >= 10: break
... print(b)
3
6
9
>>> a = 0
>>> while a < 5: a +=1
>>> print a
5
>>> for i in [2, 5, 3]:
for <target> in <object>:
<statements> ... print(i**2)
else: # optional, didn't hit a break 4
<other statements> 25
9
>>> for j in range(5): print(j)
0
1
2
3
4
>>> range(3, 10, 2)
[3,5,7,9]
>>> d = {'this': 2, 'that': 7}
>>> for k, v in d.items():
... print('%s is %i'%(k, v))
this is 2
that is 7
Auxiliary Statements if while for

elif •
else • • •
break • •
continue • •
pass • • •

Note:- pass is valid anywhere a suite (single or multiple statements) is required (also
includes elif, else, class, def, Try, except, finally).
Function
 Syntax:
Default Arguments
Function Description
Display attributes of object or the names of global variables if
dir([obj])
noparameter given
Display object's documentation string in a pretty-printed format
help([obj]) or enters interactive help if no parameter given
int(obj) Convert object to an integer
len(obj) Return length of object
open(fn, mode) Open file fn with mode ('r' = read, 'w' = write)
Return a list of integers that begin at start up to but not
range(start, stop, step) including stop in increments of step; start defaults to 0, and step
defaults to 1
Wait for text input from the user, optional prompt string can be
raw_input(str)
provided
str(obj) Convert object to a string
type(obj) Return type of object (a type object itself!)

You might also like