DEV Community

Saravanan Cn
Saravanan Cn

Posted on

Python Learning Journey:Pure and Impure Fnctions,Global Keyword,if-elif-else and Operator Precedence

1.Pure and Impure Functions in python:

Pure Functions:
A pure function always produce the same output for the same input and does not modify external data.

Example:
`def add(a+b):
return a+b

print(add(10,20));
print(add(10,20));

Output:
30
30
`
Both calls produce the same output because the function depend only on its input values.

Impure Functions:

An impure function can depend on modify external data or produce side effects.

Example:
count = 10

def update():
global count
count = count + 5
return count

print(update())
print(update())

Output:
15
20

Here the function modifies the global variable count.Therefore its result depend on changing external state.

2.Global Keyword in Python:
The Global keyword allows us to modify a global variable from inside a function.

example:
count = 10

def update():
global count
count = 20

update()
print(count)

Output:
20

here:

  • count = 10 creates a global variable.
  • global count tells Python that we want to use global variable inside the function.
  • count=20 updates the global variable. print(count) displays the updted value.

Important:we can read global variable inside a without usage of global.We generally need global when assigned to global variable itsef.

Conditonal Statements:if,elif and else
These statements allow us to execute diffrent blocks of code depends on condition whether it is true or false.

python provide three important keywords:

if
elif
else

`Example:

marks =75

if marks >= 90:
print("Grade A")

elif marks >= 70:
print("Grade B")

else:
print("GRADE c")

Output:
Grade B
`
How does it work?
1.if checks whether the marks are greater than or equal to 90.
2.If that condition is false,elif checks whether marks are greater than equal to 70.
3.if all conditions are false,else executes.

Python checks condition from top to bottom and executes the first matching block.

4.Operator Precedence determines the order in which Python evaluates operators in an expression.

result = 10+5*2
print(result)

Output:
20

multiplication has higher precedence than addition.

Another example using parenthesis:

`result = (10+5)*2
print(result)

Output:
30`

Parenthesis have higher precedence and allow us to control the evaluation order

Basic operator precedence order:
From higher to lower precedence:
1.Parentheses()
2.Exponetiation:**
3.Multiplication,division,floor division,module:*,/,//,%
4.Addition and subtraction.
5.comparison operators:==,<=,>=,<,>,!=
Logical NOT:not
Logical AND:and
Logical OR:or

Top comments (0)