Unit-I

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

iamriteshkandari 9259069231 riteshkandarics@gmail.

com

UNIT-I

Introduction
• Python is a simple, general purpose, high level and Object-oriented Programming
• Python is an interpreted scripting language as its programs are executed by an
interpreter.
• Python support multiple programming pattern, including Object Oriented,
functional or procedural programming styles.
• Thus, Python interpreter should be installed on the computer system to write
and run Python programs.

Overview of Python
Python programming language was developed by Guido Van Rossum in February
1991. Python is based on or influenced with two programming language:
➢ ABC Language, a teaching language created as a replacement of BASIC, and
➢ Modula-3
• Python is an easy to learn yet powerful Object-oriented Programming language. It
is a very high-level programming language yet as powerful as many other middle
levels not so high-level programming language like C, C++, Java etc.
• Python is a general-purpose high-level programming language. It is an open-
source language, released under a GPL-compatible license. Python Software
Foundation (PSF), a non-profit organization, holds the copyright of Python.
• Guido Van Rossum conceived Python in the late 1980s. It was released in 1991 at
Centrum Wiskunde & Informatica (CWI) in the Netherlands as a successor to the
ABC language. He named this language after a popular comedy show called'Monty
Python's Flying Circus' (and not after Python-the snake).
• The Python programming language is an object-oriented language, which means
that it can model real-world entities. It is also dynamically-typed because it carries
out type-checking at runtime. It does so to make sure that the type of construct
matches what we expect it to be. The distinctive feature of Python is that it is an
interpreted language. The Python IDLE (Integrated Development Environment)
executes instructions one line at a time. CPython, written in C, is the mostcommon
implementation of Python.

1
iamriteshkandari 9259069231 riteshkandarics@gmail.com

Compiler and Interpreter in Python


A compiler is a program that translates a source language or high-level programming
language (for example, Java, C++) into a target machine code (binary bits – 1 and 0)
that the CPU can process and understand. The program to be translated is written
inside an editor and are known as source statements. The act of translating source
code to machine or binary code is known as compilation.
An interpreter is a program which also converts a high-level programming language
(like Python, PHP, Perl) into machine code. Although similar to a compiler, the way
that code is executed is different for both. Unlike a compiler that simply converts the
source code to machine code, an interpreter can be run directly as an executable
program. Contrary to a compiler, it converts source code to machine code when the
program is running and not before the program runs.
Interpreters do not produce any intermediary object code like compilers. In
interpreters, the source code is compiled and executed at the same time.

Python Interpreter
The compilation process to bytecode is entirely implicit. This means that you never
invoke the compiler. Instead, you simply run a .py file. The lack of an explicit compile
step is why the Python executable is known as the Python interpreter. The first step of
an interpreter is to read a Python code or instruction. It then checks the syntax of each
line and verifies if the instruction is well-formatted. The interpreter can display the
errors of each line one by one.
An important feature of Python is its interactive prompt. A Python statement can be
typed and immediately executed. Most of the compiled languages may not have this
interactivity. Python is compiled to bytecode and this bytecode is immediately
executed without an explicit compile step.

2
iamriteshkandari 9259069231 riteshkandarics@gmail.com

Python Shell (Interactive Mode)


In interactive mode, instructions are given in front of Python Prompt (e.g., >>>) in
python Shell. Python carries out the given instruction and show the result there itself.
Python provides a Python Shell (also known as Python Interactive Shell) which is used
to execute a single Python command and get the result.
Python Shell waits for the input command from the user. As soon as the user enters
the command, it executes it and displays the result.
Now, you can enter a single statement and get the result. For example, enter a simple
expression like 2+ 3, press enter and it will display the result in the next line, as shown
below

Script Mode
In script mode, Python instructions are stored in a file generally with .py extension and
are executed together in one go as a unit. The save instructions are known as Python
Script or Python Program.
To execute multiple statements, create a Python file with extension .py, and write
Python scripts (multiple statements).

print ("This is Python Script.")


print ("Welcome to Python Tutorial by Ritesh Kandari")
Save it as myPythonScript.py, and run this file.

3
iamriteshkandari 9259069231 riteshkandarics@gmail.com

Characteristics of Python
1) Platform independent
Python is platform independent. The python code can be used for any operating
system like Windows, Unix, Linux, and Mac. There is no need to write different
code for the different OS.
2) Interpreted
The python code does not need to compile as required for other languages. Python
code automatically converts the source code into byte code internally and the
code is executed line by line not at once, so it takes more time to execute the code
for the application.
3) Simple
The Python language is simple that can be easily coded and read. The syntax
of python is really simple and can be learned easily.
4) Robust
Python is robust
5) High-level language
It is a high-level language used for scripting. It means one does not need to
remember the system architecture and no need for managing the memory as well.
6) Rich library support
Python can be integrated with other libraries that help in making the functionality
work for you. Do not need to write the extra code for that.
7) Embeddable
Python source code can be put into a different language to use. This helps in
integrating the functionality of the python program with other languages.

Advantages of Python
1. It is open source and readily available to use.
2. It is easy to learn and explore.
3. Third party modules can be easily integrated.
4. It is high level and object-oriented programming language
5. It is interactive and portable.
6. Applications can be run at any platform.
7. It is a dynamically typed language.

4
iamriteshkandari 9259069231 riteshkandarics@gmail.com

8. It has great online support and community forums.


9. It has a user-friendly data structure.
10. It has extensive support libraries.
11. It is interpreted language.
12. Python provides database connectivity.
13. It improves programmer productivity.

Disadvantages of Python
1. Not the fastest language
2. Lesser libraries than C, Java, Perl
3. Not strong on Type Binding
4. Not easily Convertible
5. It has limitations with database access.
6. It throws run time issues that cause the issue for the programmers.
7. It consumes more memory because of dynamically typed language.
8. Need more maintenance of application and code.

Structure of a Python Program


A python program constitutes several elements such as statements, expressions,
functions comments etc., which are synchronized in the manner as shown below:

Let us see the several components of a basic Python program.

5
iamriteshkandari 9259069231 riteshkandarics@gmail.com

As shown in snippet given below, the several components that a Python program holds
are:
➢ Expressions: An expression represents something, like a number, a string, or an
element. Any value is an expression.
➢ Statements: Anything that does something is a statement. Any assignment to a
variable or function call is a statement. Any value contained in that statement
is an expression.
➢ Comments: Comments are the additional information provided against a
statement or a chunk of code for the better clarity of the code. Interpreter
ignores the comments and does not count them in commands.
Symbol used for writing comments include Hash (#) or Triple Double Quotation
marks (“”” or ‘’’).
➢ Functions: Function is a set of instructions defined under a particular name,
which once written can be called whenever and wherever required.
➢ Blocks: A block refers to a group of statements which are part of another
statement or function. All statements inside a block are indented at the same
level.

6
iamriteshkandari 9259069231 riteshkandarics@gmail.com

Indentation in Python
Indentation is a very important concept of Python because without proper indenting
the Python code, you will end up seeing IndentationError and the code will not get
compiled.
Indentation
In simple terms indentation refers to adding white space before a statement. But the
question arises is it even necessary?
To understand this consider a situation where you are reading a book and all of a
sudden all the page numbers from the book went missing. So you don’t know, where
to continue reading and you will get confused. This situation is similar with Python.
Without indentation, Python does not know which statement to execute next or which
statement belongs to which block. This will lead to IndentationError.
Python indentation is a way of telling a Python interpreter that the group of
statements belongs to a particular block of code. A block is a combination of all these
statements. Block can be regarded as the grouping of statements for a specific
purpose. Most of the programming languages like C, C++, Java use braces { } to define
a block of code.
Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the
same block of code. If a block has to be more deeply nested, it is simply indented
further to the right. You can understand it better by looking at the following lines of
code.
Note: Python uses 4 spaces as indentation by default. However, the number of spaces
is up to you, but a minimum of 1 space has to be used.

Python program showing indentation


site = ‘imt'
if site == ‘imt':
print(‘Welcome to IMT College.')
else:
print(‘Good Bye.')
print('All set !')

7
iamriteshkandari 9259069231 riteshkandarics@gmail.com

The lines print(‘Welcome to IMT College.') and print(‘Good Bye.’) are two separate
code blocks. The two blocks of code in our example if-statement are both indented
four spaces. The final print(‘All set!’) is not indented, and so it does not belong to the
else-block.

Python Variables
• Variable is a name that is used to refer to memory location. Python variable is
also known as an identifier and used to hold value.
• In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
• Variable names can be a group of both the letters and digits, but they have to
begin with a letter or an underscore.
• It is recommended to use lowercase letters for the variable name. Rahul and
rahul both are two different variables.

Python Keywords: A keyword is a word having special meaning reserved by


programming language. Keywords are the words that convey a special meaning to the
language compiler/interpreter. These are reserved for special purpose and must not
be used as normal identifier names.
The list of all the keywords is given below.

8
iamriteshkandari 9259069231 riteshkandarics@gmail.com

Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
1) Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A
to Z) or digits (0 to 9) or an underscore _.
2) An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid
name.
3) Keywords cannot be used as identifiers. e.g., global = 1
4) We cannot use special symbols like @, #, $, % etc. in our identifier. e.g., a@ = 0
5) An identifier can be of any length.

Python Data Types


Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and
variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
1) Numeric
2) Sequence Type
3) Boolean
4) Set
5) Dictionary

9
iamriteshkandari 9259069231 riteshkandarics@gmail.com

1) Numeric
In Python, numeric data type represents the data which has numeric value. Numeric
value can be integer, floating number or even complex numbers. These values are
defined as int, float and complex class in Python.
➢ Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fraction or decimal). In Python there is no limit to how
long an integer value can be.
➢ Float – This value is represented by float class. It is a real number with floating
point representation. It is specified by a decimal point. Optionally, the character
e or E followed by a positive or negative integer may be appended to specify
scientific notation.
➢ Complex Numbers – Complex number is represented by complex class. It is
specified as (real part) + (imaginary part) j. For example – 2+3j

2) Sequence Type
In Python, sequence is the ordered collection of similar or different data types.
Sequences allows to store multiple values in an organized and efficient fashion. There
are several sequence types in Python –
a) String
b) List
c) Tuple
a) String: In Python, Strings are arrays of bytes representing Unicode characters. A
string is a collection of one or more characters put in a single quote, double-quote
or triple quote. In python there is no character data type, a character is a string of
length one. It is represented by str class.
Creating String: Strings in Python can be created using single quotes or double
quotes or even triple quotes.
b) List: Lists are just like the arrays, declared in other languages which is a ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type.
Creating List: Lists in Python can be created by just placing the sequence inside the
square brackets [].

10
iamriteshkandari 9259069231 riteshkandarics@gmail.com

c) Tuple: Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e., tuples cannot be
modified after it is created. It is represented by tuple class.
Creating Tuple: In Python, tuples are created by placing a sequence of values
separated by ‘comma’ with or without the use of parentheses for grouping of the
data sequence. Tuples can contain any number of elements and of any data type
(like strings, integers, list, etc.).

3) Boolean
Data type with one of the two built-in values, True or False. Boolean objects that
are equal to True are truthy (true), and those equal to False are falsy (false). But
non-Boolean objects can be evaluated in Boolean context as well and determined
to be true or false. It is denoted by the class bool.

4) Set
In Python, Set is an unordered collection of data type that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it
may consist of various elements.
Creating Sets: Sets can be created by using the built-in set () function with an
iterable object or a sequence by placing the sequence inside curly braces,
separated by ‘comma’. Type of elements in a set need not be the same, various
mixed-up data type values can also be passed to the set.

5) Dictionary
Dictionary in Python is an unordered collection of data values, used to store data
values like a map, which unlike other Data Types that hold only single value as an
element, Dictionary holds key: value pair.
Key-value is provided in the dictionary to make it more optimized. Each key-value
pair in a Dictionary is separated by a colon: whereas each key is separated by a
‘comma’.
Creating Dictionary: In Python, a Dictionary can be created by placing a sequence
of elements within curly {} braces, separated by ‘comma’. Values in a dictionary
can be of any data type and can be duplicated, whereas keys can’t be repeated

11
iamriteshkandari 9259069231 riteshkandarics@gmail.com

and must be immutable. Dictionary can also be created by the built-in function dict
(). An empty dictionary can be created by just placing it to curly braces {}.

Literals in Python
Literals (often referred to as Constant values) are data items that have a fixed value.
Python allows several kinds of literals:
a) String literals
b) Numeric literals
c) Boolean literals
d) Special literal None
e) Literal Collections

a) String literals: A string literal is a sequence of characters surrounded by quotes


(single or double or triple quotes). For example, ‘a’, ‘abc’, “abc” are all string
literals in Python.
Python allows you to have certain nongraphic-characters in String values.
Nongraphic characters are those characters that cannot be typed directly from
keyboard e.g., backspace, tabs, carriage return etc. These nongraphic-characters
can be represented by using escape sequences. An escape sequence is
represented by a backslash (\) followed by one or more characters.

Escape Non-Graphic Escape Non-Graphic


Sequence Character Sequence Character
\\ Backslash (\) \t Horizontal tab
\’ Single quote (‘) \n New line
\” Double quote (“) \r Carriage return

String Types in Python


Python allow you to have two string types:
i. Single line strings
ii. Multiline strings

12
iamriteshkandari 9259069231 riteshkandarics@gmail.com

b) Numeric literals: They are immutable and there are three types of numeric
literal:
i. Integer
ii. Float
iii. Complex.

• Integer: Both positive and negative numbers including 0. There should not be
any fractional part.
• Float: These are real numbers having both integer and fractional parts.
• Complex Literal: The numerals will be in the form of a+bj, where ‘a‘ is the real
part and ‘b‘ is the complex part.

c) Boolean literals: There are only two boolean literals in Python. They
are true and false.
d) Special literal None: The None literal is used to indicate absence of value. It is
also used to indicate the ends of list in python.
d) Literal Collections: There are four different types of literal collections
i. List literals
ii. Tuple literals
iii. Dict literals
iv. Set literals

i. List literals
List contains items of different data types. The values stored in List are separated by
comma (,) and enclosed within square brackets ([]). We can store different types of
data in a List. Lists are mutable.
# List literals
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)

13
iamriteshkandari 9259069231 riteshkandarics@gmail.com

ii. Tuple literals


A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and
each element is separated by the comma(,). It is immutable.
Example:
# Tuple literals
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)
print(odd_number)

iii. Dict literals


Dictionary stores the data in the key-value pair. It is enclosed by curly-braces ‘{}‘ and
each pair is separated by the commas(,). We can store different types of data in a
dictionary. Dictionaries are mutable.
Example:
# Dict literals
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
information = {'name': 'amit', 'age': 20, 'ID': 20}
print(alphabets)
print(information)

iv. Set literals


Set is the collection of the unordered data set. It is enclosed by the {} and each element
is separated by the comma (,).
Example: we can create a set of vowels and fruit
# Set literals
vowels = {'a', 'e', 'i', 'o', 'u'}
fruits = {"apple", "banana", "cherry"}
print(vowels)
print(fruits)

14

You might also like