0% found this document useful (0 votes)
147 views38 pages

Basics of Pythhon N Operators

The document discusses the basics of Python including its structure, character set, input/output functions, indentation, tokens, keywords, identifiers, literals, operators, and comparison operators. It provides examples to illustrate each concept. The key topics covered are the main components of a Python program, the valid characters recognized by Python, how input is handled, the importance of indentation, the basic building blocks like tokens and keywords, data types like literals, and operators for mathematical and logical operations.

Uploaded by

Rishu Kaul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views38 pages

Basics of Pythhon N Operators

The document discusses the basics of Python including its structure, character set, input/output functions, indentation, tokens, keywords, identifiers, literals, operators, and comparison operators. It provides examples to illustrate each concept. The key topics covered are the main components of a Python program, the valid characters recognized by Python, how input is handled, the importance of indentation, the basic building blocks like tokens and keywords, data types like literals, and operators for mathematical and logical operations.

Uploaded by

Rishu Kaul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

BASICS OF

PYTHON,
OPERATORS &
EXPRESSIONS
Structure of a python program

Program
|->Module -> main program
| -> functions
| ->libraries
|->Statements -> simple statement
| ->compound statement
|->expressions -> Operators
| -> expressions
|---- objects ->data model
2
Python basics
Python 3.0 was released in 2008. Although this version is supposed
to be backward incompatibles, later on many of its important
features have been back ported to be compatible with version 2.7
Python Character Set
A set of valid characters recognized by python. Python uses the traditional ASCII
character set. The latest version recognizes the Unicode character set. The ASCII
character set is a subset of the Unicode character set.
Letters :– A-Z,a-z
Digits :– 0-9
Special symbols :– Special symbol available over keyboard
White spaces:– blank space,tab,carriage return,new line, form feed
Other characters:- Unicode
3
var1=‘Computer Science'
var2=‘Informatics Practices' Input and Output
print(var1,' and ',var2,' )
Output :-
Computer Science and Informatics Practices
raw_input() Function In Python allows a user to give input to a program from a
keyboard but in the form of string.
NOTE : raw_input() function is deprecated in python 3
e.g.
age = int(raw_input(‘enter your age’))
percentage = float(raw_input(‘enter percentage’))
input() Function In Python allows a user to give input to a program from a keyboard
but returns the value accordingly.
e.g.
age = int(input(‘enter your age’))
C = age+2 #will not produce any error
NOTE : input() function always enter string value in python 3.so on need int(),float()
4 function can be used for data conversion.
Indentation
Indentation refers to the spaces applied at the beginning of a code line. In other
programming languages the indentation in code is for readability only, where as the
indentation in Python is very important.
Python uses indentation to indicate a block of code or used in block of codes.
E.g.1
if 3 > 2:
print(“Three is greater than two!") //syntax error due to not indented

E.g.2
if 3 > 2:
print(“Three is greater than two!") //indented so no error

5
Token

Smallest individual unit in a program is known as token.


1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators/Delimiters

6
Keywords
Reserve word of the compiler/interpreter which can’t be
used as identifier. and exec not
as finally or
assert for pass
break from print
class global raise
continue if return
def import try
del in while
elif is with
else lambda yield
except
7
Identifiers
A Python identifier is a name used to identify a variable, function, class,
module or other object.
*An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
* Python does not allow special characters
* Identifier must not be a keyword of Python.
*Python is a case sensitive programming language. Thus, Rollnumber
and rollnumber are two different identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no

8
Identifiers-continue
Some additional naming conventions
1. Class names start with an uppercase letter. All other
identifiers start with a lowercase letter.
2. Starting an identifier with a single leading underscore
indicates that the identifier is private.
3. Starting an identifier with two leading underscores
indicates a strong private identifier.
4. If the identifier also ends with two trailing
underscores, the identifier is a language-defined
9
special name.
Literals
Literals in Python can be defined as number, text, or other data that
represent values to be stored in variables.

Example of String Literals in Python


name = ‘Johni’ , fname =“johny”
Example of Integer Literals in Python(numeric literal) age =
22
Example of Float Literals in Python(numeric literal) height
= 6.2
Example of Special Literals in Python
10 name = None
Literals
Escape sequence/Back slash character constants
Escape Description
Sequence
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
11
\xhh Character with hex value hh
Operators
Operators can be defined as symbols that are used to
perform operations on operands.

Types of Operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
12
7. Identity Operators
Operator
Operators are special symbols in Python that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand. Arithmetic operators
Used for mathematical operation
Operator Meaning Example
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y

/ Divide left operand by the right one (always results into x/y
float)

% Modulus - remainder of the division of left operand by the x % y (remainder of x/y)


right
Floor division - division that results into whole
// x // y
number adjusted to the left in the number line
13 ** Exponent - left operand raised to the power of right x**y (x to the power y)
Arithmatic operator continue
e.g.
x =5
y =4
print('x + y =',x+y) print('x
- y =',x-y) print('x * y
=',x*y) print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
OUTPUT
('x + y =', 9)
('x - y =', 1)
('x * y =', 20)
('x / y =', 1)
('x // y =', 1)
('x ** y =', 625)

14
Arithmatic operator continue

# EMI Calculator program in Python

def emi_calculator(p, r, t):


r = r / (12 * 100) # one month interest
t = t * 12 # one month period
emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1)
return emi

# driver code
principal = 10000;
rate = 10;
time = 2;
emi = emi_calculator(principal, rate, time);
print("Monthly EMI is= ", emi)
15
Comparison operators -used to compare values
Operator Meaning Example

> Greater that - True if left operand is greater than the right x>y

< Less that - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand is greater than


>= x >= y
or equal to the right

<= Less than or equal to - True if left operand is less than or equal to x <= y
the right
16
Comparison operators continue
e.g.
x = 101
y = 121
print('x > y is',x>y) print('x < y
is',x<y) print('x == y is',x==y)
print('x != y is',x!=y) print('x >= y
is',x>=y) print('x <= y is',x<=y)

Output
('x > y is', False)
('x < y is', True)
('x == y is', False)
('x != y is', True)
('x >= y is', False)
('x <= y is', True)

17
Logical operators
Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

e.g.
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Outpur
('x and y is', False)
('x or y is', True)
('not x is', False)
18
Bitwise operators
Used to manipulate bit values.

Operator Meaning Example

& Bitwise AND x& y


| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>> 2
<< Bitwise left shift x<< 2

19
Bitwise operators continue
a=6
b=3
print
('a=',a,':',bin(a),'b=',b,':',bin(b)) c
=0
c = a & b; Output
print ("result of AND is ", c,':',bin(c)) ('a=', 6, ':', '0b110', 'b=', 3, ':', '0b11')
c = a | b; ('result of AND is ', 2, ':', '0b10')
print ("result of OR is ", ('result of OR is ', 7, ':', '0b111')
c,':',bin(c)) c = a ^ b; ('result of EXOR is ', 5, ':', '0b101')
print ("result of EXOR is ", ('result of COMPLEMENT is ', -7, ':', '-0b111')
c,':',bin(c)) c = ~a;
('result of LEFT SHIFT is ', 24, ':', '0b11000')
print ("result of COMPLEMENT is ",
c,':',bin(c))
('result of RIGHT SHIFT is ', 1, ':', '0b1')
c = a << 2;
print ("result of LEFT SHIFT is ",
c,':',bin(c)) c = a >> 2;
print ("result of RIGHT SHIFT is ",
20 c,':',bin(c))
Python Membership Operators
Test for membership in a sequence

Operator Description
in Evaluates to true if it finds a variable in the specified sequence and false otherwise.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

e.g.
a=5
b = 10
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list") output
else: Line 1 - a is available in the given list
21 print ("Line 2 - b is available in the given list") Line 2 - b is not available in the given list
Python Identity Operators
Operat Description
or
Evaluates to true if the variables on either side of the operator point to the same
is
object and false otherwise.
Evaluates to false if the variables on either side of the operator point to the same
is not
object and true otherwise.

e.g.
a = 10
b = 10
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity") else:
print ("Line 2 - a and b do not have same identity") OUTPUT
('Line 1', 'a=', 10, ':', 20839436, 'b=', 10, ':', 20839436)
Line 2 - a and b have same identity

22
Operators Precedence :highest precedence to lowest precedence table
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= Assignment operators
+=
*= **=
is is not Identity operators
in not in Membership operators
23 not or and Logical operators
Punctuators/Delimiters
Used to implement the grammatical and structure of a
Syntax.Following are the python punctuators.

24
#function definition comment
def keyArgFunc(empname, emprole):
print ("Emp Name: ", empname) Function
print ("Emp Role: ", emprole) indentation
return;
A = 20 expression
print("Calling in proper sequence")
keyArgFunc(empname = "Nick",emprole = "Manager" )
print("Calling in opposite sequence") statements
keyArgFunc(emprole = "Manager",empname = "Nick")

A python program contain the following components


a. Expression
b. Statement
c. Comments
d. Function
25
e. Block &n indentation Barebone of a python program
a. Expression : - which is evaluated and produce result. E.g. (20 + 4) / 4
b. Statement :- instruction that does something.
e.g
a = 20
print("Calling in proper sequence")
c. Comments : which is readable for programmer but ignored by python
interpreter
i. Single line comment: Which begins with # sign.
ii. Multi line comment (docstring): either write multiple line beginning with # sign or use
triple quoted multiple line. E.g.
‘’’this is my
first
python multiline comment ‘’’
d. Function
a code that has some name and it can be reused.e.g. keyArgFunc in above program
d. Block & indentation : group of statements is block.indentation at same level
create a block.e.g. all 3 statement of keyArgFunc function

26
Variable is a name given to a memory location. A variable can
consider as a container which holds value. Python is a type infer
language that means you don't need to specify the datatype of
variable.Python automatically get variable datatype depending
upon the value assigned to the variable.
Assigning Values To Variable
name = ‘python' # String Data Type
sum = None # a variable without value
a = 23 # Integer
b = 6.2 # Float
sum = a + b
print (sum)
Multiple Assignment: assign a single value to many variables
a = b = c = 1 # single value to multiple variable
a,b = 1,2 # multiple value to multiple variable
27 a,b = b,a # value of a and b is swaped Variables
Variables
Variable Scope And Lifetime in Python Program
1. Local Variable
def fun():
x=8
print(x)

fun()
print(x) #error will be shown
2.Global Variable
x=8
def fun():
print(x) # Calling variable ‘x’ inside fun()

fun()
print(x) # Calling variable ‘x’ outside fun()
28
Variables
▸ Concept of L Value and R Value in variable
▸ Lvalue and Rvalue refer to the left and right side of the
assignment operator. The Lvalue (pronounced: L value)
concept refers to the requirement that the operand on the left
side of the assignment operator is modifiable, usually a
variable. Rvalue concept fetches the value of the expression or
operand on the right side of the assignment operator.
example:
amount = 390
The value 390 is pulled or fetched (Rvalue) and stored into the
variable named amount (Lvalue); destroying the value
29 previously stored in that variable.
Dynamic typing

Data type of a variable depend/change upon the value


assigned to a variable on each next statement.
X = 25 # integer type
X = “python” # x variable data type change to string on just
next line
Now programmer should be aware that not to write like this:
Y = X / 5 # error !! String cannot be devided
30
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to
think of constants as containers that hold information which cannot be changed
later.
In Python, constants are usually declared and assigned in a module. Here, the
module is a new file containing variables, functions, etc which is imported to the
main file. Inside the module, constants are written in all capital letters and
underscores separating the words.
Create a constant.py:
PI = 3.14

Create a main.py:
import constant
print(constant.PI)
Note: In reality, we can not create constants in Python. Naming them in all capital
letters is a convention to separate them from variables, however, it does not
actually prevent reassignment, so we can change it’s value
31
print() Function In Python is used to print output on the screen.
Syntax of Print Function - print(expression/variable)
e.g.
print(122)
Output :-
122
print('hello India')
Output :-
hello India

print(‘Computer',‘Science')
print(‘Computer',‘Science',sep=' & ')
32 print(‘Computer',‘Science',sep=' & ',end='.')

Output :-
Computer Science
Computer & Science
Computer & Science. Input and Output
Expression
It is a valid combination of operators,literals and
variable.
1. Arithmatic expression :- e.g. c=a+b
2. Relational expression :- e.g. x>y
3. Logical expression :- a or b
4. String expression :- c=“comp”+”sc”

33
Type conversion
▸ The process of converting the value of one data type (integer, string,
float, etc.) to another
▸ data type is called type conversion.
▸ Python has two types of type conversion.
▸ Implicit Type
Conversion Explicit
Type Conversion

▸ Implicit Type Conversion:


▸ In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user involvement.
e.g.
num_int = 12
num_flo = 10.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

OUTPUT
('datatype of num_int:', <type 'int'>)
('datatype of num_flo:', <type 'float'>)
('Value of num_new:', 22.23)
('datatype of num_new:', <type 'float'>)

35
Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(),float(),str() etc.
e.g.
num_int = 12
num_str = "45"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
OUTPUT
('Data type of num_int:', <type 'int'>)
('Data type of num_str before Type Casting:', <type 'str'>)
('Data type of num_str after Type Casting:', <type 'int'>)
('Sum of num_int and num_str:', 57)
36 ('Data type of the sum:', <type 'int'>)
It is a standard module in Python. To use mathematical functions of this
module,we have to import the module using import math.
Function Description Example
MATH MODULE
ceil(n) It returns the smallest integer greater than or equal to n. math.ceil(4.2) returns 5
factorial(n) It returns the factorial of value n math.factorial(4) returns 24
floor(n) It returns the largest integer less than or equal to n math.floor(4.2) returns 4
fmod(x, y) It returns the remainder when n is divided by y math.fmod(10.5,2) returns 0.5
exp(n) It returns e**n math.exp(1) return 2.718281828459045
log2(n) It returns the base-2 logarithm of n math.log2(4) return 2.0
log10(n) It returns the base-10 logarithm of n math.log10(4) returns 0.6020599913279624
pow(n, y) It returns n raised to the power y math.pow(2,3) returns 8.0
sqrt(n) It returns the square root of n math.sqrt(100) returns 10.0
cos(n) It returns the cosine of n math.cos(100) returns
0.8623188722876839
sin(n) It returns the sine of n math.sin(100) returns -
0.5063656411097588
tan(n) It returns the tangent of n math.tan(100) returns -
0.5872139151569291
pi It is pi value (3.14159...) It is (3.14159...)
e It is mathematical constant e (2.71828...) It is (2.71828...)
37
😉 THANK YOU

38

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy