Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

U2 of python

Python unit 2 given as presentation

Uploaded by

swarna
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

U2 of python

Python unit 2 given as presentation

Uploaded by

swarna
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

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 Interpreters translate and execute the source
machine code before execution. code line by line.

Compiled code runs faster because it's already Interpreted code runs slower because it must be
translated into machine code. translated on the fly.

Compilers generate an executable file that can Interpreters require the source code to be
be run independently. present at runtime.
Compilers display all errors at once after Interpreters display errors one at a time during
compilation. execution.
Compiled languages include C, C++, and Java. Interpreted languages include Python, Ruby, and
JavaScript.
Compilers have a longer development cycle due Interpreters have a shorter development cycle as
to the compilation step. 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
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.
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
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 Using membership operators to check a


(membership particular character is in string or not. Returns
operator) 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:Nee
d 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
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.
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:

a=b=c=100
print(a)
100
print(c)
100

Assigning multiple values to multiple variables


a=b=c=10,20,"Ram"
print(c)
(10, 20, 'Ram')
print(a)
(10, 20, 'Ram')
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
>>> n = 17
a value.
>>> print(n)

• Expressions:
• a=2
An expression is a combination of values, variables, and operators.
a+3+2
7
str=("Good"+"Morning")
print(str)
GoodMorning
Multiple assignments

• same value to multiple variables


a=b=c=10
print(a)
10
print(b)
10

• Assign multiple values to multiple variables

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 #This is


print(“I love my country”) #another example
percentage = (minute * #of comment statement
100) / 60 # calculating
percentage of an hour
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
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

==,<
>
<=
>=
!=
Assignment Operators

• Assignment operators are used in Python


to assign values to variables.
Operator Description Example
= Assigns values from right side operands to c = a + b assigns value of a
left side operand + b into c

+= Add It adds right operand to the left operand c += a


AND and assign the result to left operand is equivalent to c = c + a

-= Subtract It subtracts right operand from the left c -= a


AND operand and assign the result to left is equivalent to c = c - a
operand

*= Multiply It multiplies right operand with the left c *= a


AND operand and assign the result to left is equivalent to c = c * a
operand

**= Performs exponential (power) calculation c **= a


Exponent on operators and assign value to the left is equivalent to c = c ** a
AND operand

//= Floor It performs floor division on operators and c //= a is equivalent to c = c


Division assign value to the left operand // a
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


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)
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

You might also like