0% found this document useful (0 votes)
51 views29 pages

Unit I

Python is a popular, high-level programming language used for web development, machine learning, and other applications. It has a simple syntax and can be used across platforms for tasks like web development, software development, mathematics, and system scripting. Python code is often shorter than other languages, and it can be treated procedurally, object-orientedly, or functionally. Popular uses of Python include web development with Django, scientific computing, and machine learning.

Uploaded by

Michael godson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views29 pages

Unit I

Python is a popular, high-level programming language used for web development, machine learning, and other applications. It has a simple syntax and can be used across platforms for tasks like web development, software development, mathematics, and system scripting. Python code is often shorter than other languages, and it can be treated procedurally, object-orientedly, or functionally. Popular uses of Python include web development with Django, scientific computing, and machine learning.

Uploaded by

Michael godson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

PYTHON

PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

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.

Below are some facts about Python Programming Language:

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.

HOW TO INSTALL PYTHON ON WINDOWS [PYCHARM IDE]


PyCharm is a cross-platform editor developed by JetBrains. Pycharm provides all the tools you need
for productive Python development.Below are the detailed steps for installing Python and PyCharm
How to Install Python IDE
Below is a step by step process on how to download and install Python on Windows:
Step 1) To download and install Python, visit the official website of
Python https://www.python.org/downloads/ and choose your version. We have chosen Python
version 3.6.3

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 3) You can see Python installing at this point.

Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click on
"Close".

How to Install Pycharm


Here is a step by step process on how to download and install Pycharm IDE on Windows:
Step 1) To download PyCharm visit the website https://www.jetbrains.com/pycharm/download/ and
Click the "DOWNLOAD" link under the Community Section.
4
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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 6) Wait for the installation to finish.

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.

Hello World: Create your First Python Program


In the last tutorial, we completed our Python installation and setup. It's time to create your first
program.
Creating First Program
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To create a new
project, click on “Create New Project”.

Step 2) You will need to select a location.

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 5) Now type a simple program - print (‘Hello World!’).


8
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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.

The output of the code would be


9
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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.

Here are naming conventions for Python identifiers −

 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.

RESERVED WORDS/ KEYWORDS

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.

and exec not

assert finally or

break for pass

class from print

continue global raise

def if return

del import try

elif in while

else is with
10

except lambda yield


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

LINES AND INDENTATION

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")

However, the following block generates an error −

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 −

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']
11
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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

This produces the following result −

Hello, Python!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

# 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

Using Blank Lines

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.

Assigning Values to 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 −

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

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.

STANDARD DATA TYPES

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.

Python has five standard data types −

 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

Python supports four different numerical types −

 int (signed integers)

 long (long integers, they can also be represented in octal and hexadecimal)

 float (floating point real values)

 complex (complex numbers)

Examples

Here are some examples of numbers −

int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

 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.

 A complex number consists of an ordered pair of real floating-point numbers denoted by x +


yj, where x and y are the real numbers and j is the imaginary unit.

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

str = 'Hello World!'


print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

This will produce the following result −

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 −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print (list) # Prints complete list


print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
16

print (list + tinylist) # Prints concatenated lists


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

This produce the following result −

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

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"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
17

['sales', 6734, 'john']


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out
of order"; they are simply unordered.

Data Type Conversion

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.

Sr.No. Function & Description

1
int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

2
long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

3
float(x)

Converts x to a floating-point number.

4
complex(real [,imag])

Creates a complex number.

5
str(x)

Converts object x to a string representation.

6
repr(x)

Converts object x to an expression string.

7
eval(str)

Evaluates a string and returns an object.


18
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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)

Creates a dictionary. d must be a sequence of (key,value) tuples.

12
frozenset(s)

Converts s to a frozen set.

13
chr(x)

Converts an integer to a character.

14
unichr(x)

Converts an integer to a Unicode character.

15
ord(x)

Converts a single character to its integer value.

16
hex(x)

Converts an integer to a hexadecimal string.

17
oct(x)

Converts an integer to an octal string.


19
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

PYTHON - BASIC OPERATORS


Operators are the constructs which can manipulate the value of operands.Consider the expression 4
+ 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

Python language supports the following types of operators.

 Arithmetic Operators

 Comparison (Relational) Operators

 Assignment Operators

 Logical Operators

 Bitwise Operators

 Membership Operators

 Identity Operators

Let us have a look on all operators one by one.

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b%a=0


and returns remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the power 20


20
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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)

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

== 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.


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

right operand, then condition becomes true.


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

= Assigns values from right side operands to left c = a + b assigns value of


side operand a + b into c

+= 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

**= Exponent Performs exponential (power) calculation on c **= a is equivalent to c


AND operators and assign value to the 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

Python Bitwise Operators

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&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language

Operator Description Example

& Binary AND Operator copies a bit to the result if it (a & b) (means 0000
exists in both operands 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011


1101)

^ Binary XOR It copies the bit if it is set in one operand (a ^ b) = 49 (means 0011
but not both. 0001)

~ Binary Ones (~a ) = -61 (means 1100


Complement It is unary and has the effect of 'flipping' 0011 in 2's complement
bits. form due to a signed
binary number.

<< 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.

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10 and
23

variable b holds 20 then


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Operator Description Example

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 Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below −

Operator Description Example

in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a


specified sequence and false otherwise. member of sequence y.

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.

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −

[ Show Example ]

Operator Description Example

is Evaluates to true if the variables on either side of


x is y, here is results in 1 if id(x)
the operator point to the same object and false
equals id(y).
otherwise.
24
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

is not Evaluates to false if the variables on either side of


x is not y, here is not results in 1
the operator point to the same object and true
if id(x) is not equal to id(y).
otherwise.

PYTHON OPERATORS PRECEDENCE

The following table lists all operators from highest precedence to lowest.

Sr.No. Operator & Description

1
**

Exponentiation (raise to the power)

2
~+-

Complement, unary plus and minus (method names for the last two are +@ and -
@)

3
* / % //

Multiply, divide, modulo and floor division

4
+-

Addition and subtraction

5
>> <<

Right and left bitwise shift

6
&

Bitwise 'AND'

7
^|

Bitwise exclusive `OR' and regular `OR'


25
Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

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

The input statement


Developers often have a need to interact with users, either to get data or to provide some sort of
result. Most programs today use a dialog box as a way of asking the user to provide some type of
input. While Python provides us with inbuilt functions to read the input from the keyboard.

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

Python eval() Function

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

eval(expression, globals, locals)

Parameter Values

Parameter Description

expression A String, that will be evaluated as Python code

globals Optional. A dictionary containing global parameters

locals Optional. A dictionary containing local parameters

Python type() Function

The type() function returns the type of the specified object

Syntax
28

type(object, bases, dict)


Page
PYTHON
PRORAMMING YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES 2019 ONWARS BATCH

Parameter Values

Parameter Description

object Required. If only one parameter is specified, the type() function returns the type
of this object

bases Optional. Specifies the base classes

dict Optional. Specifies the namespace with the definition for the class

Example

Return the type of these objects:

a = ('apple', 'banana', 'cherry')


b = "Hello World"
c = 33
x = type(a)
y = type(b)
z = type(c)

Result:

<class 'tuple'>
<class 'str'>
<class 'int'>

*********************************
29
Page

You might also like