Python Notes
Python Notes
FE0_SEC_PYP_T202
Module 1
Basics of Python:
By
Ms. Harshal P G
Asst. Professor, SFIT
MODULE 1
Basics of Python:
1.1 Introduction: Features of Python, Comparison of Python with C/C++
• Interpreted
• Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• A broad standard library: Python's bulk of the library is very portable and
cross platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.
• Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• 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.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.
• Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
Creating a Comment
• Comments starts with a #, and Python will ignore them:
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Interpreter VS Compiler
• Two kinds of applications process high-level languages into low-level languages:
interpreters and compilers.
• An interpreter reads a high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately reading lines and
performing computations.
• A compiler reads the program and translates it into a low-level program, which can then be
run.
• In this case, the high-level program is called the source code, and the translated program
is called the object code or the executable. Once a program is compiled, you can execute
it repeatedly without further translation.
• Many modern languages use both processes. They are first compiled into a
lower level language, called byte code, and then interpreted by a program
called a virtual machine. Python uses both processes, but because of the way
programmers interact with it, it is usually considered an interpreted language
• There are two ways to use the Python interpreter: shell mode and script mode.
• In shell mode, you type Python statements into the Python shell and the
interpreter immediately prints the result.
• Running Python program:
Semantic errors
• The third type of error is the semantic error. If there is a semantic error in your program, it will
run successfully, in the sense that the computer will not generate any error messages, but it will
not do the right thing. It will do something else.
• Specifically, it will do what you told it to do.
• The problem is that the program you wrote is not the program you wanted to write. The meaning
of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it
requires you to work backward by looking at the output of the program and trying to figure out
what it is doing.
• Formal and Natural Languages:
• Natural languages are the languages that people speak, such as
English, Spanish, and French. They were not designed by people
(although people try to impose some order on them); they evolved
naturally.
• Formal languages are languages that are designed by people for
specific applications. For example, the notation that mathematicians use
is a formal language that is particularly good at denoting relationships
among numbers and symbols.
• Casting
If you want to specify the data type of a variable, this can be done
with casting.
Get the Type
• You can get the data type of a variable with the type() function.
Python Datatypes
1.Numeric – int , float, complex
2. String
It can be declared either by using single or double quotes:
• print("Hello")
print('Hello')
Multiline Strings
• You can assign a multiline string to a variable by using three double or single quotes:
• a = """Lorem ipsum dolor sit amet, a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit, consectetur adipiscing elit,
ut labore et dolore magna aliqua.""" ut labore et dolore magna aliqua.'''
b = "Hello, World!“
1. Accessing elements
b[0]
b[-1]
b[-6]
2. Slicing
print(b[2:5])
print(b[:5])
print(b[2:])
3. Replace String
print(b.replace("H", "J"))
4. Split String
print(b.split(",")) # returns ['Hello', ' World!']
5. String Concatenation
• a = "Hello"
b = "World"
c=a+b
print(c) # HelloWorld
• c=a+""+b
print(c) # Hello World
6. String Length
Len(b)
7. Miscellaneous
b.capitalize() b.count(‘o’) b.find(‘Wo’)
b.endswith(“!”) b*3
3. Boolean
• Booleans represent one of two values: True or False.
• print(10 > 9) #True
print(10 == 9) #False
print(10 < 9) #False
• x = "Hello"
y = 15
print(bool(x)) #True
print(bool(y)) #True
• The following will return False:
• bool(False)
• bool(None)
• bool(0)
• bool("")
Operators in Python
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Assignment
Comparison Bitwise
Logical
Membership
Identity
Lists :
• A list is an ordered set of values, where each value is identified by an index.
• The values that make up a list are called its elements .
• Lists are similar to strings, which are ordered sets of characters, except that the
elements of a list can have any type.
• Lists and strings—and other things that behave like ordered sets—are called
sequences .
• The list is the most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets.
• Important thing about a list is that the items in a list need not be of the
same type.
• There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):
• [10, 20, 30, 40] ["spam", "bungee", "swallow"] [10, “spam”,30,40,”swallow”]
• A list within another list is said to be nested .
• Finally, there is a special list that contains no elements. It is called the empty list,
and is denoted []. Like numeric 0 values and the empty string, the empty list is
false in a boolean expression
Lists are mutable :
• Unlike strings lists are mutable , which means we can change their elements.
• Using the bracket operator on the left side of an assignment, we can update one of
the elements:
>>> fruit = ["banana", "apple", “berry"]
>>> fruit[0] = "pear"
>>> fruit[-1] = "orange"
>>> print fruit
[’pear’, ’apple’, ’orange’]
Repetition Len()
>>>lst1=[12, 34, 56] >>>lst1=[12, 34, 56]
>>>print( lst1*3) >>>print(len(lst1))
• #Output
#Output
[12, 34, 56, 12, 34, 56, 12, 34, 56] 3
List list() Method : List sort() Method :
• The list()method takes sequence types and
converts them to lists. This is used to convert
a given tuple into list. >>>list1 = ['physics', 'Biology', 'chemistry',
• Note: Tuple are very similar to lists with only 'maths']
difference that element values of a tuple can
not be changed and tuple elements are put >>>list1.sort()
between parentheses instead of square
bracket. This function also converts >>>print ("list now : ", list1)
characters in a string into a list. >>>list now : ['Biology', 'chemistry',
'maths', 'physics']
>>>aTuple = (123, 'C++', 'Java', 'Python')
>>>list1 = list(aTuple)
>>>print ("List elements : ", list1) • Note: this method sorts the list as
alphabetically , incase of numbers it will
sort according to its value
>>>str="Hello World"
>>>list2=list(str)
>>>print ("List elements : ", list2)
List count()Method List append() Method :
• This method returns count of how • The append() method appends a
many times obj occurs in list. passed obj into the existing list.
>>>aList = [123, 'xyz', 'zara', 'abc', 123]; >>>list1 = ['C++', 'Java', 'Python']
>>>print ("Count for 123 : ", >>>list1.append('C#')
aList.count(123)) >>>print ("updated list : ", list1)
>>>print ("Count for zara : ",
aList.count('zara')) • updated list :['C++', 'Java',
'Python‘, ’C#’]
• Count for 123 : 2
• Count for zara : 1 • NOTE: append method used to add
element in list at last position
List index() Method List extend()Method
• The index() method returns the lowest • The extend() method appends the contents
index in list that obj appears. of seq to list.
• The left side is a tuple of variables; the right side is a tuple of values. Each value is
assigned to its respective variable. This feature makes tuple assignment quite
versatile. Naturally, the number of variables on the left and the number of values
on the right have to be the same:
• Such statements can be useful shorthand for multiple assignment statements, but
care should be taken that it doesn’t make the code more difficult to read.
• One example of tuple assignment that improves readibility is when we want to
swap the values of two variables. With conventional assignment statements, we
have to use a temporary variable. For example, to swap a and b.
Dictionary
• Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this:
{ }.
• Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such
as strings, numbers, or tuples.
• dict['Name']: Zara
• dict['Age']: 7
• Properties of Dictionary keys :
• Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys-
• A. More than one entry per key is not allowed. This means no
duplicate key is allowed. When duplicate keys are encountered during assignment,
the last assignment wins.
>>>dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
>>>print ("dict['Name']: ", dict['Name'])
o/p
• dict['Name']: Manni
• B. Keys must be immutable. This means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed.
>>>dict = {['Name']: 'Zara', 'Age': 7}
>>>print ("dict['Name']: ", dict['Name'])
o/p
• TypeError: list objects are unhashable
Operations in Dictionary :
• The del statement removes a key-value pair from a dictionary.
>>>inventory={’oranges’: 525, ’apples’: 430, ’pears’: 560,
’bananas’: 312}
>>> del inventory["pears"]
>>> print inventory
• {’oranges’: 525, ’apples’: 430, ’bananas’: 312}
• Or if we’re expecting more pears soon, we might just change
the value associated with pears:
>>> inventory["pears"] = 0
>>> print inventory
• {’oranges’: 525, ’apples’: 430, ’pears’: 0, ’bananas’: 312}
• The len function also works on dictionaries; it returns the
number of key-value pairs:
>>> len(inventory) gives 4
Dictionary copy() Method Dictionary get() Method
• This method returns a shallow • This method returns a value for
copy of the dictionary. the given key. If the key is not
>>>dict1 = {'Name': 'Manni', available, then returns default
'Age': 7, 'Class': 'First'} value as None.
>>>dict2 = dict1.copy() >>>dict = {'Name': 'Zara', 'Age': 27}
>>>print ("New Dictionary : >>>print ("Value : " ,dict.get('Age'))
",dict2) >>>print (“Value : " , dict.get('Sex', "NA"))