SlideShare a Scribd company logo
Introduction to Python
Python – a mysterious name
Python is a widely used general-purpose,
high level programming language. It was
initially designed by Dutch programmer
Guido van Rossum in 1991.
The name Python comes from an old BBC
television comedy sketch series called
Monty Python’s Flying Circus. When
Guido van Rossum was creating Python, he
was also reading the scripts of Monty
Python. He thought the name Python was
appropriately short and slightly mysterious.
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
Working with lists,list of lists, work tuples, work with
dates
and times ,and get started with dictionaries
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’}
Python functions and Boolean expressions
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’
Selection and iteration structure
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)
References
[1] Kenneth A Lambert, Fundamentals of Python: First programs, 2nd
edition – Cengage Learning India, 2019.
[2] Saha Amit, Doing Math with Python - No starch press, San Francisco,
2015.
[3] E. Balgurusamy, Problem solving and Python programming- Tata
McGraw Hill, 2017.
[4] Bill Lubanovic, Introducing Python, Shroff Publishers & Distributors
Pvt. Ltd., 2nd
Edition, 2020.
Thank You

More Related Content

PPTX
Python knowledge ,......................
PPTX
Introduction to learn and Python Interpreter
PPTX
Keep it Stupidly Simple Introduce Python
PPTX
unit1.pptx for python programming CSE department
PPT
Python Programming Introduction demo.ppt
PPTX
PPTX
unit (1)INTRODUCTION TO PYTHON course.pptx
PPTX
Python fundamentals
Python knowledge ,......................
Introduction to learn and Python Interpreter
Keep it Stupidly Simple Introduce Python
unit1.pptx for python programming CSE department
Python Programming Introduction demo.ppt
unit (1)INTRODUCTION TO PYTHON course.pptx
Python fundamentals

Similar to Chapter1 python introduction syntax general (20)

PPTX
Python basics
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
PPTX
Python (Data Analysis) cleaning and visualize
PPTX
Introduction To Python.pptx
PPTX
Pythonppt28 11-18
PPTX
FUNDAMENTALS OF PYTHON LANGUAGE
PPT
Python
PDF
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
PPTX
Python 3.pptx
PPTX
Python Scipy Numpy
PPTX
lecture 2.pptx
PDF
python lab programs.pdf
PPTX
funadamentals of python programming language (right from scratch)
PPTX
Python_Haegl.powerpoint presentation. tx
PPTX
MODULE. .pptx
PPTX
Python introduction towards data science
PPTX
introduction to python programming concepts
PDF
Basic Concepts in Python
PDF
Revision of the basics of python1 (1).pdf
PPTX
Python for Beginners(v1)
Python basics
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Python (Data Analysis) cleaning and visualize
Introduction To Python.pptx
Pythonppt28 11-18
FUNDAMENTALS OF PYTHON LANGUAGE
Python
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
Python 3.pptx
Python Scipy Numpy
lecture 2.pptx
python lab programs.pdf
funadamentals of python programming language (right from scratch)
Python_Haegl.powerpoint presentation. tx
MODULE. .pptx
Python introduction towards data science
introduction to python programming concepts
Basic Concepts in Python
Revision of the basics of python1 (1).pdf
Python for Beginners(v1)
Ad

More from ssuser77162c (14)

PPTX
REGULAR EXPRESSION FOR NATURAL LANGUAGES
PPTX
satellitesystems.pptx mobile database computing
PPTX
FINALEXAMCHAPTER3.pptx remote sensing diagram
PPT
CHAPTER2.ppt DATABASES FOR MULTIMEDIA COMPUTING
PPTX
UNIT-3.pptx GIS INFORMATION SYSTEMFOR COMPUTING
PPTX
chapter21-parallel processing. computing
PPT
RTET-2024_52.ppt research presentation for
PPTX
FSA.pptx natural language prsgdsgocessing
PPTX
chapter4.pptx natural language processing
PPTX
Chapter 5-Numpy-Pandas.pptx python programming
PPT
Semantic natural language processing ppt
PPTX
arthimetic operator,classes,objects,instant
PPT
intro.ppt
PPT
8034.ppt
REGULAR EXPRESSION FOR NATURAL LANGUAGES
satellitesystems.pptx mobile database computing
FINALEXAMCHAPTER3.pptx remote sensing diagram
CHAPTER2.ppt DATABASES FOR MULTIMEDIA COMPUTING
UNIT-3.pptx GIS INFORMATION SYSTEMFOR COMPUTING
chapter21-parallel processing. computing
RTET-2024_52.ppt research presentation for
FSA.pptx natural language prsgdsgocessing
chapter4.pptx natural language processing
Chapter 5-Numpy-Pandas.pptx python programming
Semantic natural language processing ppt
arthimetic operator,classes,objects,instant
intro.ppt
8034.ppt
Ad

Recently uploaded (20)

PDF
Pre independence Education in Inndia.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Insiders guide to clinical Medicine.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
Pre independence Education in Inndia.pdf
TR - Agricultural Crops Production NC III.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
102 student loan defaulters named and shamed – Is someone you know on the list?
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Structure & Organelles in detailed.
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPH.pptx obstetrics and gynecology in nursing
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
Insiders guide to clinical Medicine.pdf
human mycosis Human fungal infections are called human mycosis..pptx

Chapter1 python introduction syntax general

  • 2. Python – a mysterious name Python is a widely used general-purpose, high level programming language. It was initially designed by Dutch programmer Guido van Rossum in 1991. The name Python comes from an old BBC television comedy sketch series called Monty Python’s Flying Circus. When Guido van Rossum was creating Python, he was also reading the scripts of Monty Python. He thought the name Python was appropriately short and slightly mysterious.
  • 3. 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.
  • 4. 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.
  • 7. 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.
  • 8. 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.
  • 9. 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
  • 12. Running Python 1) in interactive mode: >>> print("Hello Teachers") Hello Teachers >>> a=10 >>> print(a) 10 >>> x=10 >>> z=x+20 >>> z 30
  • 13. 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
  • 14. Data Types Python has various standard data types:  Integer [ class ‘int’ ]  Float [ class ‘float’ ]  Boolean [ class ‘bool’ ]  String [ class ‘str’ ]
  • 15. 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'>
  • 16. 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'>
  • 17. 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'>
  • 18. 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
  • 19. Working with lists,list of lists, work tuples, work with dates and times ,and get started with dictionaries
  • 20. 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’}
  • 21. Python functions and Boolean expressions
  • 22. 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
  • 23. 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
  • 24. 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.
  • 25. 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
  • 26. 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”}
  • 27. 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
  • 28. 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
  • 29. 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 !=
  • 30. 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
  • 31. 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)
  • 32. 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.
  • 33. 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.
  • 34. 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
  • 35. 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)
  • 36. 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’
  • 38. 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
  • 39. Conditional if Example: a=10 if a > 9 : print("a is greater than 9") Output: a is greater than 9
  • 40. Alternative if Example: A = int(input(‘Enter the marks ')) if A >= 40: print("PASS") else: print("FAIL") Output: Enter the marks 65 PASS
  • 41. # 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.
  • 42. # 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
  • 43. 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.
  • 44. # 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
  • 45. # 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. # 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
  • 50. # 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: ***** **** ***
  • 51. # 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: * ** *** **** *****
  • 52. # 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
  • 53. # 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')
  • 54. # 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 * * * * * * * * * * * * * * * * * * * * *
  • 55. 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
  • 56. 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)
  • 57. References [1] Kenneth A Lambert, Fundamentals of Python: First programs, 2nd edition – Cengage Learning India, 2019. [2] Saha Amit, Doing Math with Python - No starch press, San Francisco, 2015. [3] E. Balgurusamy, Problem solving and Python programming- Tata McGraw Hill, 2017. [4] Bill Lubanovic, Introducing Python, Shroff Publishers & Distributors Pvt. Ltd., 2nd Edition, 2020.