Python Notes
Python Notes
PYTHON NOTES
Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords
frequently where as other languages use punctuation, and it has fewer syntactical
constructions than other languages.
• Python is Interpreted − Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is similar
to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers to
games.
• 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 its progress.
Python Features
Python's features include −
• Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.
• 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.
Apart from the above-mentioned features, Python has a big list of good features,
few are listed below −
• It supports functional and structured programming methods as well as
OOP.
• It can be used as a scripting language or can be compiled to byte-code for
building large applications.
• It provides very high-level dynamic data types and supports dynamic type
checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Advantages/Benefits of Python
The diverse application of the Python language is a result of the
combination of features which give this language an edge over others.
Some of the benefits of programming in Python include:
The code style guidelines, PEP 8, provide a set of rules to facilitate the
formatting of code. Additionally, the wide base of users and active
developers has resulted in a rich internet resource bank to encourage
development and the continued adoption of the language.
Python has built-in list and dictionary data structures which can be
used to construct fast runtime data structures. Further, Python also
provides the option of dynamic high-level data typing which reduces
the length of support code that is needed.
but requires variable declarations for a and b, and does not allow overloading of the +
operator for instances of user-defined classes.
For these reasons, Python is much better suited as a "glue" language, while Java is better
characterized as a low-level implementation language. In fact, the two together make an
excellent combination. Components can be developed in Java and combined to form
applications in Python; Python can also be used to prototype components until their design
can be "hardened" in a Java implementation. To support this type of development, a Python
implementation written in Java is under development, which allows calling Python code from
Java and vice versa. In this implementation, Python source code is translated to Java
bytecode (with help from a run-time library to support Python's dynamic semantics).
C++
Almost everything said for Java also applies for C++, just more so: where Python code is
typically 3-5 times shorter than equivalent Java code, it is often 5-10 times shorter than
equivalent C++ code! Anecdotal evidence suggests that one Python programmer can finish
in two months what two C++ programmers can't complete in a year. Python shines as a
glue language, used to combine components written in C++.
Disadvantages of Python
Python is a widely used general-purpose, high-level programming language. It is widely
used by developers in various domain like from web-development to Machine Learning.
Though, Python got its own set of advantages and disadvantages. Let’ see some of the
disadvantages of Python.
Speed: Python is interpreted language and is slow as compared to C/C++ or Java.
Unlike C or C++ it’s not closer to hardware because Python is a high-level language. As
we all know that compilation and execution help to work normally, but in this case,
execution of Python takes place with the help of an interpreter instead of the compiler
as we have seen that Python code is executed line by line, which causes it to slow
down. Speed is a focal point for the project required by any programmer. On the other
hand, it can be seen that it is fast for many web applications too.
Mobile Development: However Python is strong in desktop and server platforms, that
is it is an excellent server-side language but for the mobile development, Python is not a
very good language which means it is a weak language for mobile development. It is
very rarely used for mobile development. This is the reason very few mobile
applications are built in it like Carbonnelle, which is built in python.
Below are the major features and applications due to which people choose
Python as their first programming language:
Python’s extensibility features allow you to integrate Java as well as .NET components.
You can also invoke C and C++ libraries.
8. Web Development
You can also perform web scraping where you can fetch details from any other
websites. You will also be impressed as many websites such as Instagram, bit bucket,
Pinterest are build on these frameworks only.
7. Artificial Intelligence
6. Computer Graphics
It is also used in game development where you can write the logic of using a module
‘pygame’ which also runs on android devices.
5. Testing Framework
4. Big Data
There are other libraries such as ‘Dask‘ and ‘Pyspark‘ for big data
processing. Therefore, Python is widely used for Big Data where you can easily process
it!
Once the code is checked, it can be used several times. So by automation, you can
automate certain tasks in a program.
2. Data Science
Python also deals with the tabular, matrix as well as statistical data and it even
visualizes it with popular libraries such as ‘Matplotlib’ and ‘Seaborn‘.
x = 20 int
x = 20.5 float
x = 1j complex
"cherry")
x = range(6) range
x = frozenset({"apple", frozenset
"banana", "cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
• Setting the Specific Data Type
• If you want to specify the data type, you can use the
following constructor functions:
• Example Data Type Try it
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
x = dict(name="John", dict
age=36)
x = frozenset(("apple", frozenset
"banana", "cherry"))
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
•
• Python Casting
• x = int(1) # x will be 1
• y = int(2.8) # y will be 2
• z = int("3") # z will be 3
Creating Variables
Variables are containers for storing data values.
Unlike other programming languages, Python has no command for declaring a
variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
Variable Names
• A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables: A variable name
must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
• Assign Value to Multiple Variables
• Python allows you to assign values to multiple variables in one line:
•
• Example
• x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
!= Not equal x != y
apple
banana
for x in range(6):
print(x)
0
1
2
3
4
5
apple
cherry
2
5
8
11
14
17
20
23
26
29
for x in adj:
for y in fruits:
print(x, y)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
1
2
4
5
6
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
*
**
***
****
*****
Using break and continue
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
Current Letter : P
Current Letter : y
Current Letter : t
val in "string":
if val == "i":
continue
print(val)
print("The end")
g
The end
Python - pass Keyword
The pass keyword as name suggests, does nothing. It is used as
a dummy place holder whenever a syntactical requirement of a
certain programming element is to be fulfilled without
assigning any operation. In other words, the pass statement is
simply ignored by the Python interpreter and can be seen as a
null statement. It is generally used as a dummy statement in a
code block, for example in the if or else block.
for num in range(1,6):
if num==3:
pass
else:
print (num)
1
2
4
5
String Literals
String literals in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello".
print("Hello")
print('Hello')
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three
quotes:
a = """NAVIN
JUNEJA
BCCA."""
print(a)
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon,
to return a part of the string.
b="hello world"
print(b[2:5])
llo
b="hello world"
print(b[-5:-2])
wor
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
a="navin"
print(len(a))
5
The strip() method removes any whitespace from the beginning
or the end:
a=" Hello, World! "
print(a.strip())
a = "Hello, World!"
print(a.lower())
a = "Hello, World!"
print(a.upper())
a = "Hello, World!"
print(a.replace("H", "J"))
a = "Hello, World!"
print(a.split(","))
['Hello', ' World!']
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming
language:
• List is a collection which is ordered and changeable. Allows
duplicate members.
• Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
thislist=["banana","apple","cherry"]
print(thislist[1])
apple
thislist=["banana","apple","cherry"]
print(thislist[-1])
cherry
list1=["a","b","c"]
list2=[1,2,3]
list3=list1+list2
print(list3)
thislist=["apple","banana","cherry"]
for x in thislist:
print(x)
apple
banana
cherry
list1=["a","b","c"]
list2=[1,2,3]
for x in list2:
list1.append(x)
print(list1)
['a', 'b', 'c', 1]
['a', 'b', 'c', 1, 2]
['a', 'b', 'c', 1, 2, 3]
list1=["a","b","c"]
list2=[1,2,3]
list1.extend(list2)
print(list1)
['a', 'b', 'c', 1, 2, 3]
list1=["a","b","c"]
list2=list1.copy()
print(list1)
print(list2)
['a', 'b', 'c']
['a', 'b', 'c']
Tuple
A tuple is a collection which is ordered and unchangeable. In
Python tuples are written with round brackets.
thistuple=("apple","banana","cherry")
print(thistuple)
('apple', 'banana', 'cherry')
Dictionary
A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets,
and they have keys and values.
thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
print(thisdict)
thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
thisdict["year"] = 2018
print(thisdict)
thisdict={
"brand":"ford",
"model":"mustang",
"year":1964
}
for x in thisdict:
print(thisdict)
Python Functions
def my_function():
print("Hello from a function")
my_function()
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Emil Refsnes
Tobias Refsnes
Linus Refsnes
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
I am from Sweden
I am from India
I am from Norway
I am from Brazil
def my_function(food):
for x in food:
print(x)
my_function(fruits)
apple
banana
cherry
Arbitrary Arguments
If you do not know how many arguments that will be passed
into your function, add a * before the parameter name in the
function definition.
This way the function will receive a tuple of arguments, and can
access the items accordingly:
def my_function(*kids):
print("The youngest child is " + kids[2])
x = lambda a : a + 10
print(x(5))
A lambda function that sums argument a, b, and c and print the
result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an
anonymous function inside another function.
Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
import mymodule
mymodule.greeting("Jonathan")
Variables in Module
The module can contain functions, as already described, but
also variables of all types (arrays, dictionaries, objects etc):
Import the module named mymodule, and access the person1
dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
29.999999999999996
The following statements show sin, cos and tan ratios for the
angle of 30 degrees (0.5235987755982988 radians):
>>math.sin(0.5235987755982988)
0.49999999999999994
>>>math.cos(0.5235987755982988)
0.8660254037844387
>>>math.tan(0.5235987755982988)
0.5773502691896257
math.log()
The math.log() method returns the natural logarithm of a given
number. The natural logarithm is calculated to the base e.
>>>math.log(10)
2.302585092994046
math.log10()
The math.log10() method returns the base-10 logarithm of the
given number. It is called the standard logarithm.
>>>math.log10(10)
1.0
math.pow()
The math.pow() method receives two float arguments, raises
the first to the second and returns the result. In other words,
pow(4,4) is equivalent to 4**4.
>>>math.pow(2,4)
16.0
>>>2**4
16
math.sqrt()
The math.sqrt() method returns the square root of a given
number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
The following two functions are called representation
functions. The ceil() function approximates the given number to
the smallest integer, greater than or equal to the given floating
point number. The floor() function returns the largest integer
less than or equal to the given number.
>>>math.ceil(4.5867)
5
>>>math.floor(4.5687)
4
What are packages?
We don't usually store all of our files in our computer in the
same location. We use a well-organized hierarchy of directories
for easier access.
Similar files are kept in the same directory, for example, we
may keep all the songs in the "music" directory. Analogous to
this, Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of
modules, we place similar modules in one package and
different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.
Similar, as a directory can contain sub-directories and files, a
Python package can have sub-packages and modules.
A directory must contain a file named __init__.py in order for
Python to consider it as a package. This file can be left empty
but we generally place the initialization code for that package in
this file.
Here is an example. Suppose we are developing a game, one
possible organization of packages and modules could be as
shown in the figure below.
interpreter doesn't execute all the code that exists after the
that.
Common Exceptions
A list of common exceptions that can be thrown from a normal
python program is given below.
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local
or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
#other code:
print("Hi I am other part of the program")
Enter a:10
Enter b:0
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Enter a:10
Enter b:0
can't divide by zero