PGDCA Python Notes UNIT - 1
PGDCA Python Notes UNIT - 1
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.
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.
C:\>python
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.
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 −
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.
assert finally or
def if return
else is with
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
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.
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 −
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
Python Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise 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
= 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
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
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:
is not Returns true if both variables are not the same object x is not y
not in Returns True if a sequence with the specified value is not present x not in y
in the object
<< 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
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])