Unit I
Unit I
UNIT I
Python is a high-level, general-purpose and a very popular programming language. Python
programming language is being used in web development, Machine Learning applications, along with
all cutting edge technology in Software Industry. Python Programming Language is very well suited
for Beginners, also for experienced programmers with other programming languages like C++ and
Java.
It is used for:
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.
1. Python is currently the most widely used multi-purpose, high-level programming language.
2. Python allows programming in Object-Oriented and Procedural paradigms.
1
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
3. Python programs generally are smaller than other programming languages like Java.
Programmers have to type relatively less and indentation requirement of the language, makes
them readable all the time.
4. Python language is being used by almost all tech-giant companies like – Google, Amazon,
Facebook, Instagram, Dropbox, Uber… etc.
5. The biggest strength of Python is huge collection of standard library which can be used for the
following:
Machine Learning
GUI Applications (like Kivy, Tkinter, PyQt etc. )
Web frameworks like Django (used by YouTube, Instagram, Dropbox)
Image processing (like OpenCV, Pillow)
Web scraping (like Scrapy, BeautifulSoup, Selenium)
Test frameworks
Multimedia
Scientific computing
Text processing and many more..
APPLICATIONS OF PYTHON
As mentioned before, Python is one of the most widely used language over the web
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.
2
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
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.
Step 2) Once the download is completed, run the .exe file to install Python. Now click on Install Now.
3
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click on
"Close".
Step 2) Once the download is complete, run the exe for install PyCharm. The setup wizard should
have started. Click “Next”.
Step 3) On the next screen, Change the installation path if required. Click “Next”.
Step 4) On the next screen, you can create a desktop shortcut if you want and click on “Next”.
5
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Step 5) Choose the start menu folder. Keep selected JetBrains and click on “Install”.
Step 7) Once installation finished, you should receive a message screen that PyCharm is installed. If
you want to go ahead and run it, click the “Run PyCharm Community Edition” box first and click
“Finish”.
6
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Step 8) After you click on "Finish," the Following screen will appear.
1. You can select the location where you want the project to be created. If you don’t want to
change location than keep it as it is but at least change the name from “untitled” to something
more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
3. Next Click the “Create” Button.
7
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 4) A new pop up will appear. Now type the name of the file you want (Here we give
“HelloWorld”) and hit “OK”.
Step 6) Now Go up to the “Run” menu and select “Run” to run your program.
Step 7) You can see the output of your program at the bottom of the screen.
Step 8) Don't worry if you don't have Pycharm Editor installed, you can still run the code from the
command prompt. Enter the correct path of a file in command prompt to run the program.
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.
Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is 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.
The following list shows the Python keywords. These are reserved words and you cannot use them
as constant or variable or any other identifier names. All the Python keywords contain lowercase
letters only.
assert finally or
def if return
elif in while
else is with
10
Python provides no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces in
the indentation is variable, but all statements within the block must be indented the same amount. For
example −
if True:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")
Thus, in Python all the continuous lines indented with same number of spaces would form a block.
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example −
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long
as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are
legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up
to the end of the physical line are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print ("Hello, Python!") # second comment
Hello, Python!
You can type a comment on the same line after a statement or expression −
# This is a comment.
# This is a comment, too.
Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comments:
'''
This is a multiline
comment.
12
'''
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
A line containing only whitespace, possibly with a comment, is known as a blank line and Python
totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline
statement.
PYTHON - VARIABLE
Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory.Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals or characters in these variables.
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable. For example −
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result −
100
1000.0
John
13
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.
The data stored in memory can be of many types. For example, a person's age is stored as a numeric
value and his or her address is stored as alphanumeric characters. Python has various standard data
types that are used to define the operations possible on them and the storage method for each of them.
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −
var1 = 1
var2 = 10
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
14
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
long (long integers, they can also be represented in octal and hexadecimal)
Examples
Python allows you to use a lowercase l with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the 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.
15
For example −
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
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. For example −
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found
in Perl and consist of key-value pairs. A dictionary key 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 ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
17
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out
of order"; they are simply unordered.
Sometimes, you may need to perform conversions between the built-in types. To convert between
types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.
1
int(x [,base])
2
long(x [,base] )
3
float(x)
4
complex(real [,imag])
5
str(x)
6
repr(x)
7
eval(str)
8
tuple(s)
Converts s to a tuple.
9
list(s)
Converts s to a list.
10
set(s)
Converts s to a set.
11
dict(d)
12
frozenset(s)
13
chr(x)
14
unichr(x)
15
ord(x)
16
hex(x)
17
oct(x)
Types of Operator
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
operators
// Floor Division - The division of operands where the 9//2 = 4 and 9.0//2.0 = 4.0, -
result is the quotient in which the digits after the 11//3 = -4, -11.0//3 = -4.0
decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity)
−
These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
== If the values of two operands are equal, then the condition (a == b) is not true.
becomes true.
<> If values of two operands are not equal, then condition (a <> b) is true. This is
becomes true. similar to != operator.
> If the value of left operand is greater than the value of right (a > b) is not true.
operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value (a >= b) is not true.
of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of (a <= b) is true.
21
+= Add AND It adds right operand to the left operand and c += a is equivalent to c =
assign the result to left operand c+a
-= Subtract AND It subtracts right operand from the left operand c -= a is equivalent to c =
and assign the result to left operand c-a
*= Multiply AND It multiplies right operand with the left operand c *= a is equivalent to c =
and assign the result to left operand c*a
/= Divide AND It divides left operand with the right operand c /= a is equivalent to c =
and assign the result to left operand c/a
%= Modulus AND It takes modulus using two operands and assign c %= a is equivalent to c =
the result to left operand c%a
//= Floor Division It performs floor division on operators and c //= a is equivalent to c =
assign value to the left operand c // a
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now
in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists
out the bitwise operators supported by Python language with an example each in those, we use the
above two variables (a and b) as operands −
a = 0011 1100
22
b = 0000 1101
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
-----------------
~a = 1100 0011
& Binary AND Operator copies a bit to the result if it (a & b) (means 0000
exists in both operands 1100)
^ Binary XOR It copies the bit if it is set in one operand (a ^ b) = 49 (means 0011
but not both. 0001)
<< Binary Left Shift The left operands value is moved left by
a << 2 = 240 (means
the number of bits specified by the right
1111 0000)
operand.
>> Binary Right Shift The left operands value is moved right by
a >> 2 = 15 (means 0000
the number of bits specified by the right
1111)
operand.
There are following logical operators supported by Python language. Assume variable a holds 10 and
23
and Logical AND If both the operands are true then condition becomes (a and b) is true.
true.
or Logical OR If any of the two operands are non-zero then condition (a or b) is true.
becomes true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below −
not in Evaluates to true if it does not finds a variable x not in y, here not in results in a 1 if
in the specified sequence and false otherwise. x is not a member of sequence y.
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −
[ Show Example ]
The following table lists all operators from highest precedence to lowest.
1
**
2
~+-
Complement, unary plus and minus (method names for the last two are +@ and -
@)
3
* / % //
4
+-
5
>> <<
6
&
Bitwise 'AND'
7
^|
8
<= < > >=
Comparison operators
9
<> == !=
Equality operators
10
= %= /= //= -= += *= **=
Assignment operators
11
is is not
Identity operators
12
in not in
Membership operators
13
not or and
Logical operators
PYTHON- STATEMENTS
The print statement
You are now ready to start typing statements into the file hello.py. These statements will make up a
program. Each statement gives the computer an instruction. A statement might tell the computer to put
something on the screen (which is called “printing”), it might prompt the user to type something, or it
might tell the computer to remember some information so that we can recall it and use it later in the
program, etc.
Let’s try to write a program that makes some text show up in the Shell window. So, let’s type the
following into your new file.
print("Hello")
26
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
input ( prompt )
input ( ) : This function first takes the input from the user and then evaluates the expression,
which means Python automatically identifies whether user entered a string or a number or list. If
the input provided is not correct then either syntax error or exception is raised by python. For
example –
val = input("Enter your value: ")
print(val)
Output:
Assignment statements
An assignment statement is a statement that creates or updates the value of a variable. Our input
statement in the previous example was also an assignment statement because it created the variable
named firstname.
Let’s look at more examples of assignment statements. Consider the following. I live on an acreage,
and we have a barn where cats tend to gather. We didn’t have to buy any cats; they just show up. It’s
good they are around because they eat mice and we don’t like mice.
Suppose we want to store the number of cats we have in our barn at any given time, and suppose we
currently have six cats. To store this information in a Python variable, we would type the following.
cats = 6
To experiment with what’s happening here, let’s add two more lines so that your code now looks
like
cats = 6
print(cats)
print("cats")
27
Can you guess what will happen when you run this code? It is very important to be able to read code
line by line to figure out in your mind what will happen. Later on, when you’re programming and
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH
something doesn’t work right, you’ll need to look at your code line by line to make sure that it
makes logical sense. This code will print
6
cats
The eval() method parses the expression passed to this method and runs python expression (code)
within the program.In simple terms, the eval() function runs the python code (which is passed as an
argument) within the program.
The eval() function evaluates the specified expression, if the expression is a legal Python statement,
it will be executed.
Syntax
Parameter Values
Parameter Description
Syntax
28
Parameter Values
Parameter Description
object Required. If only one parameter is specified, the type() function returns the type
of this object
dict Optional. Specifies the namespace with the definition for the class
Example
Result:
<class 'tuple'>
<class 'str'>
<class 'int'>
*********************************
29
Page