Sunday, 23 February 2025

Conditional Instructions

 Program execution transfer instructions in 8086 microprocessor

Program execution transfer instructions are similar to branching instructions and refer to the act of switching execution to a different instruction sequence as a result of executing a branch instruction.

The two types of program execution transfer instructions are:

  1. Unconditional
  2. Conditional

1. Unconditional Program Execution Transfer Instructions – These instruction always execute.

Opcode

Operand

Explanation

Example

CALL

address

calls a subroutine and saves the return address on the stack

CALL 2050

RET

none

returns from the subroutine to the main program

RET

JUMP

address

transfers the control of execution to the specified address

JUMP 2050

LOOP

address

loops through a sequence of instructions until CX=0

LOOP 2050

Here the address can be specified directly or indirectly.

2. Conditional Program Execution Transfer Instructions : These instructions only execute when the specified condition is true.

Opcode

Operand

Explanation

Example

JC

address

jump if CF = 1

JC 2050

JNC

address

jump if CF = 0

JNC 2050

JZ

address

jump if ZF = 1

JZ 2050

JNZ

address

jump if ZF = 0

JNZ 2050

JO

address

jump if OF = 1

JO 2050

JNO

address

jump if OF = 0

JNO 2050

JP

address

jump if PF = 1

JP 2050

JNP

address

jump if PF = 0

JNP 2050

JPE

address

jump if PF = 1

JPE 2050

JPO

address

jump if PF = 0

JPO 2050

JS

address

jump if SF = 1

JS 2050

JNS

address

jump if SF = 0

JNS 2050

JA

address

jump if CF=0 and ZF=0

JA 2050

JNBE

address

jump if CF=0 and ZF=0

JNBE 2050

JAE

address

jump if CF=0

JAE 2050

JNB

address

jump if CF=0

JNB 2050

JBE

address

jump if CF = 1 or ZF = 1

JBE 2050

JNA

address

jump if CF = 1 or ZF = 1

JNA 2050

JE

address

jump if ZF = 1

JE 2050

JG

address

jump if ZF = 0 and SF = OF

JG 2050

JNLE

address

jump if ZF = 0 and SF = OF

JNLE 2050

JGE

address

jump if SF = OF

JGE 2050

JNL

address

jump if SF = OF

JNL 2050

JL

address

jump if SF != OF

JL 2050

JNGE

address

jump if SF != OF

JNGE 2050

JLE

address

jump if ZF = 1 or SF != OF

JLE 2050

JNG

address

jump if ZF = 1 or SF != OF

JNG 2050

JCXZ

address

jump if CX = 0

JCXZ 2050

LOOPE

address

loop while ZF = 1 and CX = 0

LOOPE 2050

LOOPZ

address

loop while ZF = 1 and CX = 0

LOOPZ 2050

LOOPNE

address

loop while ZF = 0 and CX = 0

LOOPNE 2050

LOOPNZ

address

loop while ZF = 0 and CX = 0

LOOPNZ 2050

Here the address can be specified directly or indirectly.
CF is carry flag
ZF is zero flag
OF is overflow flag
PF is parity flag
SF is sign flag
CX is the register

 

Logical instructions

 Logical instructions:

The processor instruction set provides the instructions AND, OR, XOR, TEST, and NOT Boolean logic, which tests, sets, and clears the bits according to the need of the program.

The format for these instructions −

Sr.No.

Instruction

Format

1

AND

AND operand1, operand2

2

OR

OR operand1, operand2

3

XOR

XOR operand1, operand2

4

TEST

TEST operand1, operand2

5

NOT

NOT operand1

 

1) AND: Logical AND

General form: AND destination, source

 This instruction ANDs bits of destination and source. The result is stored in destination.

 The source can be immediate number, a register or memory location.

 The destination can be a register or a memory location.

 Both operands cannot be memory locations.

 The size of operand must be same.

 Flags affected:

 OF = CF = 0 (reset)

 P, S and Z flags are modified.

 A (Auxiliary Carry) flag is undefined.

Examples:

AND AX, 8000H

AND BH, CL

AND DX, [BX]

 

2) OR: Logical OR

General form: OR destination, source

 This instruction performs OR operation on bits of source and destination. The result is stored in destination.

 The source can be immediate number, a register or memory location.

 The destination can be a register or a memory location.

 Both operands cannot be memory locations.

 The size of operand must be same.

 Flags affected:

 OF = CF = 0 (reset)

 P, S and Z flags are modified.

 A (Auxiliary Carry) flag is undefined.

 

Examples:

OR BX, CX

OR AL, DL

OR [BX], AH

OR AL, 30H

 

3) XOR: Logical Exclusive OR

General form: XOR destination, source

 This instruction performs logical exclusive OR operation on bits of source and destination. The result is stored in destination.

 The source can be immediate number, a register or memory location.

 The destination can be a register or a memory location.

 Both operands cannot be memory locations.

 The size of operand must be same.

 Flags affected:

 OF = CF = 0 (reset)

 P, S and Z flags are modified.

 A (Auxiliary Carry) flag is undefined.

 Examples:

XOR AL, BL

XOR CX, DX

XOR BX, 5000H

XOR [SI], FFH

XOR DX, DX

 

4) NOT: Invert each bit of operand

The NOT instruction implements the bitwise NOT operation. NOT operation reverses the bits in an operand. The operand could be either in a register or in the memory.

General form: XOR destination

 This instruction complements the contents of destination.

 The destination can be register or memory location.

 No flags are affected.

 Examples:

NOT BX

NOT BYTE PTR[BX]

NOT WORD PTR[SI]

NOT CL

 

5) TEST: AND operands to update flags.

The TEST instruction works same as the AND operation, but unlike AND instruction, it does not change the first operand. So, if we need to check whether a number in a register is even or odd, we can also do this using the TEST instruction without changing the original number.

General form: TEST destination, source M.A.Ansari Page 13

This instruction logically ANDs the bits of source and destination.

No operand will change, only flags are updated.

Flags affected:

OF = CF = 0 (reset)

P, S and Z flags are modified.

A (Auxiliary Carry) flag is undefined

Examples:

TEST AX, BX

TEST [0500H], 06H

TEST AL, CL

Functions in Python

Unit 3 - 3.1 Functions in Python

Functions in Python are reusable blocks of code that perform a specific task. They help make code more organized, readable, and reusable.

Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Some Benefits of Using Functions

  • Increase Code Readability 

Types of Functions in Python

1. Built-in Functions – Predefined functions like print(), len(), type(), etc.

2. User-Defined Functions – Functions created by the user using the def keyword.

3. Lambda Functions – Anonymous, single-expression functions created using the lambda keyword.

4. Recursive Functions – Functions that call themselves to solve problems iteratively.

Defining a Function :A function is defined using the def keyword

python

def greet(name):

    """Function to greet a person"""

    print(f"Hello, {name}!")

 

# Calling the function

greet("Alice")

Function Explanation

  • def – Keyword to define a function.
  • greet – Function name.
  • name – Parameter (input).
  • print(f"Hello, {name}!") – Function body (execution statements).
  • greet("Alice") – Function call.

Function with Return Value : Functions can return values using return

python

def add(a, b):

    return a + b

result = add(5, 3)

print(result)  # Output: 8


Function with Multiple Return Value

python

def calculate(a, b):

sum_value = a + b

diff_value = a - b

product_value = a * b

return sum_value, diff_value, product_value # Returning multiple values as a tuple

 

# Calling the function

result = calculate(10, 5)

# Accessing the returned values

sum_result, diff_result, product_result = result

print("Sum:", sum_result)

print("Difference:", diff_result)

print("Product:", product_result)

 


Default Arguments : Default values can be assigned to parameters

python

def power(base, exp=2):

    return base ** exp

print(power(3))   # Uses default exp=2, output: 9

print(power(3, 3)) # Output: 27


Variable-Length Arguments

1. *args (Non-keyword arguments) – Allows passing multiple values as a tuple.

python

def sum_all(*numbers):

    return sum(numbers)

print(sum_all(1, 2, 3, 4))  # Output: 10

2. **kwargs (Keyword arguments) – Allows passing multiple key-value pairs as a dictionary.

python

def print_info(**info):

    for key, value in info.items():

        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NY")


Lambda Functions

Short, anonymous functions written using lambda

python

square = lambda x: x ** 2

print(square(5))  # Output: 25


Recursive Functions : A function calling itself

python

def factorial(n):

    if n == 0:

        return 1

    return n * factorial(n - 1)

print(factorial(5))  # Output: 120


Nested Function or Inner Function

A nested function, also called an inner function, is a function defined inside another function. It is used to encapsulate functionality, provide better modularity, and restrict access to certain functionalities within the outer function.

python

def outer_function(message):

    def inner_function():

        print("Message from inner function:", message)

    inner_function()  # Calling the inner function

 

# Calling the outer function

outer_function("Hello, Python!")


Function Scope

1.     Local Scope – Variables declared inside a function.

2.     Global Scope – Variables declared outside functions.

3.     Nonlocal Scope – Used in nested functions.

python

x = 10  # Global variable

def outer():

    x = 5  # Local variable

    def inner():

        nonlocal x

        x += 1

        print(x)  # Output: 6

    inner()

outer()


Python provides many built-in functions that are ready to use without requiring any imports. These functions perform various tasks such as mathematical operations, type conversions, input/output handling, and more.

Common Python Built-in Functions

Mathematical Functions

  • abs(x): Returns the absolute value of x.
  • round(x, n): Rounds x to n decimal places.
  • max(iterable): Returns the maximum value in an iterable.
  • min(iterable): Returns the minimum value in an iterable.
  • sum(iterable): Returns the sum of all elements in an iterable.
  • pow(x, y): Returns x raised to the power of y.

Example:

python

print(abs(-10))       # 10

print(round(3.14159, 2))  # 3.14

print(max([1, 2, 3, 4]))  # 4


Type Conversion Functions

  • int(x): Converts x to an integer.
  • float(x): Converts x to a float.
  • str(x): Converts x to a string.
  • bool(x): Converts x to a boolean.
  • list(iterable): Converts an iterable into a list.
  • tuple(iterable): Converts an iterable into a tuple.
  • set(iterable): Converts an iterable into a set.

Example:

python

print(int("10"))      # 10

print(float("3.14"))  # 3.14

print(str(100))       # '100'

print(list("hello"))  # ['h', 'e', 'l', 'l', 'o']


Input/Output Functions

  • print(value, ...): Displays values on the screen.
  • input(prompt): Accepts user input.
  • len(iterable): Returns the length of an iterable.

Example:

python

name = input("Enter your name: ")

print("Hello,", name)

print(len("Python"))  # 6


Working with Iterables

  • range(start, stop, step): Generates a sequence of numbers.
  • enumerate(iterable): Returns an iterator that yields index-value pairs.
  • zip(iter1, iter2, ...): Combines multiple iterables element-wise.
  • sorted(iterable): Returns a sorted list.
  • reversed(iterable): Returns a reversed iterator.
  • map(function, iterable): Applies a function to each element.
  • filter(function, iterable): Filters elements based on a function.

Example:

python

nums = [1, 2, 3]

squared = list(map(lambda x: x**2, nums))  # [1, 4, 9]

evens = list(filter(lambda x: x % 2 == 0, nums))  # [2]

 

print(squared, evens)


Object Inspection Functions

  • type(obj): Returns the type of an object.
  • id(obj): Returns the memory address of an object.
  • dir(obj): Lists all attributes and methods of an object.

Example:

python

 

x = 10

print(type(x))  # <class 'int'>

print(id(x))    # Memory address of x

print(dir(x))   # List of attributes and methods for an int


File Handling Functions

  • open(filename, mode): Opens a file in a given mode.
  • read(): Reads content from a file.
  • write(text): Writes content to a file.
  • eval()

Example:

python

with open("test.txt", "w") as file:

    file.write("Hello, World!")

 

Data Type-Related Built-in Functions

These functions help with type conversion, checking, and manipulation.

 

Type Conversion Functions

These functions convert values from one data type to another.

Function

Description

int(x)

Converts x to an integer.

float(x)

Converts x to a floating-point number.

str(x)

Converts x to a string.

bool(x)

Converts x to a boolean (True or False).

complex(x, y)

Converts x and y to a complex number (x + yj).

list(iterable)

Converts an iterable to a list.

tuple(iterable)

Converts an iterable to a tuple.

set(iterable)

Converts an iterable to a set.

dict(iterable)

Converts an iterable (like a list of key-value pairs) to a dictionary.


Example

python

print(int("10"))      # 10

print(float("3.14"))  # 3.14

print(str(100))       # '100'

print(bool(0))        # False

print(list("abc"))    # ['a', 'b', 'c']

 

print(tuple([1, 2, 3]))  # (1, 2, 3)

print(set([1, 2, 2, 3]))  # {1, 2, 3}

print(dict([("a",1), ("b", 2)]))  # {'a': 1,'b': 2}




Type Checking Functions

These functions help in checking the type of an object.

Function

Description

type(obj)

Returns the type of an object.

isinstance(obj, class)

Checks if obj is an instance of the given class.

issubclass(sub, sup)

Checks if sub is a subclass of sup.

 

Example

python

x = 10

print(type(x))  # <class 'int'>

print(isinstance(x,int))  # True

print(isinstance(x,float))  # False


class Animal:

pass

 

class Dog(Animal):

pass

 

print(issubclass(Dog,Animal))  # True

 

print(issubclass(Animal,Dog))  # False

 


 Object-Related Built-in Functions

These functions help inspect and manipulate objects.

 

Object Attributes & Methods

Function

Description

dir(obj)

Returns a list of attributes and methods of obj.

id(obj)

Returns the memory address of obj.

hash(obj)

Returns a unique hash value of obj (only for hashable types).

callable(obj)

Checks if obj is callable (like a function).

getattr(obj, name)

Gets the attribute name from obj.

setattr(obj, name, value)

Sets the attribute name of obj to value.

hasattr(obj, name)

Checks if obj has an attribute name.

delattr(obj, name)

Deletes the attribute name from obj.


Example

python

class Sample:

    def __init__(self, value):

        self.value = value

    def show(self):

        print("Value:", self.value)

obj =

Sample(10)

print(dir(obj))  # Lists attributes and methods

 

print(id(obj))   # Memory address of obj

 

print(hash(42))  # Hash value (only for immutable types)

 

print(getattr(obj,"value"))  # 10

 

setattr(obj,"value", 20)

 

print(getattr(obj,"value"))  # 20

 

print(hasattr(obj,"value"))  # True

delattr(obj,"value")

print(hasattr(obj, "value"))  # False


 

Checking If an Object Is Callable

An object is callable if it can be called like a function (e.g., functions, classes with __call__ method).

python

def hello():

 

    return "Hello, World!"

print(callable(hello))  # True

x = 10

print(callable(x))  # False


Summary

Category
Functions
Type Conversion
int(), float(), str(), bool(), complex(), list(), tuple(), set(), dict()
Type Checking type(), isinstance(), issubclass()
Object Inspection dir(), id(), hash(), callable()
Attribute Handling getattr(), setattr(), hasattr(), delattr()

Desktop Virtualisation

Desktop Virtualization ( DV ) Desktop Virtualization ( DV ) is a technique that creates an illusion of a desktop provided to the user. It d...