0% found this document useful (0 votes)
124 views

PGDCA Python Notes UNIT - 1

Uploaded by

karnabahadurpal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views

PGDCA Python Notes UNIT - 1

Uploaded by

karnabahadurpal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Notes

PGDCA
Unit – I
Jiwaji University
Year – 2019 – 2020

1. Introduction to Python
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and
first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant
whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical
code for small and large-scale projects.
Python is dynamically typed and garbage-collected. It supports multiple programming paradigms,
including procedural, object-oriented, and functional programming. Python is often described as a "batteries
included" language due to its comprehensive standard library.
Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0, released in 2000,
introduced features like list comprehensions and a garbage collection system capable of collecting reference cycles.
Python 3.0, released in 2008, was a major revision of the language that is not completely backward-compatible,
and much Python 2 code does not run unmodified on Python 3.
Python interpreters are available for many operating systems. A global community of programmers develops and
maintains CPython, an open source reference implementation. A non-profit organization, the Python Software
Foundation, manages and directs resources for Python and CPython development.
Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum
in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.

What can Python do?

 web development (server-side),


 software development,
 mathematics,
 system scripting.

 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-orientated way or a functional way.

2. History of Python
The programming language Python was conceived in the late 1980s, and its implementation was started in
December 1989 by Guido van Rossum at CWI in the Netherlands as a successor to ABC capable of exception
handling and interfacing with the Amoeba operating system. Van Rossum is Python's principal author, and his
continuing central role in deciding the direction of Python 2.0 was released on October 16, 2000, with many major
new features, including a cycle-detecting garbage collector (in addition to reference counting) for memory
management and support for Unicode. However, the most important change was to the development process itself,
with a shift to a more transparent and community-backed process.
Python 3.0, a major, backwards-incompatible release, was released on December 3, 2008 after a long period of
testing. Many of its major features have also been backported to the backwards-compatible, while by now
unsupported, Python 2.6 and 2.7.
4. Python Features

1) Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly and high level programming
language.

2) Expressive Language: Python language is more expressive means that it is more understandable and readable.

3) Interpreted Language: Python is an interpreted language i.e. interpreter executes the code line by line at a time.
This makes debugging easy and thus suitable for beginners.

4) Cross-platform Language: Python can run equally on different platforms such as Windows, Linux, Unix and
Macintosh etc. So, we can say that Python is a portable language.

5) Free and Open Source: Python language is freely available at offical web address.The source-code is also
available. Therefore it is open source.

6) Object-Oriented Language: Python supports object oriented language and concepts of classes and objects come
into existence.

7) Extensible: It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our python code.

8) Large Standard Library: Python has a large and broad library and prvides rich set of module and functions for
rapid application development.

9) GUI Programming Support: Graphical user interfaces can be developed using Python.

10) Integrate: It can be easily integrated with languages like C, C++, JAVA etc.

3. Setting up path for python


If you’ve installed Python in Windows using the default installation options, the path to the Python executable
wasn’t added to the Windows Path variable. The Path variable lists the directories that will be searched for
executables when you type a command in the command prompt. By adding the path to the Python executable, you
will be able to access python.exe by typing the python keyword (you won’t need to specify the full path to the
program).
Consider what happens if we enter the python command in the command prompt and the path to that executable
is not added to the Path variable:

C:\>python

'python' is not recognized as an internal or external command,

operable program or batch file.

As you can see from the output above, the command was not found. To run python.exe, you need to specify the
full path to the executable:

C:\>C:\Python34\python --version

Python 3.4.3

To add the path to the python.exe file to the Path variable, start the Run box and enter sysdm.cpl:

This should open up the System Properties window. Go to the Advanced tab and click the Environment
Variables button:
In the System variable window, find the Path variable and click Edit:
Position your cursor at the end of the Variable value line and add the path to the python.exe file, preceeded
with the semicolon character (;). In our example, we have added the following value: ;C:\Python34

Close all windows. Now you can run python.exe without specifying the full path to the file:

C:>python --version

Python 3.4.3

If you get the ‘python’ is not recognized as an internal or external command, operable program or batch
file. error, there is something wrong with your Path variable. Note also that you will have to reopen all command
prompt windows in order for changes to the Path variable take effect.

4. Internal working of Python


Python is an object oriented programming language like Java. Python is called an interpreted language. Python
uses code modules that are interchangeable instead of a single long list of instructions that was standard for
functional programming languages. The standard implementation of python is called “cpython”. It is the default
and widely used implementation of the Python.
Python doesn’t convert its code into machine code, something that hardware can understand. It actually converts
it into something called byte code. So within python, compilation happens, but it’s just not into a machine language.
It is into byte code and this byte code can’t be understood by CPU. So we need actually an interpreter called the
python virtual machine. The python virtual machine executes the byte codes.

The Python interpreter performs following tasks to execute a Python program:

The Python language has many similarities to Perl, C, and Java. However, there are some definite differences
between the languages.
First Python Program
Type the following text at the Python prompt and press the Enter −

>>> print ("Hello, Python!")

If you are running new version of Python, then you would need to use print statement with parenthesis as in print
("Hello, Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!

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

except lambda yield

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"

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']

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

#!/usr/bin/python

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

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 also delete the reference to a number object by using the del statement. The syntax of the del statement
is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
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. For example −

#!/usr/bin/python

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

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

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

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators

Comparison operators are used to compare two values:


Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object,
with the same memory location:

Operator Description Example

is Returns true if both variables are the same object x is y

is not Returns true if both variables are not the same object x is not y

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is present in x in y


the object

not in Returns True if a sequence with the specified value is not present x not in y
in the object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description

& AND Sets each bit to 1 if both bits are 1


| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off

>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmos

Python Input, Output and

This tutorial focuses on two built-in functions print() and input() to perform I/O task in Python. Also, you
will learn to import modules and use them in your program.

Python provides numerous built-in functions that are readily available to us at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output operations respectively.
Let us see the output section first.
print('This sentence is output to the screen')
# Output: This sentence is output to the screen
a=5
print('The value of a is', a)
# Output: The value of a is 5

Python Input
Up till now, our programs were static. The value of variables were defined or hard coded into the source code.
To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow
this. The syntax for input() is

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.


1. >>> num = input('Enter a number: ')
2. Enter a number: 10
3. >>> num
4. '10'

You might also like