DEV Community

Cover image for Python Intermediate Concepts.
Torine6
Torine6

Posted on

Python Intermediate Concepts.

A. Control Flow Structures

They determine the order in which instructions are executed in our programs.
For more information visit https://www.educative.io/edpresso/what-are-control-flow-statements-in-python.

1. Sequential Control
In sequential control, the execution process follows the order in which we write our instructions, i.e line-by-line execution .

print('Hello')
print('How are you')
print('Welcome to Lux Tech Academy')

Enter fullscreen mode Exit fullscreen mode

#output
Hello
How are you
Welcome to Lux Tech Academy

2. Selection Control/ Decision Control
Here, we have a condition and statements are executed based on the condition. If the condition is true, then only the True statements are executed while the False statements are ignored, and vice versa.
There is a selection of statements based on the condition that is true.
We have different types of selection control statements;
i) simple if statement
The block of code is executed whenever the condition is true. If the condition is false, the code is not executed

temperature = 35
if temperature > 30:
   print("It is a hot day.")
Enter fullscreen mode Exit fullscreen mode

#output
It is a hot day

ii) if-else statement
This is used to evaluate a statement or a block of statement based on the given condition. The if block of code is executed whenever the condition is true. The else block of code is executed whenever the condition is false.

value =int(input("Enter an integer: ))
if value<10:
    print("value is less than 10")
else:
    print("value is greater than 10")
Enter fullscreen mode Exit fullscreen mode

iii) Multiway selection
These allow us to execute multiple expressions.
>>nested if statement
These are if statements inside other if statements.

num_1 = float(input("Enter a number: "))
if num_1 >= 0:
    if num_1 == 0:
        print("The number is zero.")
    else:
        print("This is a positive number.")
else:
    print("This is a negative number.")
Enter fullscreen mode Exit fullscreen mode

>>if-elif-else statement
Here, only one block of code is executed based on the condition. If the if block of code is false, the elif block is executed. If all the conditions are false, the else block of code is executed.

temperature = 19
if temperature > 35:
    print("It is a hot day.")
elif temperature > 20:
    print("It is a good day")
else:
    print("Enjoy your day.")
Enter fullscreen mode Exit fullscreen mode

#output
It is a good day

The link https://www.datacamp.com/community/tutorials/python-if-elif-else?utm_source=adwords_ppc&utm_medium=cpc&utm_campaignid=1455363063&utm_adgroupid=65083631748&utm_device=c&utm_keyword=&utm_matchtype=&utm_network=g&utm_adpostion=&utm_creative=332602034364&utm_targetid=dsa-429603003980&utm_loc_interest_ms=&utm_loc_physical_ms=9076838&gclid=Cj0KCQiA3rKQBhCNARIsACUEW_ZmhCnRNOBp3kY6kGuq6_-Z3ZKZntTEOMd4LQWgZMR1XztQjBaEOEUaAiueEALw_wcB contains more information on the different types of decision control statements.

3. Iterative Control
There is a condition. The True statement is executed repeatedly as long as the condition is true. When the condition becomes false, it comes out from the loop.

i = 0
while i<=10:
      print(i)
      i += i
Enter fullscreen mode Exit fullscreen mode

#output is
1
2
3
4
5
6
7
8
9
10

B)Functions

A function is a 'container' for lines of code that perform a specific task. Functions help us organize our code by breaking is into smaller blocks that are more manageable.
Types of functions

  1. Built-in functions These are functions that can be used directly in the program. Examples: int() float() bool() str()
  2. User-defined functions These are functions that a user defines using the def keyword. Python keywords cannot be used as the function name.

Syntax of python functions

  1. We use def reserve keyword to define functions.
  2. Function name- we name out function with lower case characters and use underscore if we are naming the function using multiple words for example,say_hello. Use meaningful and descriptive names for your functions.
  3. Parameter - this is the value that we give to the function and is usually listed inside the parentheses.
  4. Colon(:)- This tells Python that we are defining a block of code and all the lines of code after the colon are indented and belong to the function.
  5. docstrings- Python documentation strings(docstrings)describe what the function does. They are declared using '''triple single quotes''' or """triple double quotes"""
  6. Statements- these are the lines of code that give Python instructions to be executed.
  7. Return statements-they return the result of the function to the user. By default, all Python functions return None, we can return our function value by using return statement.
def cube(number):
    return number*number*number
print(number)

print(cube(5))
Enter fullscreen mode Exit fullscreen mode

#output == 125

Advantages of functions

  • Enhances readability of a program.

  • They maximize reusability of the code

  • They minimize redundancy

  • Improve the clarity of the code.

Types of arguments
An argument is the value that is sent to the function when we are calling the function. Types of arguments in function definition include:

  1. Positional arguments -Positional arguments are arguments that have to be passed in their correct order. They can be called by their position in the function definition.
  2. Keyword arguments -A keyword argument helps us to change the position of an argument. It is used when we know the exact number of arguments we want to pass.
  3. Default arguments -A default argument is used in the case where the user does not provide a value for the parameter. The default argument assumes default values for the argument when calling the function. Here we use the assignment operator (=).
  4. Variable-length arguments -These are used when the number of arguments we want to pass is unknown. Here, we add * before the parameter.

Recursive functions
A recursive function is a function that calls itself.
Advantages

  • Recursive functions are used for sequence generation.

  • They make the code look clean.

Disadvantages

  • Recursive functions are difficult to debug

  • Recursive functions take up a lot of time and memory.

Lambda functions
A lambda function is an anonymous function, which is a function without a name.
Lambda functions are defined using lambda keyword.
Lambda functions are limited to a single line of code.
They can be assigned to variables and used as normal functions.
Lambda functions use filter and map.
Filter
The filter()function takes in items in a list and returns a new list with items which the function evaluates to True
Map
The map()function takes in items in a list and returns a new list which contains items returned by the function for each item on the list.

C)Classes and objects

Classes
A class is a blueprint from which you can create objects.
Classes are defined by class keyword.
Methods
These are functions defined inside the body of a class. They are used to define behavior of an object.
Inheritance
Inheritance is the process of creating a new class by using details of an existing class without modifying it.
It allows us to inherit attributes and methods from a parent class.
The newly formed class is known as a derived / child class.
The existing class is referred to as a base or parent class.

Objects
An object is an instantiation(copy) of a class.
It is a collection of data variables and functions that act on that data.
Instance variables /Attributes
These are variables defined inside an object. They are used to get details about the object.

NOTE

You can check out my GitHub if you would like to run the codes in the article.
Here is the link:https://github.com/Torine6/pythonProject1/blob/master/main.py

Top comments (0)