(Day 06) Task : Function , while loop & Escaping the maze Project :-

Aditya SharmaAditya Sharma
5 min read

1. Function in Python :-

A function is a block of reusable code that performs a specific task.

A function in its simplest form is just a wrapper name for a block of code. You give it name and then when you call the function by that name, all the code within the function block will be executed. It can help us save time and reduce repeated code.

Why use functions?

  • Makes code more organised and readable.

  • Avoids repetition (DRY - Don't Repeat Yourself).

  • Easy to test and debug.

There are many inbuilt functions in python :-

FunctionDescription
abs()Returns absolute value. → abs(-5)5
all()Returns True if all items in iterable are true.
any()Returns True if any item in iterable is true.
ascii()Returns readable string (escapes non-ASCII chars).
bin()Converts number to binary string. → bin(5)'0b101'
bool()Converts value to True or False.
breakpoint()Enters debugger.
bytearray()Returns bytearray object.
bytes()Returns immutable bytes object.
callable()Checks if object is callable (like function).
chr()Converts Unicode to character. → chr(65)'A'
classmethod()Used to create class methods.
compile()Compiles source into code object.
complex()Creates complex number. → complex(2, 3)2 + 3j
delattr()Deletes an attribute from object.
dict()Creates a dictionary.
dir()Lists attributes/methods of an object.
divmod()Returns quotient and remainder → divmod(7, 3)(2, 1)
enumerate()Adds index to iterable.
eval()Evaluates string as Python expression.
exec()Executes Python code dynamically.
filter()Filters items using a function.
float()Converts to float.
format()Formats a string or number.
frozenset()Creates an immutable set.
getattr()Gets value of an attribute.
globals()Returns global symbol table.
hasattr()Checks if object has an attribute.
hash()Returns hash value of object.
help()Launches help utility.
hex()Converts number to hex.
id()Returns memory address (identity) of object.
input()Takes user input.
int()Converts to integer.
isinstance()Checks type of an object.
issubclass()Checks if class is subclass of another.
iter()Returns iterator.
len()Returns length of an object.
list()Converts iterable to list.
locals()Returns local symbol table.
map()Applies function to all items in iterable.
max()Returns maximum value.
memoryview()Returns memory view object.
min()Returns minimum value.
next()Returns next item from iterator.
object()Base class of all classes.
oct()Converts number to octal.
open()Opens file.
ord()Returns Unicode code for a character.
pow()Returns power (x^y).
print()Prints output.
property()Returns property attribute.
range()Returns sequence of numbers.
repr()Returns string representation.
reversed()Returns reversed iterator.
round()Rounds number.
set()Creates a set.
setattr()Sets attribute on object.
slice()Creates slice object.
sorted()Returns sorted list.
staticmethod()Declares static method.
str()Converts to string.
sum()Adds numbers in iterable.
super()Refers to parent class.
tuple()Converts to tuple.
type()Returns the type of object.
vars()Returns __dict__ of object.
zip()Combines iterables element-wise.
__import__()Advanced import function used internally.

Defining of a Function in Python :-

A function in Python is a named block of code that performs a specific task. You can define it once and reuse it whenever needed.

Syntax to Define a Function :-

def function_name(parameters):
    # block of code
function_name()  #function call
  • Once a function is defined, it doesn't run automatically.

  • It needs to be called or triggered by writing its name followed by parentheses ().

    • Example :-

      •   def greet():
              print("Hello, welcome to Python!")
        
          # Calling the function
        
          greet()  # O/P = Hello, welcome to Python!
        
    • Key Points About Functions :-

      • Use def keyword to define a function.

      • Functions may accept parameters (inputs).

      • Functions can return a value using the return keyword.

      • If no return is specified, it returns None by default.

      • Improves code reusability and modularity.

    • Benefits of Using Functions :-

      • Reusable: Write once, use many times.

      • Readable: Breaks complex problems into smaller parts.

      • Testable: Easier to test small pieces of code.

2. While Loop in Python :-

What is a While Loop?

  • A loop that repeats a block of code as long as a specified condition is True.

Syntax of While Loop :-

while condition:
    # Loop body

Key Points:

  • The loop runs as long as the condition is True.

  • If condition is False initially, the loop body is skipped.

  • Avoid infinite loops by updating the condition variable inside the loop.

Example: Counting from 1 to 5

count = 1
while count <= 5:
    print(count)
    count += 1

🧾 Output:

1
2
3
4
5

Escaping the maze Project :-

  • Using For Loop:

  • Using While Loop:

0
Subscribe to my newsletter

Read articles from Aditya Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aditya Sharma
Aditya Sharma

DevOps Enthusiast | Python | Chef | Docker | GitHub | Linux | Shell Scripting | CI/CD & Cloud Learner | AWS