You are on page 1of 33

Python Programming

By
Vaibhav P. Vasani
Assistant Professor
Department of Computer Engineering
K. J. Somaiya College of Engineering
Somaiya Vidyavihar University

4/18/2022 vaibhav.vasani@gmail.com 1
What is python ??
1.Python is higher level,object oriented,interactive
language.
2.Interpreted because you don't have to compile the
program after writing
3.Interactive because you can use python shell and get
instant output of code which you are writing
4.Object oriented as it support objects oriented style

4/18/2022 2
Features of python
• Easy to learn,Read and Maintain
• Broad standard of library
• Interactive mode
• Portable
• Extendable
• GUI programming
• Scalable

4/18/2022 3
Identifier
• Identifier are basically used to name the variable so as
for human understanding
• The naming convention for python are similar to java
• Indentation is important & similar to the brackets of
java.

4/18/2022 4
Variables
• Variable are nothing but any set of character to which is
assigned
• For eg.
• Test = 1,a = 2,b=”this is just a test”
• Multiple assignment => a=b=c=1 or a,b,c,d = 1,2,’test’,3
• Every time a values is assigned to a variable the we reserve a
memory for that variable based on the datatype of that
variable

4/18/2022 5
Data Types in python
• Number :- the types of number used in python are int, long,float and complex
• String :- python take string as the set of characters enclosed in the pair of single or
double quotes

• List :- classic example of array with some additional feature.the list store store
anything in [ ]

• Tuple :- It is different than list in only in terms of functionality and storing data as
the data of tuple cannot be modified

• Dictionary :- Dictionary in python is very similar to hash tables and it stores the
values in key value pair manner and key in dictionary can only be string or integer but
the value assigned to keys can be anything

4/18/2022 6
Enough to Understand the Code
• Indentation matters to meaning the code
o Block structure indicated by indentation
• The first assignment to a variable creates it
o Dynamic typing: no declarations, names don’t have types,
objects do
• Assignment uses = and comparison uses ==
• For numbers + - * / % are as expected.
o Use of + for string concatenation.
o Use of % for string formatting (like printf in C)
• Logical operators are words (and,or,not)
not symbols
• The basic printing command is print
4/18/2022 vaibhav.vasani@gmail.com 7
Data Types
>>> type(15) >>> 1j * 1j
<class 'int'> (-1+0j)
>>> type (3.) >>> s = 3 + 1j
<class 'float'> >>> type(s)
>>> x = 34.8 <class 'complex'>
>>> type(x) >>> x = "learning”
<class 'float'> >>> type(x)
<class 'str'>

4/18/2022 vaibhav.vasani@gmail.com 8
Whitespace
Whitespace is meaningful in Python, especially
indentation and placement of newlines
Use a newline to end a line of code
Use \ when must go to next line prematurely
No braces {} to mark blocks of code, use consistent
indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
Colons start of a new block in many constructs, e.g.
function definitions, then clauses

4/18/2022 vaibhav.vasani@gmail.com 9
Comments
• Start comments with #, rest of line is ignored
• Can include a “documentation string” as the first
line of a new function or class you define
• Development environments, debugger, and other
tools use it: it’s good style to include one
def fact(n):
“““fact(n) assumes n is a positive
integer and returns facorial of n.”””
assert(n>0)
return 1 if n==1 else n*fact(n-1)

4/18/2022 vaibhav.vasani@gmail.com 10
Assignment
• Binding a variable in Python means setting a name to
hold a reference to some object
o Assignment creates references, not copies
• Names in Python don’t have an intrinsic type, objects
have types
Python determines type of the reference auto-
matically based on what data is assigned to it
• You create a name the first time it appears on the left
side of an assignment expression:
x = 3
• A reference is deleted via garbage collection after any
names bound to it have passed out of scope
• Python uses reference semantics (more later)
4/18/2022 vaibhav.vasani@gmail.com 11
Naming Rules
• Names are case sensitive and cannot start with a
number. They can contain letters, numbers, and
underscores.
abc Abc _abc _2_abc_ abc_2 AbC
• There are some reserved words:
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if, import,
in, is, lambda, not, or, pass, print,
raise, return, try, while

4/18/2022 vaibhav.vasani@gmail.com 12
Naming conventions
The Python community has these recommended naming
conventions
 joined_lower for functions, methods and, attributes
 joined_lower or ALL_CAPS for constants
 StudlyCaps for classes
 camelCase only to conform to pre-existing
conventions
 Attributes: interface, _internal, __private

4/18/2022 vaibhav.vasani@gmail.com 13
Accessing Non-Existent Name
Accessing a name before it’s been properly created
(by placing it on the left side of an assignment),
raises an error

>>> y

Traceback (most recent call last):


File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3

4/18/2022 vaibhav.vasani@gmail.com 14
Everything is an object
• Python data is represented by objects or by relations
between objects
• Every object has an identity, a type and a value
• Identity never changes once created Location or
address in memory
• Type (e.g., integer, list) is unchangeable and
determines the possible values it could have and
operations that can be applied
• Value of some objects is fixed (e.g., an integer) and
can change for others (e.g., list)

4/18/2022 vaibhav.vasani@gmail.com 15
Python’s built-in type hierarchy

4/18/2022 vaibhav.vasani@gmail.com 16
Expressions

• An expression calculates a value


• Arithmetic operators: +, -, *, /, ** (exponentiation)
• Add, subtract, multiply, divide work just as they do in
other C-style languages
• Spaces in an expression are not significant
• Parentheses override normal precedence

4/18/2022 vaibhav.vasani@gmail.com 17
Expressions
• Mixed type (integer and float) expressions are converted to floats:
>>> 4 * 2.0 /6
1.3333333333333333

• Mixed type (real and imaginary) conversions:


>>> x = 5 + 13j
>>> y = 3.2
>>> z = x + y
>>> z
(8.2 + 13J )

• Explicit casts are also supported:


>>> y = 4.999 >>> x = 8
>>> int(y) >>> float(x)
4 8.0

4/18/2022 vaibhav.vasani@gmail.com 18
Output Statements
3.x version
• Statement syntax: (EBNF notation)
print ({expression,})
where the final comma in the list is optional
• Examples:
print() # prints a blank line
print(3, y, z + 10) # go to new line
print('result: ',z,end=" ")# no
newline
• Output items are automatically separated by a single
space.

4/18/2022 vaibhav.vasani@gmail.com 19
Interactive Input
• Syntax: input → variable = input(string)
The string is used as a prompt.
Inputs a string
>>> y = input("enter a name --> ")
enter a name --> max
>>> y
'max'
>>> number = input("Enter an integer ")
Enter an integer 32
>>> number
’32’
• input() reads input from the keyboard as a string;

4/18/2022 vaibhav.vasani@gmail.com 20
Input
• To get numeric data use a cast :
>>> number = int(input("enter an
integer: "))
enter an integer: 87
>>> number
87
• If types don’t match (e.g., if you type
4.5 and try to cast it as an integer) you
will get an error:
ValueError: invalid literal for int() with base 10:

4/18/2022 vaibhav.vasani@gmail.com 21
Input
• Multiple inputs:
>>> x, y = int(input("enter an integer: ")),
float(input("enter a float: "))
enter an integer: 3
enter a float: 4.5
>>> print("x is", x, " y is ", y)
x is 3 y is 4.5
• Instead of the cast you can use the eval( ) function and
Python choose the correct types:
>>> x, y = eval(input("Enter two numbers: "))
Enter two numbers: 3.7, 98
>>> x, y
(3.7, 98)

4/18/2022 vaibhav.vasani@gmail.com 22
Python Data Types/Data Structures
• Many built-in simple types: ints, floats, infinite
precision integers, complex, string, etc.
• Built-in data structures:
o Lists or dynamic arrays
o Dictionaries (associative arrays or hash tables)
−Accessed by key-value indices
o Tuples
−Similar to lists, but cannot be modified
−Sometimes used like structs, but indexed by position instead of field
name

4/18/2022 vaibhav.vasani@gmail.com 23
String Data Type
• A sequence of characters enclosed in quotes (single or
double; just be consistent)
• Elements can be accessed via an index, but you
cannot change the individual characters – you will get
an error if you try:
• TypeError: 'str' object does not
support item assignment

4/18/2022 vaibhav.vasani@gmail.com 24
String Data Type
>>> str1 = 'happy'
>>> str2 = “Holi"
>>> str1, str2
(‘happy', ‘Holi') # a tuple
>>> str1[1]
'a'
>>> x = str1, str2
>>> x
('happy', ‘Holi') # x is a tuple
>>> x[1]
‘Holi'

4/18/2022 vaibhav.vasani@gmail.com 25
String Data Type - continued
>>> print(str1, str2)
Happy Holi
>>> “Delhi is Capital of Bharat"
" Delhi is Capital of Bharat "
>>> ‘Mumbai isn’t capital of Bharat'
>>>
Syntax Error: invalid syntax

Use double quotes when you want to include single quotes


(and vice versa)

4/18/2022 vaibhav.vasani@gmail.com 26
String Data Type
• More examples:
>>> '"why not?" said Arjun'
'"why not?" said Arjun'
>>> 'can\'t'
"can't“

You can get the same effect by using the escape sequence \’ or
\”

4/18/2022 vaibhav.vasani@gmail.com 27
String Operations
• Indexing: 0-based indexing for string characters
• General format: <string>[<expr>]
>>> name = ‘Radha Krishna'
>>> name[0]
‘R'
>>> x = 3
>>> name[x + 2]
‘ ’
• Negative indexes work from right to left:
>>> myName = "Radha Krishna"
>>> myName[-3]
‘h'

4/18/2022 vaibhav.vasani@gmail.com 28
String Operations
• Slicing: selects a ‘slice’ or segment of a string
<string>[<start>:<end>] where <start> is the
beginning index and <end> is one past final index
>>> myName = “Manan Vasani"
>>> myName[2:7]
‘nan V‘

• If either <start> or <end> is omitted, the start and


end of the string are assumed
>>> myName[:5]
'Manan'
>>> myName[4:]
'n Vasani'
>>> myName[:]
'Manan Vasani'

4/18/2022 vaibhav.vasani@gmail.com 29
String Operations
Concatenation (+)
>>> "happy" + "birthday"
'happybirthday'
>>> 'happy' + ' birthday'
'happy birthday’
Repetition (*)
>>> word = 'ha'
>>> 3 * word
'hahaha'
>>> word + 3 * '!'
'ha!!!'

4/18/2022 vaibhav.vasani@gmail.com 30
String Operations
Other examples:
>>> word = 'ha'
>>> len(word) # length function
2
>>> len(“Krishna and Radha")
12

4/18/2022 vaibhav.vasani@gmail.com 31
None
• None is used to define a null variable or an object.
• Assigning value None to Variable
• Testing the value of Variable
var =None
if var is no
print(“None”)
else
print(“Not None”)
none
Type(var)
None type

4/18/2022 vaibhav.vasani@gmail.com 32
• Thank you

4/18/2022 vaibhav.vasani@gmail.com 33

You might also like