2. 2
INTRODUCTION TO PYTHON
Python is a general-purpose interpreted, interactive, object-
oriented, and high-level programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was
released in the year 2000
Python is interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before executing
it.
Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the
beginner- level programmers and supports the development of a wide
range of applications.
3. 3
PYTHON FEATURES:
Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms and has
the same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is
no need to compile a program before executing it. You can simply run the
program.
Extensible: Programmers can embed python within their C,C++,Java
script ,ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source
code, and edit it.
High Level Language: When writing programs, programmers concentrate
on solutions of the current problem, no need to worry about the low level
details.
Scalable: Python provides a better structure and support for large
programs than shell scripting.
5. 5
PYTHON INTERPRETER
Interpreter: To execute a program in a high-level language
by translating it one line at a time.
Compiler: To translate a program written in a high-level
language into a low level language all at once, in preparation
for later execution.
6. 6
MODES OF PYTHON INTERPRETER
Python Interpreter is a program that reads and executes
Python code.
It uses 2 modes of Execution.
Interactive mode
Script mode
7. 7
1.INTERACTIVE MODE
Interactive Mode, as the name suggests, allows us to interact with OS
When we type Python statement, interpreter displays the
result(s) immediately.
Advantages:
v Python, in interactive mode, is good enough to learn, experiment or
explore.
v Working in interactive mode is convenient for beginners and
for testing small pieces of code.
Drawback:
v We cannot save the statements and have to retype all the statements
once again to re-run them.
8. 8
In interactive mode, you type Python programs and the interpreter displays
the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is
ready for you to enter code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
9. 9
2. SCRIPT MODE:
In script mode, we type python program in a file and
then use interpreter to execute the content of the file.
Scripts can be saved to disk for future use. Python
scripts have the extension .py, meaning that the
filename ends with .py
Save the code with filename.py and run the
interpreter in script mode to execute the script.
11. 11
INTEGRATED DEVELOPMENT LEARNING ENVIRONMENT
(IDLE):
Is a graphical user interface which is completely written in
Python.
It is bundled with the default implementation of the python
language and also comes with optional part of the Python
packaging.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting
.
12. 12
VALUES AND DATA TYPES
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong
to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values
Python has four standard data types:
13. 13
NUMBERS:
• Number data type stores Numerical Values.
• This data type is immutable [i.e. values/items cannot be changed].
• Python supports integers, floating point numbers and complex
numbers. They are defined as
14. 14
SEQUENCE
A sequence is an ordered collection of items,
indexed by positive integers.
It is a combination of mutable (value can be
changed) and immutable (values cannot be
changed) data types.
There are three types of sequence data type available
in Python, they are
1. Strings
2. Lists
3. Tuples
15. 15
1. STRINGS
A String in Python consists of a series or sequence of
characters - letters, numbers, and special characters.
Strings are marked by quotes:
single quotes (' ') Eg, 'This a string in single quotes‘
double quotes (" ") Eg, "'This a string in double quotes'“
triple quotes(""" """) Eg, This is a paragraph. It is made up
of multiple lines and sentences.""“
Individual character in a string is accessed using a subscript
(index).
Characters can be accessed using indexing and slicing
operations
Strings are immutable i.e. the contents of the string cannot
be changed after it is created.
16. 16
Positive indexing helps in accessing the string from
the beginning.
Negative subscript helps in accessing the string from
the end.
Subscript 0 or –ve n(where n is length of the string)
displays the first element.
Example: A[0] or A[-5] will display “H”
Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”
18. 18
2. LISTS
List is an ordered
sequence of items.
Values in the list are
called elements /
items.
It can be written as a
list of comma-
separated items
(values)
between square brack
ets[ ].
Items in the lists can
be of different data
types.
Operations on list:
• Indexing
• Slicing
• Concatenation
• Repetitions
• Updation,Insertion,
Deletion
19. 19
3. TUPLE:
v A tuple is same as list, except that the set of elements is enclosed in
parentheses instead of square brackets.
v A tuple is an immutable list. i.e. once a tuple has been created, you can't
add elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
v Tuples are faster than lists.
v If the user wants to protect the data from accidental changes, tuple can be
used.
v Tuples can be used as keys in dictionaries, while lists can't.
20. 20
COND…
Altering the tuple data type leads to error. Following error occurs when
user tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
21. 21
MAPPING
This data type is unordered and mutable.
Dictionaries fall under Mappings
Dictionaries:
v Lists are ordered sets of objects, whereas dictionaries are unordered sets.
v Dictionary is created by using curly brackets. i,e. {}
v Dictionaries are accessed via keys and not via their position.
v A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value.
v The values of a dictionary can be any Python data type. So dictionaries are
22. 22
Unordered key-value-pairs (The association of a key and a value is called a key-value
pair )
Dictionaries don't support the sequence operation of the sequence data types like
strings, tuples and lists.
if you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'
23. 23
Data Type Compile Time Run Time
int a=10 a=int(input(“Enter a “))
float a=10.5 a=float(input(“Enter a “))
char a=“NICHE” a=input(“Enter a string”)
List a=[20,30,40,50] a=list(input(“Enter a list”))
Tuple a=(20,30,40,50) a=tuple(input(“Enter a Tuple”))
24. 24
VARIABLES
Variables are containers for storing data values.
A variable allows us to store a value by
assigning it to a name, which can be used later.
Named memory locations to store values.
Programmers generally choose names for their
variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using
it. In Python, we simply assign a value to a
variable and it will exist.
25. 25
CREATING VARIABLES
Python has no command for declaring a variable.
A variable is created the moment you first assign a
value to it.
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any
particular type, and can even change type after they
have been set
x = 4 # x is of type int
x = "Sally" # x is now of type
str
print(x)
26. 26
CASTING
If you want to specify the data type of a variable, this
can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
You can get the data type of a variable with the type() function.
x = 5
y = "John"
print(type(x))
print(type(y))
28. 28
VARIABLE NAMES
A variable can have a short name (like x and y) or a
more descriptive name (age, carname, total_volume).
Rules for Python variables:
A variable name must start with a letter or the
underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and
AGE are three different variables)
29. 29
myvar = “Mech A"
my_var = “Mech B"
_my_var = “Mech C"
myVar = “CSE A"
MYVAR = “CSE B"
myvar2 = “CSE C“
Example
Illegal variable names:
2myvar = “Mech"
my-var = “Mech"
my var = “Mech"
Remember that variable names are case-sensitive
30. 30
MULTI WORDS VARIABLE NAMES
Variable names with more than one word can be
difficult to read.
There are several techniques you can use to make
them more readable:
Camel Case
Each word, except the first, starts with a capital
letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore
character:
my_variable_name = "John"
31. 31
ASSIGN MULTIPLE VALUES
Many Values to Multiple Variables
Python allows you to assign values to multiple variables
in one line:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of
variables matches the number of
values, or else you will get an error.
One Value to Multiple Variables
And you can assign the same value to multiple
variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
32. 32
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python
allows you extract the values into variables. This is
called unpacking.
Example
Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
33. 33
Output Variables
The Python print statement is often used to output
variables.
To combine both text and a variable, Python uses
the + character:
Example
x = "awesome"
print("Python is " + x)
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
Example
x = 5
y = 10
print(x + y)
If you try to combine a string and a
number, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)
34. 34
Global Variables
Variables that are created outside of a function (as in all of the
examples above) are known as global variables.
Global variables can be used by everyone, both inside of
functions and outside.
Example
Create a variable outside of a function, and use it inside
the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function,
this variable will be local, and can only be used inside the
function. The global variable with the same name will remain
as it was, global and with the original value.
35. 35
Example
Create a variable inside a function, with the same name as the
global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
36. 36
The global Keyword
Normally, when you create a variable inside a function, that
variable is local, and can only be used inside that function.
To create a global variable inside a function, you can use
the global keyword.
Example
If you use the global keyword, the variable belongs
to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
37. 37
STATEMENTS AND EXPRESSIONS
A statement is an instruction that the Python interpreter
can execute.
A statement is a unit of code like creating a variable or
displaying a value.
When you type a statement on the command line, Python
executes it. The interpreter does not display any results.
>>> n = 17
>>> print(n)
38. 38
COND…
An expression is a combination of values,
variables, and operators.
If you type an expression at the Python prompt,
the interpreter evaluates it and displays the
result, which is always a value:
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
hifriend
39. 39
KEYWORDS
v Keywords are the reserved words in Python.
v We cannot use a keyword as variable name, function name or any other
identifier.
v They are used to define the syntax and structure of the Python language.
v Keywords are case sensitive.