SlideShare a Scribd company logo
UNIT 02: BASICS OF PYTHON
PROGRAMMING
Introduction-Python Interpreter-Interactive and
script mode -Values and types, variables,
operators, expressions, statements, precedence
of operators, Multiple assignments, comments,
input function, print function, Formatting
numbers and strings, implicit/explicit type
conversion.
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 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.
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.
Python Interpreter
• A python interpreter is a computer program that converts each
high-level program statement into machine code.
• 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
Difference between Interpreter and
Compiler
Compilers Interpreters
Compilers translate the entire source code into
machine code before execution.
Interpreters translate and execute the source
code line by line.
Compiled code runs faster because it's already
translated into machine code.
Interpreted code runs slower because it must be
translated on the fly.
Compilers generate an executable file that can
be run independently.
Interpreters require the source code to be
present at runtime.
Compilers display all errors at once after
compilation.
Interpreters display errors one at a time during
execution.
Compiled languages include C, C++, and Java. Interpreted languages include Python, Ruby, and
JavaScript.
Compilers have a longer development cycle due
to the compilation step.
Interpreters have a shorter development cycle as
code can be tested immediately.
Compiled code is platform-dependent. Interpreted code is platform-independent.
MODES OF PYTHON INTERPRETER
1. Interactive mode
2. Script mode
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:
Python, in interactive mode, is good enough to learn, experiment or
explore.
Working in interactive mode is convenient for beginners and for
testing small pieces of code.
Drawback:
We cannot save the statements and have to retype all the statements
once again to re-run them
Python unit 2 is added. Has python related programming content
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.
Python unit 2 is added. Has python related programming content
Python unit 2 is added. Has python related programming content
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.
Values and types
Value: Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to
different data types.)
Data type: Every value in Python has a data type. It is a set of values,
and the allowable operations on those values.
Python data types
Numeric Data Types
type() function is used to determine the type of Python data type.
• Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fractions or decimals). In Python,
there is no limit to how long an integer value can be.
• Float – This value is represented by the float class. It is a real number
with a 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 – A complex number is represented by a complex
class. It is specified as (real part) + (imaginary part)j . For example – 2+3j
Python unit 2 is added. Has python related programming content
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.
1.Strings (Immutable)
2. Lists( mutable)
3. Tuples(Immutable)
Strings
• A String in Python consists of a 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.
Indexing
String A H E L L 0
Positive Index 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
Example: A[0] or A[-5] will display “H”
Example: A[1] or A[-4] will display “E”
Str=‘Python Program’
Str[-3]
Str[3]
Str[6]
Str[7]
Operations on string
• Indexing
• Slicing
• Concatenation
• Repetitions
• Member ship
Indexing Accessing the item in the position
Slicing Slice operator is used to extract part of a data type
Concatenation Adding and printing the characters of two strings.
Repetition multiple copies of the same string
in, not in
(membership
operator)
Using membership operators to check a particular
character is in string or not. Returns true if present.
Indexing
Slicing
• str='hello w'
• print(len(str))
• 7
• print(str[:])
• hello w
• print(str[::2])
• Hlow
• print(str[::-1])
• w olleh
Example
• Consider the string S=“Python Programming”
• Predict the output:
• s[-1]
• S[6:12]
• S[:4]
• S[:]
• S[5:5] , s[9:] ,s[0:5] , len(s)
Concatenation
Repetition
in, not in (membership operator)
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 brackets[ ].
• Items in the lists can be of different data types.
Operations on lists
• Indexing
• Slicing
• Concatenation
• Repetitions
• Updation, Insertion, Deletion
Indexing Accessing the item in the particular position
Slicing Slice operator is used to extract part of a string, or some
part of a list Python
Concatenation Adding and printing the items of two lists.
Repetitions multiple copies of the same string
Updating the list Updating the list using index value
Inserting an element Inserting an element in 2nd position
Removing an element Removing an element by giving the element directly
Indexing
Slicing
Concatenation
Repetitions
Updating the list
Inserting an element
Removing an element
Note:
Update,Insert:Need
to give Position
Remove:give value
alone
Tuple
• A tuple is same as list, except that the set of elements is enclosed in
parentheses instead of square brackets.
• 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.
• Tuples are faster than lists
Basic Operations
• Indexing
• Slicing
• Concatenation
• Repetitions
Note:
concatenate
tuple (not "int")
to tuple
Python unit 2 is added. Has python related programming content
Dictionaries
• Lists are ordered sets of objects, whereas dictionaries are
unordered sets.
• Dictionary is created by using curly brackets. i,e. {}
• Dictionaries are accessed via keys and not via their
position.
Python unit 2 is added. Has python related programming content
Variables
• Rules:
• 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.
Assigning a single value to several variables simultaneously:
Assigning multiple values to multiple variables
a=b=c=10,20,"Ram"
print(c)
(10, 20, 'Ram')
print(a)
(10, 20, 'Ram')
a=b=c=100
print(a)
100
print(c)
100
Expressions and Statements
• Statements:
• Instructions that a Python interpreter can executes are called statements.
• A statement is a unit of code like creating a variable or displaying a value.
• Expressions:
• An expression is a combination of values, variables, and operators.
>>> n = 17
>>> print(n)
a=2
a+3+2
7
str=("Good"+"Morning")
print(str)
GoodMorning
Multiple assignments
• same value to multiple variables
• Assign multiple values to multiple variables
a=b=c=10
print(a)
10
print(b)
10
x, y, z = "Orange", "Banana", "Cherry"
print(x)
Orange
Comments
• Comments are the kind of statements that are written in the
program for program understanding purpose.
• In Python, we use the hash (#) symbol to start writing a comment.
• Python Interpreter ignores comment.
• If we have comments that extend multiple lines, one way of doing it
is to use hash (#) in the beginning of each line.
# This is comment line
print(“I love my country”)
percentage = (minute *
100) / 60 # calculating
percentage of an hour
#This is
#another example
#of comment statement
OPERATORS
• Operators are the constructs which can manipulate the value of operands.
• Consider the expression 4 + 5 = 9.
• Here, 4 and 5 are called operands and + is called operator
Types of Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic operators
• They are used to perform mathematical operations like addition,
subtraction, multiplication etc
Operator Description
+ Addition Adds values on either side of the operator
- Subtraction Subtracts right hand operand from left hand operand.
* Multiplication Multiplies values on either side of the operator
/ Division Divides left hand operand by right hand operand
% Modulus Divides left hand operand by right hand operand and
returns remainder
** Exponent Performs exponential (power) calculation on operators
// Floor Division - The division of operands where the result is
the quotient in which the digits after the decimal point are
removed
Python unit 2 is added. Has python related programming content
Comparison (Relational) Operators
• Comparison operators are used to compare values.
• It either returns True or False according to the condition. Assume, a=10 and b=5
==,<
>
<=
>=
!=
Python unit 2 is added. Has python related programming content
Assignment Operators
• Assignment operators are used in Python to
assign values to variables.
Operator Description Example
= Assigns values from right side operands to
left side operand
c = a + b assigns value of a
+ b into c
+= Add
AND
It adds right operand to the left operand
and assign the result to left operand
c += a
is equivalent to c = c + a
-= Subtract
AND
It subtracts right operand from the left
operand and assign the result to left
operand
c -= a
is equivalent to c = c - a
*= Multiply
AND
It multiplies right operand with the left
operand and assign the result to left
operand
c *= a
is equivalent to c = c * a
**=
Exponent
AND
Performs exponential (power) calculation
on operators and assign value to the left
operand
c **= a
is equivalent to c = c ** a
//= Floor
Division
It performs floor division on operators and
assign value to the left operand
c //= a is equivalent to c = c
// a
Python unit 2 is added. Has python related programming content
Logical Operators
• Logical operators are the and, or, not operators
And True if both the operands are True
Or True if either of the operands is true
not True if operands is false
Python unit 2 is added. Has python related programming content
Bitwise Operators
• A bitwise operation operates on one or more bit patterns
at the level of individual bits
• Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)
x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)
& Bitwise AND X&Y= (0000 0000)
| Bitwise OR X|y= (0000 1110)
~ Bitwise Not -x=(1111 0101)
^ Bitwise XOR x ^ y =(1111 0001)
>> Bitwise right shift X >>2=(0000 0010)
<< Bitwise left shift X <<2=(0010 1000)
Membership Operators
• Evaluates to find a value or a variable is in the specified sequence
of string, list, tuple, dictionary or not.
• Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in
operators are used.
Identity Operators
• They are used to check if two values (or variables) are
located on the same part of the memory.
• If the two values are identical: True
Precedence of operators
• When an expression contains more than one operator, the order of
evaluation depends on the order of operations.
• PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,
Subtraction)
Python unit 2 is added. Has python related programming content
Input function
• Input is data entered by user (end user) in the program.
• input () function
x=input("enter the name:")
enter the name:hhh
y=int(input("enter the number"))
enter the number 3
Output function
• Output can be displayed to the user using Print statement
print (expression/constant/variable)
print("Hello")
Hello
print(2+4)
6
print(6)
6
Type Casting(Type Conversion)
• Is the process of converting the value of one data type to another
Python Implicit Type Conversion
Python Explicit Type Conversion
Implicit Type Conversion
• In this, method, Python converts the data type into
another data type automatically. Users don’t have to
involve in this process.
a=10
b=12.0
c=a+b
print(c)
22.0
Explicit Type Conversion
• This involves converting a data type explicitly using predefined
functions like int(), float(), str(), etc., where the programmer
specifically directs the type of conversion required.
a=10
print(type(a))
<class 'int'>
print(float(a))
10.0
b=12.24
print(type(b))
<class 'float'>
print(int(b))
12
c=15.78
print(int(c))
15
• Convert string to int: (Value Error)
• Converting string to int datatype in Python with int() function. If the given
string is not number, then it will throw an error.
a="Hema"
print(int(a))
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
print(int(a))
ValueError: invalid literal for int() with base
10: 'Hema'
a="5"
print(int(a))
5
Formatting numbers and strings
price = 49
txt ="The price is {price} dollars"
print(txt)
Output:
The price is {price} dollars
price = 49
txt =f"The price is {price} dollars"
print(txt)
Output:
The price is 49 dollars
• Celsius to Fahrenheit:
F = [(C*9/5) +32]
• convert kilometers to miles
Miles=0.62*km

More Related Content

Similar to Python unit 2 is added. Has python related programming content (20)

Python slides for the beginners to learn
Python slides for the beginners to learnPython slides for the beginners to learn
Python slides for the beginners to learn
krishna43511
 
program on python what is python where it was started by whom started
program on python what is python where it was started by whom startedprogram on python what is python where it was started by whom started
program on python what is python where it was started by whom started
rajkumarmandal9391
 
Py-Slides-1.ppt1234444444444444444444444444444444444444444
Py-Slides-1.ppt1234444444444444444444444444444444444444444Py-Slides-1.ppt1234444444444444444444444444444444444444444
Py-Slides-1.ppt1234444444444444444444444444444444444444444
divijareddy0502
 
Python Over View (Python for mobile app Devt)1.ppt
Python Over View (Python for mobile app Devt)1.pptPython Over View (Python for mobile app Devt)1.ppt
Python Over View (Python for mobile app Devt)1.ppt
AbdurehmanDawud
 
Python Programming 1.pptx
Python Programming 1.pptxPython Programming 1.pptx
Python Programming 1.pptx
Francis Densil Raj
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
shetoooelshitany74
 
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
notwa dfdfvs gf fdgfgh  s thgfgh frg regggnotwa dfdfvs gf fdgfgh  s thgfgh frg reggg
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
Godwin585235
 
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
v65176016
 
Python for katana
Python for katanaPython for katana
Python for katana
kedar nath
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Introduction to Python Programming .pptx
Introduction to  Python Programming .pptxIntroduction to  Python Programming .pptx
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
Unit 2 python
Unit 2 pythonUnit 2 python
Unit 2 python
praveena p
 
Python Module-1.1.pdf
Python Module-1.1.pdfPython Module-1.1.pdf
Python Module-1.1.pdf
4HG19EC010HARSHITHAH
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
TamalSengupta8
 
intro to python.pptx
intro to python.pptxintro to python.pptx
intro to python.pptx
UpasnaSharma37
 
UNIT 1 .pptx
UNIT 1                                                .pptxUNIT 1                                                .pptx
UNIT 1 .pptx
Prachi Gawande
 
1. python programming
1. python programming1. python programming
1. python programming
sreeLekha51
 
python introduction all the students.ppt
python introduction all the students.pptpython introduction all the students.ppt
python introduction all the students.ppt
ArunkumarM192050
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
samiwaris2
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
Ahmet Bulut
 
Python slides for the beginners to learn
Python slides for the beginners to learnPython slides for the beginners to learn
Python slides for the beginners to learn
krishna43511
 
program on python what is python where it was started by whom started
program on python what is python where it was started by whom startedprogram on python what is python where it was started by whom started
program on python what is python where it was started by whom started
rajkumarmandal9391
 
Py-Slides-1.ppt1234444444444444444444444444444444444444444
Py-Slides-1.ppt1234444444444444444444444444444444444444444Py-Slides-1.ppt1234444444444444444444444444444444444444444
Py-Slides-1.ppt1234444444444444444444444444444444444444444
divijareddy0502
 
Python Over View (Python for mobile app Devt)1.ppt
Python Over View (Python for mobile app Devt)1.pptPython Over View (Python for mobile app Devt)1.ppt
Python Over View (Python for mobile app Devt)1.ppt
AbdurehmanDawud
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
shetoooelshitany74
 
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
notwa dfdfvs gf fdgfgh  s thgfgh frg regggnotwa dfdfvs gf fdgfgh  s thgfgh frg reggg
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
Godwin585235
 
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
Py-Slides-1.pptPy-Slides-1.pptPy-Slides-1.pptPy-Slides-1.ppt
v65176016
 
Python for katana
Python for katanaPython for katana
Python for katana
kedar nath
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Introduction to Python Programming .pptx
Introduction to  Python Programming .pptxIntroduction to  Python Programming .pptx
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
1. python programming
1. python programming1. python programming
1. python programming
sreeLekha51
 
python introduction all the students.ppt
python introduction all the students.pptpython introduction all the students.ppt
python introduction all the students.ppt
ArunkumarM192050
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
samiwaris2
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
Ahmet Bulut
 

Recently uploaded (20)

Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptxImpurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
Ad

Python unit 2 is added. Has python related programming content

  • 1. UNIT 02: BASICS OF PYTHON PROGRAMMING Introduction-Python Interpreter-Interactive and script mode -Values and types, variables, operators, expressions, statements, precedence of operators, Multiple assignments, comments, input function, print function, Formatting numbers and strings, implicit/explicit type conversion.
  • 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 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. 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.
  • 4. Python Interpreter • A python interpreter is a computer program that converts each high-level program statement into machine code. • 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
  • 5. Difference between Interpreter and Compiler Compilers Interpreters Compilers translate the entire source code into machine code before execution. Interpreters translate and execute the source code line by line. Compiled code runs faster because it's already translated into machine code. Interpreted code runs slower because it must be translated on the fly. Compilers generate an executable file that can be run independently. Interpreters require the source code to be present at runtime. Compilers display all errors at once after compilation. Interpreters display errors one at a time during execution. Compiled languages include C, C++, and Java. Interpreted languages include Python, Ruby, and JavaScript. Compilers have a longer development cycle due to the compilation step. Interpreters have a shorter development cycle as code can be tested immediately. Compiled code is platform-dependent. Interpreted code is platform-independent.
  • 6. MODES OF PYTHON INTERPRETER 1. Interactive mode 2. Script mode
  • 7. 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: Python, in interactive mode, is good enough to learn, experiment or explore. Working in interactive mode is convenient for beginners and for testing small pieces of code. Drawback: We cannot save the statements and have to retype all the statements once again to re-run them
  • 9. 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.
  • 12. 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.
  • 13. Values and types Value: Value can be any letter ,number or string. Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different data types.) Data type: Every value in Python has a data type. It is a set of values, and the allowable operations on those values.
  • 15. Numeric Data Types type() function is used to determine the type of Python data type. • Integers – This value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals). In Python, there is no limit to how long an integer value can be. • Float – This value is represented by the float class. It is a real number with a 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 – A complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j . For example – 2+3j
  • 17. 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. 1.Strings (Immutable) 2. Lists( mutable) 3. Tuples(Immutable)
  • 18. Strings • A String in Python consists of a 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.
  • 19. Indexing String A H E L L 0 Positive Index 0 1 2 3 4 Negative Index -5 -4 -3 -2 -1 Example: A[0] or A[-5] will display “H” Example: A[1] or A[-4] will display “E” Str=‘Python Program’ Str[-3] Str[3] Str[6] Str[7]
  • 20. Operations on string • Indexing • Slicing • Concatenation • Repetitions • Member ship
  • 21. Indexing Accessing the item in the position Slicing Slice operator is used to extract part of a data type Concatenation Adding and printing the characters of two strings. Repetition multiple copies of the same string in, not in (membership operator) Using membership operators to check a particular character is in string or not. Returns true if present.
  • 24. • str='hello w' • print(len(str)) • 7 • print(str[:]) • hello w • print(str[::2]) • Hlow • print(str[::-1]) • w olleh
  • 25. Example • Consider the string S=“Python Programming” • Predict the output: • s[-1] • S[6:12] • S[:4] • S[:] • S[5:5] , s[9:] ,s[0:5] , len(s)
  • 28. in, not in (membership operator)
  • 29. 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 brackets[ ]. • Items in the lists can be of different data types.
  • 30. Operations on lists • Indexing • Slicing • Concatenation • Repetitions • Updation, Insertion, Deletion
  • 31. Indexing Accessing the item in the particular position Slicing Slice operator is used to extract part of a string, or some part of a list Python Concatenation Adding and printing the items of two lists. Repetitions multiple copies of the same string Updating the list Updating the list using index value Inserting an element Inserting an element in 2nd position Removing an element Removing an element by giving the element directly
  • 35. Updating the list Inserting an element Removing an element Note: Update,Insert:Need to give Position Remove:give value alone
  • 36. Tuple • A tuple is same as list, except that the set of elements is enclosed in parentheses instead of square brackets. • 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. • Tuples are faster than lists
  • 37. Basic Operations • Indexing • Slicing • Concatenation • Repetitions Note: concatenate tuple (not "int") to tuple
  • 39. Dictionaries • Lists are ordered sets of objects, whereas dictionaries are unordered sets. • Dictionary is created by using curly brackets. i,e. {} • Dictionaries are accessed via keys and not via their position.
  • 41. Variables • Rules: • 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.
  • 42. Assigning a single value to several variables simultaneously: Assigning multiple values to multiple variables a=b=c=10,20,"Ram" print(c) (10, 20, 'Ram') print(a) (10, 20, 'Ram') a=b=c=100 print(a) 100 print(c) 100
  • 43. Expressions and Statements • Statements: • Instructions that a Python interpreter can executes are called statements. • A statement is a unit of code like creating a variable or displaying a value. • Expressions: • An expression is a combination of values, variables, and operators. >>> n = 17 >>> print(n) a=2 a+3+2 7 str=("Good"+"Morning") print(str) GoodMorning
  • 44. Multiple assignments • same value to multiple variables • Assign multiple values to multiple variables a=b=c=10 print(a) 10 print(b) 10 x, y, z = "Orange", "Banana", "Cherry" print(x) Orange
  • 45. Comments • Comments are the kind of statements that are written in the program for program understanding purpose. • In Python, we use the hash (#) symbol to start writing a comment. • Python Interpreter ignores comment. • If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line. # This is comment line print(“I love my country”) percentage = (minute * 100) / 60 # calculating percentage of an hour #This is #another example #of comment statement
  • 46. OPERATORS • Operators are the constructs which can manipulate the value of operands. • Consider the expression 4 + 5 = 9. • Here, 4 and 5 are called operands and + is called operator
  • 47. Types of Operators • Arithmetic Operators • Comparison (Relational) Operators • Assignment Operators • Logical Operators • Bitwise Operators • Membership Operators • Identity Operators
  • 48. Arithmetic operators • They are used to perform mathematical operations like addition, subtraction, multiplication etc
  • 49. Operator Description + Addition Adds values on either side of the operator - Subtraction Subtracts right hand operand from left hand operand. * Multiplication Multiplies values on either side of the operator / Division Divides left hand operand by right hand operand % Modulus Divides left hand operand by right hand operand and returns remainder ** Exponent Performs exponential (power) calculation on operators // Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed
  • 51. Comparison (Relational) Operators • Comparison operators are used to compare values. • It either returns True or False according to the condition. Assume, a=10 and b=5 ==,< > <= >= !=
  • 53. Assignment Operators • Assignment operators are used in Python to assign values to variables.
  • 54. Operator Description Example = Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c += Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a **= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a
  • 56. Logical Operators • Logical operators are the and, or, not operators And True if both the operands are True Or True if either of the operands is true not True if operands is false
  • 58. Bitwise Operators • A bitwise operation operates on one or more bit patterns at the level of individual bits • Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
  • 59. x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary) & Bitwise AND X&Y= (0000 0000) | Bitwise OR X|y= (0000 1110) ~ Bitwise Not -x=(1111 0101) ^ Bitwise XOR x ^ y =(1111 0001) >> Bitwise right shift X >>2=(0000 0010) << Bitwise left shift X <<2=(0010 1000)
  • 60. Membership Operators • Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or not. • Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are used.
  • 61. Identity Operators • They are used to check if two values (or variables) are located on the same part of the memory. • If the two values are identical: True
  • 62. Precedence of operators • When an expression contains more than one operator, the order of evaluation depends on the order of operations. • PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction)
  • 64. Input function • Input is data entered by user (end user) in the program. • input () function x=input("enter the name:") enter the name:hhh y=int(input("enter the number")) enter the number 3
  • 65. Output function • Output can be displayed to the user using Print statement print (expression/constant/variable) print("Hello") Hello print(2+4) 6 print(6) 6
  • 66. Type Casting(Type Conversion) • Is the process of converting the value of one data type to another Python Implicit Type Conversion Python Explicit Type Conversion
  • 67. Implicit Type Conversion • In this, method, Python converts the data type into another data type automatically. Users don’t have to involve in this process. a=10 b=12.0 c=a+b print(c) 22.0
  • 68. Explicit Type Conversion • This involves converting a data type explicitly using predefined functions like int(), float(), str(), etc., where the programmer specifically directs the type of conversion required. a=10 print(type(a)) <class 'int'> print(float(a)) 10.0 b=12.24 print(type(b)) <class 'float'> print(int(b)) 12 c=15.78 print(int(c)) 15
  • 69. • Convert string to int: (Value Error) • Converting string to int datatype in Python with int() function. If the given string is not number, then it will throw an error. a="Hema" print(int(a)) Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> print(int(a)) ValueError: invalid literal for int() with base 10: 'Hema' a="5" print(int(a)) 5
  • 70. Formatting numbers and strings price = 49 txt ="The price is {price} dollars" print(txt) Output: The price is {price} dollars price = 49 txt =f"The price is {price} dollars" print(txt) Output: The price is 49 dollars
  • 71. • Celsius to Fahrenheit: F = [(C*9/5) +32] • convert kilometers to miles Miles=0.62*km