Expression Evaluation
A Python program contains one or more statements. A statement contains zero or more expressions. Python executes by evaluating it's expressions to values one by one. Python evaluates an expression by evaluating the sub-expressions and substituting their values.
An expression is not always a mathematical expression in Python. A value by itself is a simple expression, and so is a variable.
There are various types of expressions :
Literal Expressions :
A literal expression evaluates to the value it represents.
Example :
program="hello python" # literal expression
a=10 # literal expression
b=7.89 # literal expression
print(program)
print(a)
print(b)
Output :
hello python
10
7.89
Binary Expression :
A binary expression consists of a binary operator applied to two operand expression.
Example :
a=2*6 # binary expression
b=8-6 # binary expression
print(a)
print(b)
Output :
12
2
Unary Expressions :
An unary expression contains one operator and single operand.
Example :
a=-(5/5) # unary expression like -(a)
b=-(3*4) # unary expression like -(b)
c=-(2**4) # unary expression like -(c)
print(a)
print(b)
print(c)
Output :
-1
-12
-16
Compound Expressions :
A compound expression is a series of simple expressions joined by arithmetic operators. Compound expression must return a numeric value.
Example :
a=3*2+1 # Compound expression
b=2+6*2 # Compound expression
c=(2+6)*2 # Compound expression
print(a)
print(b)
print(c)
Output :
7
14
16
Variable Access Expressions :
A variable access expression allows us to access the value of a variable.
Example :
x=10
print((x+2)*4) # value access of variable 'x'
Output :
48
No comments:
Post a Comment