SlideShare a Scribd company logo
Introduction to Python
PRESENTED BY
G.ALAMELU, MCA.,
E.M.G YADAVA WOMENS COLLEGE
Why should we learn Python?
 Python is a higher level programming language.
 Its syntax allows programmers to express concepts in
fewer lines of code.
 Python is a programming language that lets you work
quickly and integrate systems more efficiently.
 One can plot figures using Python.
 One can perform symbolic mathematics easily using
Python.
 It is available freely online.
Python versions
Python was first released on February 20, 1991 and later on developed by
Python Software Foundation.
Major Python versions are – Python 1, Python 2 and Python 3.
• On 26th January 1994, Python 1.0 was released.
• On 16th October 2000, Python 2.0 was released with many new
features.
• On 3rd December 2008, Python 3.0 was released with more testing and
includes new features.
Latest version - On 2nd
October 2023, Python 3.12 was released.
To check your Python version
i) For Linux OS type python -V in the terminal window.
ii) For Windows and MacOS type import sys print(sys.version) in the
interactive shell.
Searching for
Python
Downloading
Python
Python Interpreter
The program that translates Python instructions and then executes
them is the Python interpreter. When we write a Python program,
the program is executed by the Python interpreter. This interpreter
is written in the C language.
There are certain online interpreters like
https://ide.geeksforgeeks.org/,
http://ideone.com/ ,
http://codepad.org/
that can be used to start Python without installing an interpreter.
Python IDLE
Python interpreter is embedded in a number of larger programs that
make it particularly easy to develop Python programs. Such a
programming environment is IDLE
( Integrated Development and Learning Environment).
It is available freely online. For Windows machine IDLE
(Integrated Development and Learning Environment) is installed
when you install Python.
Running Python
There are two modes for using the Python interpreter:
1) Interactive Mode
2) Script Mode
Options for running the program:
• In Windows, you can display your folder contents, and
double click on madlib.py to start the program.
• In Linux or on a Mac you can open a terminal window,
change into your python directory, and enter the command
python madlib.py
Interactive shell
IDLE shell
Running Python
1) in interactive mode:
>>> print("Hello Teachers")
Hello Teachers
>>> a=10
>>> print(a)
10
>>> x=10
>>> z=x+20
>>> z
30
Running Python
2) in script mode:
Programmers can store Python script source code in a file
with the .py extension, and use the interpreter to execute the
contents of the file.
For UNIX OS to run a script file MyFile.py you have to type:
python MyFile.py
Data Types
Python has various standard data types:
 Integer [ class ‘int’ ]
 Float [ class ‘float’ ]
 Boolean [ class ‘bool’ ]
 String [ class ‘str’ ]
Integer
Int:
For integer or whole number, positive or negative, without decimals of
unlimited length.
>>> print(2465635468765)
2465635468765
>>> print(0b10) # 0b indicates binary number
2
>>> print(0x10) # 0x indicates hexadecimal number
16
>>> a=11
>>> print(type(a))
<class 'int'>
Float
Float:
Float, or "floating point number" is a number, positive or negative.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
>>> print(0.00000045)
4.5e-07
>>> y=2.8
>>> print(type(y))
<class 'float'>
Boolean and String
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
>>> print(‘Science college’)
Science college
>>> type("My college")
<class 'str'>
Variables
One can store integers, decimals or characters in variables.
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)
a= 100 # An integer assignment
b = 1040.23 # A floating point
c = "John" # A string
List, Tuple, Set, Dictionary
Four built-in data structures in Python:-
list, tuple, set, dictionary
- each having qualities and usage different from the other three.
List is a collection of items that is written with square brackets. It is mutable,
ordered and allows duplicate members. Example: list = [1,2,3,'A','B',7,8,[10,11]]
Tuple is a collection of objects that is written with first brackets. It is immutable.
Example: tuple = (2, 1, 10, 4, 7)
Set is a collection of elements that is written with curly brackets. It is unindexed and
unordered. Example: S = {x for x in 'abracadabra' if x not in 'abc'}
Dictionary is a collection which is ordered, changeable and does not allow duplicates.
It is written with curly brackets and objects are stored in key: value format.
Example: X = {1:’A’, 2:’B’, 3:’c’}
print function
>>>type(print)
Output:
builtin_function_or_method
>>>print( ‘Good morning’ ) or print(“Good morning”)
Output:
Good morning
>>>print(“Workshop”, “on”, “Python”) or print(“Workshop on Python”)
Output:
Workshop on Python
print function
>>>print(‘Workshop’, ‘on’, ‘Python’, sep=’n’)
# sep=‘n’ will put each word in a new line
Output:
Workshop
on
Python
>>>print(‘Workshop’, ‘on’, ‘Python’, sep=’, ’)
# sep=‘, ’ will print words separated by ,
Output:
Workshop, on, Python
print function
%d is used as a placeholder for integer value.
%f is used as a placeholder for decimal value.
%s is used as a placeholder for string.
a = 2
b = ‘tiger’
print(a, ‘is an integer while’, b, ‘is a string.’)
Output:
2 is an integer while tiger is a string.
Alternative way:
print(“%d is an integer while %s is a string.”%(a, b))
Output:
2 is an integer while tiger is a string.
print function
# printing a string
name = “Rahul”
print(“Hey ” + name)
Output:
Hey Rahul
print(“Roll No: ” + str(34)) # “Roll No: ” + 34 is incorrect
Output:
Roll No: 34
# printing a bool True / False
print(True)
Output:
True
print function
int_list = [1, 2, 3, 4, 5]
print(int_list) # printing a list
Output: [1, 2, 3, 4, 5]
my_tuple = (10, 20, 30)
print(my_tuple) # printing a tuple
Output: (10, 20, 30)
my_dict = {“language”: “Python”, “field”: “data science”}
print(my_dict) # printing a dictionary
Output: {“language”: “Python”, “field”: “data science”}
my_set = {“red”, “yellow”, “green”, “blue”}
print(my_set) #printing a set
Output: {“red”, “yellow”, “green”, “blue”}
print function
str1 = ‘Python code’
str2 = ‘Matlab code’
print(str1)
print(str2)
Output: Python code
Matlab code
print(str1, end=’ ‘)
print(str2)
Output: Python code Matlab code
print(str1, end=’, ‘)
print(str2)
Output: Python code, Matlab code
print function
items = [ 1, 2, 3, 4, 5]
for item in items:
print(item)
Output:
1
2
3
4
5
items = [ 1, 2, 3, 4, 5]
for item in items:
print(item, end=’ ‘)
Output:
1 2 3 4 5
Operators
Addition + Subtraction -
Multiplication * Exponentiation **
Division / Integer division / /
Remainder %
Binary left shift << Binary right shift >>
And & Or |
Less than < Greater than >
Less than or equal to <= Greater than or equal to >=
Check equality == Check not equal !=
Precedence of operators
Parenthesized expression ( ….. )
Exponentiation **
Positive, negative, bitwise not +n, -n, ~n
Multiplication, float division, int division, remainder *, /, //, %
Addition, subtraction +, -
Bitwise left, right shifts <<, >>
Bitwise and &
Bitwise or |
Membership and equality tests in, not in, is, is
not, <, <=, >, >=, !=, ==
Boolean (logical) not not x
Boolean and and
Boolean or or
Conditional expression if ….. else
Precedence of Operators
Examples:
a = 20
b = 10
c = 15
d = 5
e = 2
f = (a + b) * c / d
print( f)
g = a + (b * c) / d - e
print(g)
h = a + b*c**e
print(h)
Multiple Assignment
Python allows you to assign a single value to several variables
simultaneously.
a = b = c = 1.5
a, b, c = 1, 2, " Red“
Here, two integer objects with values 1 and 2 are assigned to
variables a and b respectively and one string object with the
value "Red" is assigned to the variable c.
Special Use of + and *
Examples:
x = "Python is "
y = "awesome."
z = x + y
print(z)
Output:
Python is awesome.
print(‘It is’ + 2*’very ’ + ’hot.’)
Output:
It is very very hot.
Use of ”, n, t
Specifying a backslash () in front of the quote character in a string
“escapes” it and causes Python to suppress its usual special meaning. It is
then interpreted simply as a literal single quote character:
>>> print(" ”Beauty of Flower” ")
”Beauty of Flower”
>>> print('Red n Blue n Green ')
Red
Blue
Green
>>> print("a t b t c t d")
a b c d
Comments
Single-line comments begins with a hash ( # ) symbol and is useful in mentioning
that the whole line should be considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python,
triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example:
“““ My Program to find
Average of three numbers ”””
a = 29 # Assigning value of a
b = 17 # Assigning value of b
c = 36 # Assigning value of c
average = ( a + b + c)/3
print(“Average value is ”, average)
id( ) function, ord( ) function
id( ) function: It is a built-in function that returns the unique identifier of
an object. The identifier is an integer, which represents the memory address
of the object. The id( ) function is commonly used to check if two variables
or objects refer to the same memory location.
>>> a=5
>>> id(a)
1403804521000552
ord( ) function: It is used to convert a single unicode character into its
integer representation.
>>> ord(‘A’)
65
>>> chr(65)
‘A’
Control Flow Structures
1. Conditional if ( if )
2. Alternative if ( if else )
3. Chained Conditional if ( if elif else )
4. While loop
5. For loop
Conditional if
Example:
a=10
if a > 9 :
print("a is greater than 9")
Output:
a is greater than 9
Alternative if
Example:
A = int(input(‘Enter the marks '))
if A >= 40:
print("PASS")
else:
print("FAIL")
Output:
Enter the marks 65
PASS
# Test if the given letter is vowel or not
letter = ‘o’
if letter == ‘a’ or letter == ‘e’ or letter == ‘i’ or letter == ‘o’
or letter == ‘u’ :
print(letter, ‘is a vowel.’)
else:
print(letter, ‘is not a vowel.’)
Output:
o is a vowel.
# Program to find the greatest of three different numbers
a = int(input('Enter 1st no’))
b = int(input('Enter 2nd no'))
c= int(input('Enter 3rd no'))
if a > b:
if a>c:
print('The greatest no is ', a)
else:
print('The greatest no is ', c)
else:
if b>c:
print('The greatest no is ', b)
else:
print('The greatest no is ', c)
Output:
Enter 1st no 12
Enter 2nd no 31
Enter 3rd no 9
The greatest no is 31
Chained conditional if
# Program to guess the vegetable
color = “green”
if color == “red”:
print(‘It is a tomato.’)
elif color == “purple”:
print(‘It is a brinjal.')
elif color == “green”:
print(‘It is a papaya. ')
else:
print(‘There is no such vegetable.’)
Output:
It is a papaya.
# Program to find out the greatest of four different numbers
a=int(input('Enter 1st no ‘))
b=int(input('Enter 2nd no ‘))
c=int(input('Enter 3rd no ‘))
d=int(input('Enter 4th no ‘))
if (a>b and a>c and a>d):
print('The greatest no is ', a)
elif (b>c and b>d):
print('The greatest no is ', b)
elif (c>d):
print('The greatest no is ', c)
elif d>c :
print('The greatest no is ', d)
else:
print('At least two values are equal')
Output:
Enter 1st no 23
Enter 2nd no 10
Enter 3rd no 34
Enter 4th no 7
The greatest no is 34
# Program to find out Grade
marks = int(input('Enter total marks ‘))
total = 500 # Total marks
percentage=(marks/total)*100
if percentage >= 80:
print('Grade O')
elif percentage >=70:
print('Grade A')
elif percentage >=60:
print('Grade B')
elif percentage >=40:
print('Grade C')
else:
print('Fail‘)
Output:
Enter total marks 312
Grade B
While loop
# Python program to find first ten Fibonacci numbers
a=1
print(a)
b=1
print(b)
i=3
while i<= 10:
c=a+b
print(c)
a=b
b=c
i=i+1
For loop
# Program to find the sum of squares of first n natural numbers
n = int(input('Enter the last number '))
sum = 0
for i in range(1, n+1):
sum = sum + i*i
print('The sum is ', sum)
Output:
Enter the last number 8
The sum is 204
For loop
# Program to find the sum of a given set of numbers
numbers = [11, 17, 24, 65, 32, 69]
sum = 0
for no in numbers:
sum = sum + no
print('The sum is ', sum)
Output:
The sum is 218
# Program to print 1, 22, 333, 444, .... in triangular form
n = int(input('Enter the number of rows '))
for i in range(1, n+1):
for j in range(1, i+1):
print(i, end='')
print()
Output:
Enter the number of rows 5
1
22
# Program to print opposite right triangle
n = int(input('Enter the number of rows '))
for i in range(n, 0, -1):
for j in range(1, i+1):
print('*', end='')
print()
Output:
*****
****
***
# Program to print opposite star pattern
n = int(input('Enter the number of rows '))
for i in range(0, n):
for j in range(0, n-i):
print(' ', end='')
for k in range(0, i+1):
print('*’, end='')
print('')
Output:
*
**
***
****
*****
# Program to print A, AB, ABC, ABCD, ......
ch = str(input('Enter a character '))
val=ord(ch)
for i in range(65, val+1):
for j in range(65, i+1):
print(chr(j), end='')
print()
Output:
A
AB
ABC
# Program to test Palindrome numbers
n=int(input('Enter an integer '))
x=n
r=0
while n>0:
d=n%10
r=r*10+d
n=n//10
if x==r:
print(x,' is Palindrome number’)
else:
print(x, ' is not Palindrome number')
# Program to print Pascal Triangle
n=int(input('Enter number of rows '))
for i in range(0, n):
for j in range(0, n-i-1):
print(end=' ')
for j in range(0, i+1):
print('*', end=' ')
print()
Output:
Enter number of rows 6
*
* *
* * *
* * * *
* * * * *
* * * * * *
Break and Continue
In Python, break and continue statements can alter the flow of a normal
loop.
# Searching for a given number
numbers = [11, 9, 88, 10, 90, 3, 19]
for num in numbers:
if(num==88):
print("The number 88 is found")
break
Output:
The number 88 is found
Break and Continue
# program to display only odd numbers
for num in [20, 11, 9, 66, 4, 89, 44]:
# Skipping the iteration when number is even
if num%2 == 0:
continue
# This statement will be skipped for all even numbers
else:
print(num)
File
A file is some information or data which stays in the computer
storage devices.
Files are of two types:
 text files
 binary files.
Text files:
We can create the text files by using the following syntax:
Variable name = open (“file.txt”, file mode)
Example:
f= open ("hello.txt","w+“)
File modes
Mode Description
‘r’ This is the default mode. It Opens file for reading.
‘w’ This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
‘x’ Creates a new file. If file already exists, the operation fails.
‘a’ Open file in append mode.
If file does not exist, it creates a new file.
‘t’ This is the default mode. It opens in text mode.
‘b’ This opens in binary mode.
‘+’ This will open a file for reading and writing (updating)
.
Creating output file
file = open(‘output.txt’, ‘a+’)
items = [‘mango’, ‘orange’, ‘banana’, ‘apple’]
for item in items:
print(item, file = file)
file.close()
# Write a python program to open and read a file
a=open(“one.txt”, ”r”)
content = a.read()
print(content)
a.close( )
# Write a python program to open and write “hello world” into a file.
f=open("file.txt","a")
f.write("hello world")
f.close( )
# Python program to write the content “Hi python programming” for the existing file.
f=open("MyFile.txt",'w')
f.write("Hi python programming")
f.close()
# Write a python program to open and write the content to file and read it.
f=open("abc.txt","w+")
f.write("Python Programming")
print(f.read())
f.close()
Thank You

More Related Content

Similar to Introduction to learn and Python Interpreter (20)

PDF
Python Programming
Saravanan T.M
 
PPTX
Python PPT.pptx
JosephMuez2
 
DOCX
A Introduction Book of python For Beginners.docx
kumarrabinderkumar77
 
PPTX
python_module_.................................................................
VaibhavSrivastav52
 
PPTX
Programming with python
sarogarage
 
PPTX
Chapter7-Introduction to Python.pptx
lemonchoos
 
PPTX
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
PPTX
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
PDF
Python: An introduction A summer workshop
ForrayFerenc
 
PPTX
introduction to python
Jincy Nelson
 
PPTX
Python for beginner, learn python from scratch.pptx
olieee2023
 
PDF
Python quick guide
Hasan Bisri
 
PPTX
python_class.pptx
chandankumar943868
 
PPTX
Python Traning presentation
Nimrita Koul
 
PPTX
funadamentals of python programming language (right from scratch)
MdFurquan7
 
PPT
Python
Kumar Gaurav
 
PPTX
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
PPTX
Fundamentals of Python Programming
Kamal Acharya
 
PDF
Introduction to python
Ahmed Salama
 
Python Programming
Saravanan T.M
 
Python PPT.pptx
JosephMuez2
 
A Introduction Book of python For Beginners.docx
kumarrabinderkumar77
 
python_module_.................................................................
VaibhavSrivastav52
 
Programming with python
sarogarage
 
Chapter7-Introduction to Python.pptx
lemonchoos
 
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Introduction to Python for Data Science and Machine Learning
ParrotAI
 
Python: An introduction A summer workshop
ForrayFerenc
 
introduction to python
Jincy Nelson
 
Python for beginner, learn python from scratch.pptx
olieee2023
 
Python quick guide
Hasan Bisri
 
python_class.pptx
chandankumar943868
 
Python Traning presentation
Nimrita Koul
 
funadamentals of python programming language (right from scratch)
MdFurquan7
 
Python
Kumar Gaurav
 
unit (1)INTRODUCTION TO PYTHON course.pptx
usvirat1805
 
Fundamentals of Python Programming
Kamal Acharya
 
Introduction to python
Ahmed Salama
 

More from Alamelu (7)

PPTX
Software Engineering- Understanding Requirements
Alamelu
 
PPTX
Advanced Machine Learning- Introduction to Machine Learning
Alamelu
 
PPTX
The Switch Statement,Loops,Array,Functions
Alamelu
 
PPTX
Line drawing algorithm in Computer Graphics.pptx
Alamelu
 
PPTX
Line Clipping in Comeputer Graphics.pptx
Alamelu
 
PPTX
OUTPUT PRIMITIVES.pptx
Alamelu
 
PPTX
Languages and tools for web programming
Alamelu
 
Software Engineering- Understanding Requirements
Alamelu
 
Advanced Machine Learning- Introduction to Machine Learning
Alamelu
 
The Switch Statement,Loops,Array,Functions
Alamelu
 
Line drawing algorithm in Computer Graphics.pptx
Alamelu
 
Line Clipping in Comeputer Graphics.pptx
Alamelu
 
OUTPUT PRIMITIVES.pptx
Alamelu
 
Languages and tools for web programming
Alamelu
 
Ad

Recently uploaded (20)

PPTX
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
PPTX
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
PDF
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PDF
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
PPTX
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
PPTX
ENGLISH 8 REVISED K-12 CURRICULUM QUARTER 1 WEEK 1
LeomarrYsraelArzadon
 
PPTX
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
PPTX
Connecting Linear and Angular Quantities in Human Movement.pptx
AngeliqueTolentinoDe
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
PDF
AI-assisted IP-Design lecture from the MIPLM 2025
MIPLM
 
PPTX
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
PPTX
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
PDF
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PPTX
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
PDF
I3PM Case study smart parking 2025 with uptoIP® and ABP
MIPLM
 
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
Genomics Proteomics and Vaccines 1st Edition Guido Grandi (Editor)
kboqcyuw976
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
ENGLISH 8 REVISED K-12 CURRICULUM QUARTER 1 WEEK 1
LeomarrYsraelArzadon
 
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PLANNING FOR EMERGENCY AND DISASTER MANAGEMENT ppt.pptx
PRADEEP ABOTHU
 
Connecting Linear and Angular Quantities in Human Movement.pptx
AngeliqueTolentinoDe
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
AI-assisted IP-Design lecture from the MIPLM 2025
MIPLM
 
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
The Gift of the Magi by O Henry-A Story of True Love, Sacrifice, and Selfless...
Beena E S
 
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
I3PM Case study smart parking 2025 with uptoIP® and ABP
MIPLM
 
Ad

Introduction to learn and Python Interpreter

  • 1. Introduction to Python PRESENTED BY G.ALAMELU, MCA., E.M.G YADAVA WOMENS COLLEGE
  • 2. Why should we learn Python?  Python is a higher level programming language.  Its syntax allows programmers to express concepts in fewer lines of code.  Python is a programming language that lets you work quickly and integrate systems more efficiently.  One can plot figures using Python.  One can perform symbolic mathematics easily using Python.  It is available freely online.
  • 3. Python versions Python was first released on February 20, 1991 and later on developed by Python Software Foundation. Major Python versions are – Python 1, Python 2 and Python 3. • On 26th January 1994, Python 1.0 was released. • On 16th October 2000, Python 2.0 was released with many new features. • On 3rd December 2008, Python 3.0 was released with more testing and includes new features. Latest version - On 2nd October 2023, Python 3.12 was released. To check your Python version i) For Linux OS type python -V in the terminal window. ii) For Windows and MacOS type import sys print(sys.version) in the interactive shell.
  • 6. Python Interpreter The program that translates Python instructions and then executes them is the Python interpreter. When we write a Python program, the program is executed by the Python interpreter. This interpreter is written in the C language. There are certain online interpreters like https://ide.geeksforgeeks.org/, http://ideone.com/ , http://codepad.org/ that can be used to start Python without installing an interpreter.
  • 7. Python IDLE Python interpreter is embedded in a number of larger programs that make it particularly easy to develop Python programs. Such a programming environment is IDLE ( Integrated Development and Learning Environment). It is available freely online. For Windows machine IDLE (Integrated Development and Learning Environment) is installed when you install Python.
  • 8. Running Python There are two modes for using the Python interpreter: 1) Interactive Mode 2) Script Mode Options for running the program: • In Windows, you can display your folder contents, and double click on madlib.py to start the program. • In Linux or on a Mac you can open a terminal window, change into your python directory, and enter the command python madlib.py
  • 11. Running Python 1) in interactive mode: >>> print("Hello Teachers") Hello Teachers >>> a=10 >>> print(a) 10 >>> x=10 >>> z=x+20 >>> z 30
  • 12. Running Python 2) in script mode: Programmers can store Python script source code in a file with the .py extension, and use the interpreter to execute the contents of the file. For UNIX OS to run a script file MyFile.py you have to type: python MyFile.py
  • 13. Data Types Python has various standard data types:  Integer [ class ‘int’ ]  Float [ class ‘float’ ]  Boolean [ class ‘bool’ ]  String [ class ‘str’ ]
  • 14. Integer Int: For integer or whole number, positive or negative, without decimals of unlimited length. >>> print(2465635468765) 2465635468765 >>> print(0b10) # 0b indicates binary number 2 >>> print(0x10) # 0x indicates hexadecimal number 16 >>> a=11 >>> print(type(a)) <class 'int'>
  • 15. Float Float: Float, or "floating point number" is a number, positive or negative. Float can also be scientific numbers with an "e" to indicate the power of 10. >>> y=2.8 >>> y 2.8 >>> print(0.00000045) 4.5e-07 >>> y=2.8 >>> print(type(y)) <class 'float'>
  • 16. Boolean and String Boolean: Objects of Boolean type may have one of two values, True or False: >>> type(True) <class 'bool'> >>> type(False) <class 'bool'> String: >>> print(‘Science college’) Science college >>> type("My college") <class 'str'>
  • 17. Variables One can store integers, decimals or characters in variables. 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) a= 100 # An integer assignment b = 1040.23 # A floating point c = "John" # A string
  • 18. List, Tuple, Set, Dictionary Four built-in data structures in Python:- list, tuple, set, dictionary - each having qualities and usage different from the other three. List is a collection of items that is written with square brackets. It is mutable, ordered and allows duplicate members. Example: list = [1,2,3,'A','B',7,8,[10,11]] Tuple is a collection of objects that is written with first brackets. It is immutable. Example: tuple = (2, 1, 10, 4, 7) Set is a collection of elements that is written with curly brackets. It is unindexed and unordered. Example: S = {x for x in 'abracadabra' if x not in 'abc'} Dictionary is a collection which is ordered, changeable and does not allow duplicates. It is written with curly brackets and objects are stored in key: value format. Example: X = {1:’A’, 2:’B’, 3:’c’}
  • 19. print function >>>type(print) Output: builtin_function_or_method >>>print( ‘Good morning’ ) or print(“Good morning”) Output: Good morning >>>print(“Workshop”, “on”, “Python”) or print(“Workshop on Python”) Output: Workshop on Python
  • 20. print function >>>print(‘Workshop’, ‘on’, ‘Python’, sep=’n’) # sep=‘n’ will put each word in a new line Output: Workshop on Python >>>print(‘Workshop’, ‘on’, ‘Python’, sep=’, ’) # sep=‘, ’ will print words separated by , Output: Workshop, on, Python
  • 21. print function %d is used as a placeholder for integer value. %f is used as a placeholder for decimal value. %s is used as a placeholder for string. a = 2 b = ‘tiger’ print(a, ‘is an integer while’, b, ‘is a string.’) Output: 2 is an integer while tiger is a string. Alternative way: print(“%d is an integer while %s is a string.”%(a, b)) Output: 2 is an integer while tiger is a string.
  • 22. print function # printing a string name = “Rahul” print(“Hey ” + name) Output: Hey Rahul print(“Roll No: ” + str(34)) # “Roll No: ” + 34 is incorrect Output: Roll No: 34 # printing a bool True / False print(True) Output: True
  • 23. print function int_list = [1, 2, 3, 4, 5] print(int_list) # printing a list Output: [1, 2, 3, 4, 5] my_tuple = (10, 20, 30) print(my_tuple) # printing a tuple Output: (10, 20, 30) my_dict = {“language”: “Python”, “field”: “data science”} print(my_dict) # printing a dictionary Output: {“language”: “Python”, “field”: “data science”} my_set = {“red”, “yellow”, “green”, “blue”} print(my_set) #printing a set Output: {“red”, “yellow”, “green”, “blue”}
  • 24. print function str1 = ‘Python code’ str2 = ‘Matlab code’ print(str1) print(str2) Output: Python code Matlab code print(str1, end=’ ‘) print(str2) Output: Python code Matlab code print(str1, end=’, ‘) print(str2) Output: Python code, Matlab code
  • 25. print function items = [ 1, 2, 3, 4, 5] for item in items: print(item) Output: 1 2 3 4 5 items = [ 1, 2, 3, 4, 5] for item in items: print(item, end=’ ‘) Output: 1 2 3 4 5
  • 26. Operators Addition + Subtraction - Multiplication * Exponentiation ** Division / Integer division / / Remainder % Binary left shift << Binary right shift >> And & Or | Less than < Greater than > Less than or equal to <= Greater than or equal to >= Check equality == Check not equal !=
  • 27. Precedence of operators Parenthesized expression ( ….. ) Exponentiation ** Positive, negative, bitwise not +n, -n, ~n Multiplication, float division, int division, remainder *, /, //, % Addition, subtraction +, - Bitwise left, right shifts <<, >> Bitwise and & Bitwise or | Membership and equality tests in, not in, is, is not, <, <=, >, >=, !=, == Boolean (logical) not not x Boolean and and Boolean or or Conditional expression if ….. else
  • 28. Precedence of Operators Examples: a = 20 b = 10 c = 15 d = 5 e = 2 f = (a + b) * c / d print( f) g = a + (b * c) / d - e print(g) h = a + b*c**e print(h)
  • 29. Multiple Assignment Python allows you to assign a single value to several variables simultaneously. a = b = c = 1.5 a, b, c = 1, 2, " Red“ Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively and one string object with the value "Red" is assigned to the variable c.
  • 30. Special Use of + and * Examples: x = "Python is " y = "awesome." z = x + y print(z) Output: Python is awesome. print(‘It is’ + 2*’very ’ + ’hot.’) Output: It is very very hot.
  • 31. Use of ”, n, t Specifying a backslash () in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character: >>> print(" ”Beauty of Flower” ") ”Beauty of Flower” >>> print('Red n Blue n Green ') Red Blue Green >>> print("a t b t c t d") a b c d
  • 32. Comments Single-line comments begins with a hash ( # ) symbol and is useful in mentioning that the whole line should be considered as a comment until the end of line. A Multi line comment is useful when we need to comment on many lines. In python, triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting. Example: “““ My Program to find Average of three numbers ””” a = 29 # Assigning value of a b = 17 # Assigning value of b c = 36 # Assigning value of c average = ( a + b + c)/3 print(“Average value is ”, average)
  • 33. id( ) function, ord( ) function id( ) function: It is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id( ) function is commonly used to check if two variables or objects refer to the same memory location. >>> a=5 >>> id(a) 1403804521000552 ord( ) function: It is used to convert a single unicode character into its integer representation. >>> ord(‘A’) 65 >>> chr(65) ‘A’
  • 34. Control Flow Structures 1. Conditional if ( if ) 2. Alternative if ( if else ) 3. Chained Conditional if ( if elif else ) 4. While loop 5. For loop
  • 35. Conditional if Example: a=10 if a > 9 : print("a is greater than 9") Output: a is greater than 9
  • 36. Alternative if Example: A = int(input(‘Enter the marks ')) if A >= 40: print("PASS") else: print("FAIL") Output: Enter the marks 65 PASS
  • 37. # Test if the given letter is vowel or not letter = ‘o’ if letter == ‘a’ or letter == ‘e’ or letter == ‘i’ or letter == ‘o’ or letter == ‘u’ : print(letter, ‘is a vowel.’) else: print(letter, ‘is not a vowel.’) Output: o is a vowel.
  • 38. # Program to find the greatest of three different numbers a = int(input('Enter 1st no’)) b = int(input('Enter 2nd no')) c= int(input('Enter 3rd no')) if a > b: if a>c: print('The greatest no is ', a) else: print('The greatest no is ', c) else: if b>c: print('The greatest no is ', b) else: print('The greatest no is ', c) Output: Enter 1st no 12 Enter 2nd no 31 Enter 3rd no 9 The greatest no is 31
  • 39. Chained conditional if # Program to guess the vegetable color = “green” if color == “red”: print(‘It is a tomato.’) elif color == “purple”: print(‘It is a brinjal.') elif color == “green”: print(‘It is a papaya. ') else: print(‘There is no such vegetable.’) Output: It is a papaya.
  • 40. # Program to find out the greatest of four different numbers a=int(input('Enter 1st no ‘)) b=int(input('Enter 2nd no ‘)) c=int(input('Enter 3rd no ‘)) d=int(input('Enter 4th no ‘)) if (a>b and a>c and a>d): print('The greatest no is ', a) elif (b>c and b>d): print('The greatest no is ', b) elif (c>d): print('The greatest no is ', c) elif d>c : print('The greatest no is ', d) else: print('At least two values are equal') Output: Enter 1st no 23 Enter 2nd no 10 Enter 3rd no 34 Enter 4th no 7 The greatest no is 34
  • 41. # Program to find out Grade marks = int(input('Enter total marks ‘)) total = 500 # Total marks percentage=(marks/total)*100 if percentage >= 80: print('Grade O') elif percentage >=70: print('Grade A') elif percentage >=60: print('Grade B') elif percentage >=40: print('Grade C') else: print('Fail‘) Output: Enter total marks 312 Grade B
  • 42. While loop # Python program to find first ten Fibonacci numbers a=1 print(a) b=1 print(b) i=3 while i<= 10: c=a+b print(c) a=b b=c i=i+1
  • 43. For loop # Program to find the sum of squares of first n natural numbers n = int(input('Enter the last number ')) sum = 0 for i in range(1, n+1): sum = sum + i*i print('The sum is ', sum) Output: Enter the last number 8 The sum is 204
  • 44. For loop # Program to find the sum of a given set of numbers numbers = [11, 17, 24, 65, 32, 69] sum = 0 for no in numbers: sum = sum + no print('The sum is ', sum) Output: The sum is 218
  • 45. # Program to print 1, 22, 333, 444, .... in triangular form n = int(input('Enter the number of rows ')) for i in range(1, n+1): for j in range(1, i+1): print(i, end='') print() Output: Enter the number of rows 5 1 22
  • 46. # Program to print opposite right triangle n = int(input('Enter the number of rows ')) for i in range(n, 0, -1): for j in range(1, i+1): print('*', end='') print() Output: ***** **** ***
  • 47. # Program to print opposite star pattern n = int(input('Enter the number of rows ')) for i in range(0, n): for j in range(0, n-i): print(' ', end='') for k in range(0, i+1): print('*’, end='') print('') Output: * ** *** **** *****
  • 48. # Program to print A, AB, ABC, ABCD, ...... ch = str(input('Enter a character ')) val=ord(ch) for i in range(65, val+1): for j in range(65, i+1): print(chr(j), end='') print() Output: A AB ABC
  • 49. # Program to test Palindrome numbers n=int(input('Enter an integer ')) x=n r=0 while n>0: d=n%10 r=r*10+d n=n//10 if x==r: print(x,' is Palindrome number’) else: print(x, ' is not Palindrome number')
  • 50. # Program to print Pascal Triangle n=int(input('Enter number of rows ')) for i in range(0, n): for j in range(0, n-i-1): print(end=' ') for j in range(0, i+1): print('*', end=' ') print() Output: Enter number of rows 6 * * * * * * * * * * * * * * * * * * * * *
  • 51. Break and Continue In Python, break and continue statements can alter the flow of a normal loop. # Searching for a given number numbers = [11, 9, 88, 10, 90, 3, 19] for num in numbers: if(num==88): print("The number 88 is found") break Output: The number 88 is found
  • 52. Break and Continue # program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]: # Skipping the iteration when number is even if num%2 == 0: continue # This statement will be skipped for all even numbers else: print(num)
  • 53. File A file is some information or data which stays in the computer storage devices. Files are of two types:  text files  binary files. Text files: We can create the text files by using the following syntax: Variable name = open (“file.txt”, file mode) Example: f= open ("hello.txt","w+“)
  • 54. File modes Mode Description ‘r’ This is the default mode. It Opens file for reading. ‘w’ This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file. ‘x’ Creates a new file. If file already exists, the operation fails. ‘a’ Open file in append mode. If file does not exist, it creates a new file. ‘t’ This is the default mode. It opens in text mode. ‘b’ This opens in binary mode. ‘+’ This will open a file for reading and writing (updating) .
  • 55. Creating output file file = open(‘output.txt’, ‘a+’) items = [‘mango’, ‘orange’, ‘banana’, ‘apple’] for item in items: print(item, file = file) file.close()
  • 56. # Write a python program to open and read a file a=open(“one.txt”, ”r”) content = a.read() print(content) a.close( ) # Write a python program to open and write “hello world” into a file. f=open("file.txt","a") f.write("hello world") f.close( )
  • 57. # Python program to write the content “Hi python programming” for the existing file. f=open("MyFile.txt",'w') f.write("Hi python programming") f.close() # Write a python program to open and write the content to file and read it. f=open("abc.txt","w+") f.write("Python Programming") print(f.read()) f.close()