Exploring New Techs!

  • We here at Technotizers are Engineering students, curious technology learners and try to share our knowledge with everyone. Connecting technology with daily life and engaging more and more students into it is our goal. For contribution in articles, do contact us.

  • We here at Technotizers are Engineering students, curious technology learners and try to share our knowledge with everyone. Connecting technology with daily life and engaging more and more students into it is our goal. For contribution in articles, do contact us.

  • We here at Technotizers are Engineering students, curious technology learners and try to share our knowledge with everyone. Connecting technology with daily life and engaging more and more students into it is our goal. For contribution in articles, do contact us.

Showing posts with label python Strings. Show all posts
Showing posts with label python Strings. Show all posts

Python – Functions


Hello Technotizers, this article will give you detailed information on Python Functions. Function is a block of code that is designed to perform a specific task. It runs only when it is called in the code. A function can be given some data known as parameters which is used in the function. It can also return some result.

·         Creating a Function:

In Python, a function is created or defined using the def keyword.

def my_func():                     
    print("Hello, I'm a function!")

my_func is the name of the function.

 

·         Calling a Function:

To call a function, the name of the function is written followed by parenthesis.

def my_func():                     
    print("Hello, I'm a function!")
my_func()                          

The output is obtained as:

Hello, I'm a function!    

The task written in the function of printing a line is done when the function is called in the code. The function can be called multiple times and it will give the same output multiple times.

 

·         Arguments:

Information passed inside a function are called arguments. There can be multiple number of arguments inside a function, separated by a comma. Arguments are written inside parenthesis after the function name.

def my_name(name):            
    print("My name is",name)  
my_name("Harsh")              
my_name("Simran")             

The output is obtained as:

My name is Harsh    
My name is Simran   

In the above example, the function is created using one argument ‘name’. When the function is called the name is passed in parenthesis with the function name. This name is then used in the function to print the entire sentence.

 

Arguments or Parameters?

These both are used for the same thing, information passed in a function. But there is a major difference from the function’s perspective. A parameter is the variable name inside the parentheses in the function definition. An argument is the value that is sent to the function when it is called in place of the parameter.

 

Number of Arguments

The number of arguments passed while defining the function and the number of arguments passed while calling the function should be the same. Example: If a function is defined with 2 arguments then it should be called with 2 arguments only. Using 1 or 3 arguments will generate an error.

def my_name(fname,lname):            
    print("My name is",fname,lname)  
my_name("Harsh")                     

The output is obtained as:

TypeError: my_name() missing 1 required positional argument: 'lname'.

The error shows that the function is missing one argument.

 

Arbitary Arguments

When the number of arguments to be passed is not known, we need to add a * before the parameter name in the function definition. With this the function will receive a tuple of arguments and access the items accordingly.

def my_name(*names):                
    print("My name is",names[2])    
my_name("Simran","Tanuja","Harsh"
)  

The output is obtained as:

My name is Harsh

 Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments

We can also pass the arguments in key =  value pairs. In this way, the order of arguments does not matter.

def my_name(name2,name3,name1):                           
    print("My name is",name3)                             
my_name(name1 = "Simran",name2 = "Tanuja",name3 = "Harsh"
)

The output is obtained as:

My name is Harsh

Keyword Arguments are often shortened to kwargs in Python documentations.

Arbitary Keyword Arguments

When the number of keyword arguments to be passed is not known, we need to add ** before the parameter name in the function definition. With this the function will receive a dictionary of arguments and access the items accordingly with the help of keys.

def my_name(**name):                     
    print("My name is",name2)            
my_name(name1 = "Simran",name2 = "Harsh"
)

The output is obtained as:

My name is Harsh

Arbitrary Keyword Arguments are often shortened to **kwargs in Python documentations.

 

·         Default Parameters:

Default parameter is used when no argument value is passed to the function. Default parameter is assigned while defining the function, by writing the default parameter value in front of the parameter name.

def my_name(name = "Harsh"):
    print("My name is",name)
my_name("Simran")           
my_name()                   
my_name("Tanuja"
)           

The output is obtained as:

My name is Simran    
My name is Harsh     
My name is Tanuja    

In the above example, the default parameter value is “Harsh”, so when the function was called without an argument, it used the default parameter value to print the statement.


·         Passing any data type as Argument:

Python allows any data type to be passed as an argument. The data type doesn’t lose its identity while being used as an argument.

Example: Passing list as an argument.

def my_name(names):                
    for i in names:                
        print("My name is",i)      
names = ["Simran","Harsh","Tanuja"]
my_name(names)                     

The output is obtained as:

My name is Simran    
My name is Harsh     
My name is Tanuja    

 

·         Return Values:

To return some information as result, use the return keyword.

def my_func(number):       
    return 6*number        
print("2*6 is:",my_func(2))
print("3*6 is:",my_func(3))
print("5*6 is:"
,my_func(5))

The output is obtained as:

2*6 is: 12    
3*6 is: 18    
5*6 is: 30    

·         Pass Statement:

function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

def my_func():    
    pass          

This code will show no output as pass keyword is used in the function.

 

·         Recursion:

Recursion is a method where a function calls its self. In lay man’s language, recursion can be considered as nested functions. Recursion is a very common mathematical and programming concept. It’s benefit is that we can loop through data to reach a result. The programmer should be very careful with recursion as it can be quite common to fall into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written aptly recursion can be a very efficient and mathematically-elegant approach to programming.

def recursion(number):                       
    if number>0:                             
        result = number + recursion(number-1)
        print(result)                        
    else:                                    
        result = 0                           
    return result                            
print("Recursion results:")                  
recursion(6)                                 

The output is obtained as:

Recursion results:
1                 
3                 
6                 
10                
15                
21                

In this recursion, the argument value is added with the next recursion result which continues in loop until the number becomes 0.

 

With this we come to an end of this article. Hope it was helpful. Do provide your feedback and ideas through comments, it would be highly appreciated. See you soon!
Keep coding and exploring new techs!!

 

 

Python – Dictionaries

                                 

Hello Technotizers, this article is dedicated to the last Python specific data type that is Dictionaries. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered, changeable and does not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values.

my_address = {                

    "Street" : 8,             

    "Town" : "Kharghar",      

    "City" : "Mumbai"         

}                             

print(my_address)             

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai'}

 

Some points to be remembered:

·         Dictionary items are ordered, changeable, and does not allow duplicates.

·         Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

·         A dictionary item can be of any data type like int, string or Boolean. A dictionary can also contain items of mixed data types.

 

Examples:

The below given dictionary has values of mixed data types and it is valid in Python.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai",    
    "On highway" : True   
}                         
print(my_address)         

 

·         Accessing dictionary elements:

You can access the items of a dictionary by referring to its key name, inside square braces after the dictionary name.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
x = my_address["Town"]    
print(x)                  

The output is obtained as:

Kharghar   

We can also use the get() method to access the dictionary. It is similar like the previous example.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
x = my_address.get("Town")

The output is obtained as:

Kharghar  

Another method to access the dictionary is keys() method.

my_address = {          
    "Street" : 8,       
    "Town" : "Kharghar",
    "City" : "Mumbai"   
}                       
print(my_address.keys())

The output is obtained as:

dict_keys(['Street', 'Town', 'City'])

This method returns a list of all the keys from the dictionary.

The values() method will return a list of all the values in the dictionary.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
print(my_address.values())

The output is obtained as:

dict_values([8, 'Kharghar', 'Mumbai'])

The items() method will return all the items in a dictionary in the form of a list containing tuples of key value pairs.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
print(my_address.items()) 

The output is obtained as:

dict_items([('Street', 8), ('Town', 'Kharghar'), ('City', 'Mumbai')])

 

·         Changing dictionary elements:

Value of a specific dictionary item can be changed by referring to its key.

my_address = {               
    "Street" : 8,            
    "Town" : "Kharghar",     
    "City" : "Mumbai"        
}                            
my_address["Town"] = "Panvel"
print(my_address)            

The output is obtained as:

{'Street': 8, 'Town': 'Panvel', 'City': 'Mumbai' 

The update() method will update the existing dictionary with the items from the given argument. The argument should be a dictionary, or an iterable object with key:value pairs.

my_address = {                       
    "Street" : 8,                    
    "Town" : "Kharghar",             
    "City" : "Mumbai"                
                                   
my_address.update({"Town":"Panvel"}) 
print(my_address)                    

The output is obtained as:

{'Street': 8, 'Town': 'Panvel', 'City': 'Mumbai'}

 

·         Adding new dictionary items:

A new dictionary item is added by using a new index key and assigning a new value to it.

my_address = {                     
    "Street" : 8,                  
    "Town" : "Kharghar",           
    "City" : "Mumbai"              
}                                  
my_address["State"] = "Maharashtra"
print(my_address)                  

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai', 'State': 'Maharashtra'}

The update() method will update the existing dictionary with the items from the given argument. If the item doesn’t exist, then it will be added. The argument should be a dictionary, or an iterable object with key:value pairs.

my_address = {                            
    "Street" : 8,                         
    "Town" : "Kharghar",                  
    "City" : "Mumbai"                     
}                                         
my_address.update({"State":"Maharashtra"})
print(my_address)                         

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai', 'State': 'Maharashtra'}


·         Removing dictionary items:

The pop() method removes the item with the specified key name.

my_address = {           
    "Street" : 8       
    "Town" : "Kharghar"
    "City" : "Mumbai"    
}                        
my_address.pop("Town")   
print(my_address)        

The output is obtained as:

{'Street': 8, 'City': 'Mumbai'}

The popitem() method removes the last inserted item.

In versions before 3.7, a random item is removed.

my_address = {           
    "Street" : 8       
    "Town" : "Kharghar"
    "City" : "Mumbai"    
}                        
my_address.popitem()     
print(my_address)        

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar'} 

The del keyword deletes the item with the specified key name.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
del my_address["Town"]    
print(my_address)         

The output is obtained as:

{'Street': 8, 'City': 'Mumbai'}

The del keyword is also used to delete the entire dictionary.

my_address = {                
    "Street" : 8,             
    "Town" : "Kharghar",      
    "City" : "Mumbai"         
}                             
del my_address                
print(my_address)             

Printing the dictionary will generate an error as the dictionary no longer exists.

The clear() method returns  an empty dictionary.

my_address = {            
    "Street" : 8,         
    "Town" : "Kharghar",  
    "City" : "Mumbai"     
}                         
my_address.clear()        
print(my_address)         

The output is obtained as:

{}

The output shows that the dictionary is empty.

 

·         Looping through a dictionary:

A for loop is used to loop through a dictionary. Generally the return value is a key but there are methods to get values as well. The keys(), values() and items() methods can be used to get keys, values and key value pairs respectively.

my_address = {                
    "Street" : 8,             
    "Town" : "Kharghar",      
    "City" : "Mumbai"         
}                             
#default return value         
print("All the keys are:")    
for i in my_address:          
    print(i)                  
                              
#using values() method        
print("All the values are:")  
for i in my_address.values(): 
    print(i)                  
                              
#using keys() method          
print("All the keys are:"   
for i in my_address.keys():   
    print(i)                  
                              
#using items() method         
print("All the items are:")   
for i,j in my_address.items():
    print
(i,j)                

The output is obtained as:

All the keys are:         
Street                    
Town                      
City                      
All the values are:       
8                         
Kharghar                  
Mumbai                    
All the keys are:         
Street                    
Town                      
City                      
All the items are:        
Street 8                  
Town Kharghar             
City Mumbai               

 

·         Copying a dictionary:

There are two ways to copy a dictionary. First is to use the copy() method, second is to use the in-built dict() function.

my_address = {                                      
    "Street" : 8,                                   
    "Town" : "Kharghar",                            
    "City" : "Mumbai"                               
}                                                   
#using copy() method                                
your_address = my_address.copy()                    
print(your_address)                                 
                                                    
#using dict() function                              
your_adddress = dict(my_address)                    
print(your_address)                                 

The output is obtained as:

{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai'}
{'Street': 8, 'Town': 'Kharghar', 'City': 'Mumbai'}


·         Nested dictionary:

A dictionary into a dictionary is called as Nested dictionary 

my_family = {                
    "mother" : {             
        "name" : "Sakshi",   
        "age" : 45           
    },                       
    "father" : {             
        "name" : "Suhas",    
        "age" :50            
    },                       
    "brother"              
        "name" : "Raj",      
        "age" : 23           
    },                       
}                            
print(my_family)             

The output is obtained as:

{'mother': {'name': 'Sakshi', 'age': 45},          'father': {'name': 'Suhas', 'age': 50}, 'brother': {'name': 'Raj', 'age': 23}}                       

Or you can also create three dictionaries and add to a new dictionary to make it nested.

mother = {                
        "name" : "Sakshi",
        "age" : 45        
    }                     
                          
father = {                
        "name" : "Suhas"
        "age" :50         
    }                     
                          
brother = {               
        "name" : "Raj",   
        "age" :23         
    }                     
my_family = {             
  "Mother" : mother,      
  "Father" : father,      
  "Brother" : brother     
}                         
print(my_family)          

The output is obtained as:

{'Mother': {'name': 'Sakshi', 'age': 45},          'Father': {'name': 'Suhas', 'age': 50}, 'Brother': {'name': 'Raj', 'age': 23}}                       

 

·         Dictionary methods:

Python offers a bunch of dictionary methods given below:

Method

Description

clear()

Removes all the elements from the dictionary

copy()

Returns a copy of the dictionary

fromkeys()

Returns a dictionary with the specified keys and value

get()

Returns the value of the specified key

items()

Returns a list containing a tuple for each key value pair

keys()

Returns a list containing the dictionary's keys

pop()

Removes the element with the specified key

popitem()

Removes the last inserted key-value pair

setdefault()

Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update()

Updates the dictionary with the specified key-value pairs

values()

Returns a list of all the values in the dictionary

 

With this we come to an end of this article. Hope it was helpful. Do provide your feedback and ideas through comments, it would be highly appreciated. See you soon!

Keep coding and exploring new techs!!