0% found this document useful (0 votes)
24 views66 pages

Expressions

The document discusses different types of expressions in Python like arithmetic, relational, logical and integral expressions. It also covers operators, typecasting, input function, statements, augmented assignment and precedence and associativity of operators.

Uploaded by

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

Expressions

The document discusses different types of expressions in Python like arithmetic, relational, logical and integral expressions. It also covers operators, typecasting, input function, statements, augmented assignment and precedence and associativity of operators.

Uploaded by

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

Unit-1

Variables,Expression, and Statements


Expressions
An expression is a combination of values(constants),variables
and operators.
An expression may also include call to functions and objects.
Operators are symbols that represent particular action. Operands
participate in the action performed by operators.
1. Constant Expressions: These are the expressions that have
constant values only.
# Constant Expressions
x = 15 + 1.3
print(x)
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators,
and sometimes parenthesis. The result of this type of expression is also a numeric value. The
operators used in these expressions are arithmetic operators like addition, subtraction, etc. Here are
some arithmetic operators in Python:

Operators Syntax Functioning


+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
x = 40
y = 12

add = x + y
sub = x - y
pro = x * y
div = x / y

print(add)
print(sub)
print(pro)
3. Integral Expressions: These are the kind of expressions that produce
only integer results after all computations and type conversions.
Example:

a = 13
b = 12.0

c = a + int(b)
print(c)
5. Relational Expressions: In these types of expressions, arithmetic expressions are
written on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions
are evaluated first, and then compared as per relational operator and produce a boolean
output in the end. These expressions are also called Boolean expressions.

Example:

# Relational Expressions
a = 21
b = 13
c = 40
d = 37

p = (a + b) >= (c - d)
print(p)
6. Logical Expressions: These are kinds of expressions that result in either
True or False. It basically specifies one or more conditions. For example,
(10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so it
will return False. Studying logical expressions, we also come across some
logical operators which can be seen in logical expressions most often.
Here are some logical operators in Python:
Operator Syntax Functioning
and P and Q It returns true if both P and Q are true
otherwise returns false
or P or Q It returns true if at least one of P and Q
is true
not not P It returns true if condition P is false
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
Augmented assignment
Augmented assignment is a combination of an arithmetic or a binary
operation and an assignment operation in a single statement.
We can combine arithmetic operators in assignments to form an augmented
assignment statement.
The combined operations of the augmented assignments are represented
using the following operators : +=, -=, *=, /=, %=
Let us consider a simple example:
a += b
The above statement is a shorthand for the below simple statement.
a=a+b
In augmented assignment statements, the left-hand side is evaluated before
the right-hand side
Let us discuss with a simple example:
a += b
Here the left-hand side i.e. a is evaluated first, then value of b is evaluated
and then addition is performed, and finally the addition result is written back
to a.
An augmented assignment expression like
x += 1
can be rewritten as
x=x+1
Both the above statements give out similar result, but the effect is
slightly different.
In the augmented version, the value of x is evaluated only once.
Furthermore, whenever feasible, the actual operation takes place in
the existing memory location of x, without creating a new memory
space and then assigning it to the target variable
type() function and Typecasting
 type function is used to find the data type of a given
variable in Python.
 For example:
a = 31
type(a) #class<int>

b = “31”
type(b) #class<str>
Example Program
Typecasting
 A number can be converted into a string and vice versa (if possible)

 There are many functions to convert one data type into another.

 Str(31) # ”31” Integer to string conversion

 int(“32”) # 32 String to int conversion


 float(32) #32.0 Integer to float conversion
… and so on

 Here “31” is a string literal, and 31 is a numeric literal.


Input() function
 This function allows the user to take input from the keyboard as a
string.
Syntax:
a = input(“Enter name”)
#if a is “student”, the user entered
 Note: The output of the input function is always a string even if the
number is entered by the user.

 Suppose if a user enters 34, then this 34 will automatically convert to


“34” string literal.
Instructions
 An Instruction is an order/command given to a computer
processor by a computer program to perform some
mathematical or logical manipulations (calculations).

 Each and every line or a sentence in any programming


language is called an instruction.
Statement in python
 Any Instruction that a python interpreter can execute is
called a Statement.
 The execution of a statement changes state
 Execution of a statement may or may not produces or
displays a result value, it only does whatever the
statement says.
 For Example:
a=5;
Operators in Python
The following are some common operators in Python:

1. Arithmetic Operators (+, -, *, /, etc.)


2. Assignment Operators (=, +=, -=, etc.)
3. Comparison Operators (==, >=, <=, >, <, !=, etc.)
4. Logical Operators (and, or, not)
5. Identity Operators
6. Membership Operators
7. Bitwise Operators
1. Arithmetic Operators
Practice Question
 Write a program that performs all the arithmatic operation
on two numbers.
2. Assignment Operators
3. Comparision Operator (Relational
Operator)
4. Logical Operators
Example ( logical or )
Example (logical and)
Example ( logical not )
5. Identity Operators
Example ( is )
Example ( is not )
6. Membership Operators
Example ( in )
Example ( not in )
7. Bitwise Operators
 In Python, bitwise operators are used to performing
bitwise calculations on integers. The integers are first
converted into binary and then operations are performed
on bit by bit, hence the name bitwise operators. Then the
result is returned in decimal format.

 Note: Python bitwise operators work only on integers.


Bitwise AND operator
 Returns 1 if both the bits are 1 else 0.
 Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a & b = 1010
&
0100
= 0000
= 0 (Decimal)
Bitwise or operator
 Returns 1 if either of the bit is 1 else 0
 Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a | b = 1010
|
0100
= 1110
= 14 (Decimal)
 Most of the bitwise operators are binary, which means
that they expect two operands to work with, typically
referred to as the left operand and the right operand.
Bitwise NOT (~) is the only unary bitwise operator since it
expects just one operand.
Bitwise not operator
 Returns one’s complement of the number.
 Example:
a = 10 = 1010 (Binary)

~a = ~1010
= -(1010 + 1)
= -(1011)
= -11 (Decimal)
Bitwise xor operator
 Returns 1 if one of the bits is 1 and the other is 0 else
returns false.
 Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a ^ b = 1010
^
0100
= 1110
= 14 (Decimal)
Bitwise right shift
 Shifts the bits of the number to the right and fills 0 on
voids left( fills 1 in the case of a negative number) as a
result.
 Gets similar results as of dividing the number with some
power of two.
 Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

 Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
Bitwise left shift
 Shifts the bits of the number to the left and fills 0 on voids
right as a result.
 Gets similar results as of multiplying the number with
some power of two.
 Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20

 Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
Precedence of Python Operators
There can be multiple operators in one expression as well.
 To evaluate these types of expressions there is a rule of
precedence in Python. It guides the order in which these
operations are carried out.
 For example, multiplication has higher precedence than
subtraction.
>>> 10 - 4 * 2
2 (result)
 But we can change this order using parentheses () as it
has higher precedence than multiplication.
 For Example:
Parentheses () has higher precedence
>>> (10 - 4) * 2
12 (Result)
 The operator precedence in Python is listed in the
following table. It is in descending order (upper group has
higher precedence than the lower ones).
Associativity of Python Operators
 We can see in the above table that more than one
operator exists in the same group. These operators have
the same precedence.

 When two operators have the same precedence,


associativity helps to determine the order of operations.
 Associativity is the order in which an expression is
evaluated that has multiple operators of the same
precedence. Almost all the operators have left-to-right
associativity.

 For example, multiplication and floor division have the


same precedence. Hence, if both of them are present in
an expression, the left one is evaluated first.
Example
 Left-right associativity
print(5 * 2 // 3)
# Output: 3

 Shows left-right associativity


print(5 * (2 // 3))
# Output: 0
Statement vs Expressions

Statement Expressions
 A statement executes something  An expression evaluates to a
 Execution of a statement may or value.
may not produces or displays a  Evaluation of an expression
result value, it only does whatever always Produces or returns a
the statement says. result value.
 Every statement can be an  Every expression can’t be a
expression. statement
 Example: >>> x = 3  Example: >>> a + 16
>>> print(x) >>> 20
Output: 3
Commments
 Lines in the code that are ignored by the python
interpreter during the execution of the program.
 Comments enhance the readability of the code and help
the programmers to understand the code very carefully.
Types of comments
 There are three types of comments in Python –

1. Single line Comments


2. Multiline Comments
3. Docstring Comments
1. Single line Comment
 A single-line comment
begins with a hash (#)
symbol and is useful in
mentioning that the whole
line should be considered
as a comment until the
end of the line.
 Example:
Multi-Line Comments
 Python does not provide the option for multiline
comments. However, there are different ways through
which we can write multiline comments.
1. Using Multiple Hashtags (#)
2. Using String Literals
Using Multiple Hastags
Using String Literals
 Python ignores the string
literals that are not
assigned to a variable so
we can use these string
literals as a comment.
Docstring
 Python docstring is the string literals with triple quotes
that are appeared right after the function. It is used to
associate documentation that has been written with
Python modules, functions, classes, and methods. It is
added right below the functions, modules, or classes to
describe what they do. In Python, the docstring is then
made available via the __doc__ attribute.
Example
 def multiply(a, b):
 """Multiplies the value of a and b"""
 return a*b

 # Print the docstring of multiply function


 print(multiply.__doc__)
Operations on string
 Python string is a sequence of Unicode characters that is
enclosed in the quotations marks.
 we will discuss the in-built function i.e. the functions
provided by the Python to operate on strings.
 Strings can be created by enclosing characters inside a
single quote or double-quotes. Even triple quotes can be
used in Python but generally used to represent multiline
strings and docstrings.

 Some of the important functions of strings will be


discussed in further slides.
 lower(): Converts all uppercase characters in a string into
lowercase
 upper(): Converts all lowercase characters in a string into
uppercase
 title(): Convert string to title case
 capitalize(): Converts the first character of the string to
a capital (uppercase) letter
 startswith(): Returns true if the string starts with the
specified value
 count(): Returns the number of occurrences of a
substring in the string.
 endswith(): Returns true if the string ends with the
specified value
 find(): Searches the string for a specified value and
returns the position of where it was found
 index(): Searches the string for a specified value and
returns the position of where it was found
 isalnum(): Returns True if all characters in the string are
alphanumeric
 isalpha(): Returns True if all characters in the string are in
the alphabet
 islower(): Returns True if all characters in the string are
lower case
 isupper(): Returns True if all characters in the string are
upper case
Example
text = 'this is pYthon ClAss'
print("\nUpdated String after uppercase:")
print(text.upper())
print("\nUpdated String after lowercase:")
print(text.lower())
print("\nUpdated String afer titlecase:")
print(text.title())
# original string never changes
print("\nOriginal String")
print(text)

OUTPUT SCREEN-->

You might also like