Functions in Python

Functions in Python

Functions in Python

A function in Python is a block of code that performs a specific task and returns a result. Functions help break down a program into smaller, more manageable pieces and make the code easier to read, test, and maintain. Functions define using the def keyword, followed by the name of the function, a set of parentheses, and a colon. The code within the function indent under the definition and execute when the function can call.

def func_name (optional_arguments)

statement

return optional_value

 

  • Arguments: Functions accept arguments, which values pass to the function when it calls and it specify in the parentheses of the function definition, however it use within the function to perform the desire task.
  • Return statement: Functions can return a result to the caller using the return statement for any data type, including numbers, strings, lists, dictionaries, etc. If a function doesn’t return a value, it returns None by default.
  • Scope: Variables can define inside a function are local to that function, it is not accessible outside of it. Variables define outside of a function can call global variables and can access from anywhere in the program.
  • Recursion: Functions can call themselves; this technique is recursion. Recursive functions are useful for solving problems that can break down into smaller, similar subproblems.
  • Default arguments: These arguments are used in the function definition but if a value doesn’t provide for a default argument, the default value will be used.
  • Keyword arguments: Functions can call using keyword arguments, which specify as key=value pairs but Keyword arguments allow you to specify arguments in any order if the names of the arguments can be provided.

Functions are a fundamental building block of Python programming and are essential for writing clean, reusable, and maintainable code.

Example:
def exp(i) :
return i*100
>>> exp(5)                       result = 500
In this case, when we recall exp with any number, the result is number*100

def exp(i) :

if i %2 ==0:

return ‘Pair’

return ‘Odd’

>>> exp(5)                       result = Odd

>>> exp(10)                     result = Pair

 

let’s to see video from our YouTube channel

 

If you want to learn more Python, please click here.

Functions in Python

Data Structure in Python

Data Structure in Python

Data structure in python makes it possible to store and organize data in a very efficient way. Using it, we can link the data together and perform the desired operations on them.
In programming, this process is especially important because it enables us to access and recall data more easily.

There is four general Data Structures in Python:

  • List: ordered, changeable, duplicate members.
  • Dictionary: ordered, changeable, No duplicate members.
  • Set: unordered, unchangeable, unindexed, No duplicate members.
  • Tuples: ordered, unchangeable, duplicate members.

LIST: 

>>>a = []

for example:

>>>a = [2, 5, 10]             >>>b = [1.2, 5.9, “Hi”, 8]

To recall form List: >>>a [0]      result:  2              >>>a [1]      result:  5

To change in List : >>>a [0]=3           >>>a          result  a[3, 5, 10]

Methods :
  • append(): Add element end of list
  • remove(): Remove first element
  • clear(): Remove all list
  • copy(): Copy of list
  • count(): Number of elements with value
  • extend(): Add to end of list
  • index(): Index of first element with value
  • insert(): Add element to the list
  • pop(): Remove element from list
  • reverse(): Reverse list
  • sort(): Sort list

for i in a:

print(i)

Result: 3   5   10

let’s to see video from our YouTube channel

DICTIONARY: 

Different between Dictionary with other Data Structure is, we can make Data with TAG, now you ask what is mean? let’s to see some examples:

>>>a = {}             >>>a = {“Quantiy”: 5, “Price”: 20}

>>>b = {}             >>>b = {0: 5, 1:20}

In the second example, we use Tag 0 for “Quantity” and Tag 1 for “Price”, that’s same as first one.

>>>c = {}          >>>c = {“name”: “XXX”, “family”: “YYY”}

for z,x in c.items():

print(z, ” : “, x)

Result

name : XXX
family : YYY

Methods:
  • clear(): Removes all
  • copy(): get copy
  • fromkeys(): get the specified keys and value
  • get(): get value of the specified key
  • items(): get a list for each key value pair
  • keys(): get a list with keys
  • pop(): Removes by specified key
  • popitem(): Removes the last element
  • setdefault(): get the value of the specified key
  • update(): Updates with the specified key-value pairs
  • values(): get a list of all the values

in this structure, we can make for each element, one Tag, so that’s too easy to save and recall data of this method.

let’s to see video from our YouTube channel

SET: 

SET structure is same as DICTIONARY but in SET we dont have TAG. let’s to see some examples:

>>> a = {}         a = {1, 2, 3}

in this structure if we have same number, it will remove by compiler, that’s mean, we dont have repeat in this structure.

>>> a = {1, 4, 2, 5, 1, 6, 2} ==> compiler remove 1, 2 because we have same.

for i in a:

print(i)

>>1, 2, 3, 5, 6

Methods :
  • add(): Adds element
  • clear(): Removes all
  • copy(): get a copy
  • difference(): get difference between two or more sets
  • difference_update(): Removes the items included in another
  • discard(): Remove the item
  • intersection(): get the intersection of two more sets
  • intersection_update(): Removes the items that do not present in other
  • isdisjoint(): get a intersection or not
  • issubset(): get contains or not
  • issuperset(); get contains another set or not
  • pop(): Removes element
  • remove(): Removes the specified element
  • symmetric_difference(): Get symmetric differences of two sets
  • symmetric_difference_update(): inserts the symmetric differences
  • union(): get containing the union of sets
  • update(): Update

let’s to see video from our YouTube channel

TUPLE: 

TUPLE is unchangeable, and when we assign value, we cannot change it after.

in TUPLE, we have access to the element by command for example a = [0], in this command it return value of first element of these data

>>>a = ()                 >>>a = (1, 2, 3, 4)     or           >>> a = 1, 2, 3, 4

as you see TUPLE is same as int, if we want to make TUPLE with one element, we must use comma after it, let’s see

>>> a = (1,)     or     >>>a = 1,

Methods :
  • count(): Get the number of times with specified value
  • index(): Get the position of where it was found

let’s to see video from our YouTube channel

If you want to learn more Python, please click here.

Python Standard Library

Python Standard Library

Python Standard Library

With Python Standard Library, we call module code that is ready to use. We cannot use these modules without recall and if we need, we must call them.

The Python standard library is very extensive and offers many features. In this library, we see internal modules that are often written in C language. For example, we can access the file input/output system through these modules, without these modules, Python programming will be inaccessible.

These modules provide increased programming capabilities. In the installed version of Python in Windows or Mac, usually the entire standard library also install and accessible and there is no need to add them, but in Unix, they are a set of packages that we can install separately.

Modules are the main unit of code in Python and there are two types of modules in Python:

  • Pure module: This module is written in Python and is in a .py file
  • Extension module: This module is written in these languages: C/C++ for Python, Java for Python.

we have many Modules in Python, for example Modules:

  • OS: operating system dependent functionality
  • Random: random number generators
  • Datetime: manipulating dates and times
  • Sys: information about system
  • Collection: data structure and datatypes providing

How we can recall a library in Python:

for recalling, we have two options:
  1. Recall all module: In this way, we recall all module and when we want to use commande we write module. Submodule (X)
  2. Recall a specific sub module: In this way, in command we write just submodule (X), and it doesn’t need to write module name before submodule
here a command for recalling:
  1. import module
  2. from module import submodule
let’s to see some examples by module random:
  1. import random
    random.randrange(10)
  2. from random import randrange
    randrange(10)
let’s to see video from our YouTube channel

 

If you want to learn more Python, please click here.

WHILE in Python

WHILE in Python

WHILE in Python

WHILE loop is especially useful in Python programming, and we use it many times. In the WHILE loop, we start a loop until the condition in the loop becomes True and the loop stops.

In this loop, while first evaluates the desired condition, if the condition is correct, the command inside the loop is executed. After that, the condition is reevaluated and this process continues until the desired condition is violated and when the condition becomes False, the loop will stop.

Syntax:

while condition:

statement

In WHILE loop, we need a condition to stop loop, if we don’t write a condition to stop, loop will continue without stop. here are some examples:

while a > X:

print(‘Y’)
a=a-1


while a >= X:

print(a)
a-=1


Example : 

  • a=1
  • while a <= 5:
  •    print (a)
  •    a=a+1

Output:

1

2

3

4

5

Example : 

  • a=1
  • while True:
  •    print (a)
  •    if a==5:
  •       break
  •    a=a+1

Output :

The output for this example is same as the last one, I just wanted to teach you the same result in two ways.

Infinite while Loop in Python:

In this model of the loop, if the condition is True, the loop will run for infinity. In Python, to prevent this model of infinite loops, a workaround has been considered that if the compiler detects that the loop is not able to stop, it stops automatically. To avoid such infinite loops, we need a condition in the loop to stop.

while True:

statement

while True :

print(a)
a-=1

if a==X:

break

Example : 

  • a=1
  • while True:
  •    print (a)
  •    a=a+1

Output :

This loop will continue with non-stop

Python While loop with else:

while condition:

statement

else:

statement

Example : 

a = 1

while a <= 5:

print(a)

a = a + 1

else:

print(‘a is over‘)

Output :

1
2
3
4
5
a is over

let’s to see video from our YouTube channel

If you want to learn more Python, please click here.

Functions in Python

FOR in Python

FOR in Python

Loops are used for sequential traversal, that’s mean used for repeating variables such as numbers, strings, lists or sets. The loop continues until it is terminated by the variable or by terminating the loop with the Break command. In this section, we want to learn how to use loops. loop in programming languages is an iterative method and is also found in other object-oriented languages. With a loop, we can execute a set of commands, once for each item. Loops in every programming language start with a set of rules, but they may be slightly different in structure. Python also has statements and conditional loops.

In the first part, we will introduce the FOR-loop Python. With this loop, we can iterate through instructions based on the number considered in the loop. First, we examine its structure:

for <var> in <iterable>:

<statement(s)>

In this structure, the “statement” repeats i times

let’s to see some example

for i in “Hello”:

print(i)

The output of this command: in five lines it prints Hello, line 1 first character, line 2 second character and … 

for i in “Hello”:

print(1)

The output of this command: in five lines it prints 1, line 1 print 1, line 2 print 1 and … 

for i in “55”:

print(i)

The output of this command: in two lines it prints 55, line 1 print 5, line 2 print 5 and … 

if we want to print for example from 1 to 50, we can use command range(): in this command we can make [start,stop,step] 

for i in range (3):

print(i)

The output of this command: in three lines it prints: line 1 print 0, line 2 print 1 and line 3 print 2

We must know range (3), prints 0,1,2. If we want to print 1,2,3 = for i in range (1,3+1)

With [step] we can skip numbers, for example: this prints 1,3,5 = for i in range (1,5+1,2):

let’s to see video from our YouTube channel

If you want to learn more Python, please click here.

Condition IF in Python

Condition IF in Python

Condition IF in Python

We use the IF statement in programming to run a group of statements but only when a condition is met.

In this section, we want to introduce the syntax and examples of Condition IF in Python.

IF is one of the conditional commands that is very widely used in programming and learning it is recommended to everyone.

There are three forms of the IF In Python:

  1. if
  2. if  else
  3. if   elif   else

elif allows to check multiple statements for TRUE and if one the condition was True then it execute those statements.

else: if all conditions were False then the last condition in ‘else’ will execute at the end.

we must know the conditional elements and here there are some elements:

a==b              Is a equal to b?

a !=b              Is NOT a equal to b?

a < b              Is a smaller than b?

a > b              Is a greater than b?

 

for using IF we have three steps:

if condition1:

statement a

if it’s True then compiler run it and skip others condition

elif condition2:

statement b

and if last IF was False then compiler check this part and if it’s True then compiler execute it and skip other conditions

elif condition3:

statement c

we can have another IF and if last ELIF was False then compiler check this part and if it’s True then compiler execute it and skip other conditions

else:

statement d

All conditions were False, and compiler runs this.

 

For Example:

if a > b:

    print (‘Yes’)

elif a < b:

    print (‘No’)

else:

    print (‘Equal’)

 

Nested IF in Python:

We can merge several IF into a single IF statement and this is called Nesting in programming languages.

First Condition: if condition1:

Second Condition: if condition2:

Third Condition: if condition3:

statement a

elif condition3-1:

statement b

else:

statement c

 

let’s to see video from our YouTube channel

If you want to learn more Python, please click here.