Python Basics: Functions

Python Basics: Functions

Python Basics: Functions - A function is an organized reusable piece of code solving a specific task. Functions help us to keep our code clean and provide us with the power of code reusability.

A function is an organized reusable piece of code solving a specific task. Functions help us to keep our code clean and provide us with the power of code reusability.

After reading this article you’ll know:

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements

Introduction

A function is an organized reusable piece of code solving a specific task. Functions help us to keep our code clean and provide us with the power of code reusability.

Built-in Functions

Python has several built-into functions which are always available. Some of these functions are print and max. Let’s see some examples of how we can use them.

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements
print("Python")
print("chess", "backgammon")

Output:

Python
chess backgammon

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements
numbers = [10, 5, 49, 24, -10]
largest_number = max(numbers)
largest_number

Output:

49

We can see that we simply call the function by writing its name and pass the required inputs.

User-Defined Functions

As a programmer or data scientist, sometimes we need functionality specific to our needs. In these cases, we can define our own functions.

To define a function we need to follow these rules:

  1. Use the keyword **def** to introduce a function definition
  2. Write the function name followed by parentheses **()**and a colon**:**
  3. Define a list of parameters inside these parentheses (optional)
  4. Write the function body. The statements that form the function body, start at the next line and must be intended. When the function is called the code in the function body is run.
  5. The first statement of the function body can be a string literal which represents the function documentation (optional)
  6. Use the **return** keyword to pass back a result to the caller (optional)

Don’t worry if you think that there are many steps. We’ll see many examples and the concepts will become pretty straightforward.

Defining a Function Without Parameters

Let’s see a simple example of a function definition without the optional parts. We can call the function by typing its name followed by parentheses (). When we call this function, it will print the current date.

import datetime # importing the "datetime" module

def print_current_date():
    current_date = datetime.datetime.now().date()
    print(current_date)
    
print_current_date()

Output:

2019-02-19

Note that, this output can be different for you. The output will be the date in which you call the function.

Defining a Function With Parameters

We need function parameters almost always. They’re used when we want to pass data into our function. When we call a function we pass arguments (values for the parameters) to the function.

One Parameter Example

def print_message(text):
    print(text)
    
print_message("Forgive yourself for your faults and your mistakes and move on. - Les Brown")

Output:

Forgive yourself for your faults and your mistakes and move on. - Les Brown

When we’re defining parameter like that it’s required. If we don’t pass an argument value for this parameter, this will give us an error.

def print_message(text):
    print(text)
    
print_message()

Output:

--------------------------------------------------------------------
TypeError                          Traceback (most recent call last)
<ipython-input-48-f2f093834d71> in <module>()
      2     print(text)
      3 
----> 4 print_message()

TypeError: print_message() missing 1 required positional argument: 'text'

Later, in this blog post, we’ll see how to define optional arguments (arguments with a default value).

Multiple Parameters Example We can add as many parameters as we want, we just need to separate them with commas. In many cases, we need more than just one parameter.

The order in which the arguments are passed corresponds to the order of the parameters in our function definition. In the example below, we pass 10 as value for the number1 parameter and 5 as a value for the number2 parameter.

def sum_numbers(number1, number2):
    print(number1 + number2)

sum_numbers(10, 5)

Output:

15

However, if we want to save the result in a variable, we cannot do that using the above function definition, because our function is simply printing the result and we don’t use a **return** statement. Let’s see what will happen if we try to save the result.

def sum_numbers(number1, number2):
    print(number1 + number2)

result = sum_numbers(10, 5)
print(result)

Output:

15
None

We can see that the sum is printed (because our function was called), but the result variable has a value of None instead of 15. In the next section let’s see how we can return values.

Defining a Function That Returns a Result

We can use the **return** keyword to leave the current function call and to return a wanted result. Let’s see how we can re-define our function sum_numbers to return the sum instead of printing it.

def sum_numbers(number1, number2):
    return number1 + number2

result = sum_numbers(10, 5)
print(result)

Output:

15

We can clearly see that this time the result variable has a value of 15.

Defining a Function That Returns Multiple Values

We can also define a function that returns multiple values. We can do that by constructing objects called tuples in your function. The tuples data type in Python is an immutablesequence. This means that they can contain multiple values like lists.

import datetime

def get_current_datetime():
    current_datetime = datetime.datetime.now()
    current_date = current_datetime.date()
    current_time = current_datetime.time()
    return (current_date, current_time)

date, time = get_current_datetime()
print(date)
print(time)

Output:

2019-02-19
08:23:38.030659

In the example above we use sequence unpacking. We just “unpack” the values from the tuple into date and time variables.

Defining a Function with Documentation

In the last example, we defined a function that returns the current date and current time as a tuple. Maybe it’s easy to understand what the function does. However, wouldn’t be nice if there is a documentation for this function?

import datetime

def get_current_datetime():
    """
    Returns the current date and current time as a 2-tuple
    """
    current_datetime = datetime.datetime.now()
    current_date = current_datetime.date()
    current_time = current_datetime.time()
    return (current_date, current_time)

date, time = get_current_datetime()
print(date)
print(time)

Output:

2019-02-19
08:26:49.538434

In many cases, our functions are more complex than the above example. In these cases, it’s always preferable to have documentation for your function. The function documentation can include information about:

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements

Scope

Not all objects (including the functions) we have defined are accessible everywhere in our Python code. The scope of the program represents where a variable name or function name may be accessed. Python has 3 types of scopes: local, global and built-in scope.

Local Scope

When our object or function is defined inside a function this means that it has a local scope. We can use this object or function only inside the function where it’s defined.

Global Scope

When our object or function is defined in the main body of our Python code this means that is has a global scope. We have access to this object or function everywhere because it’s global.

Bult-In Scope

In Python, we have a number of functions and types built into that are always available.

Additional Notes

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements

It’s time to see a couple of examples.

def sum_numbers(number1, number2):
    result = number1 + number2
    return result

print(sum_numbers(10, 5))
print(result)

Output:

15

--------------------------------------------------------------------
NameError                          Traceback (most recent call last)
<ipython-input-2-faf6ee9da5b3> in <module>()
      4 
      5 print(sum_numbers(10, 5))
----> 6 print(result)

NameError: name 'result' is not defined

In this example, we can see that we have access to the result variable in our function, but we don’t have access to it outside the function. That’s because of the **result** variable has local scope and can be accessed only inside the sum_numbers function.

name = "Ventsi" # Global variable

def sum_numbers(number1, number2):
    greting = "Hi, " + name # greeting is a local variable
    sum_result = number1 + number2 # sum_result local variable
    result = greting + " the sum is " + str(sum_result) # str() is a bult-in function
    return result

print(sum_numbers(10, 5))
print(result)

Output:

Hi, Ventsi the sum is 15

--------------------------------------------------------------------
NameError                          Traceback (most recent call last)
<ipython-input-1-747761fcaa8f> in <module>()
      7 
      8 print(sum_numbers(10, 5))
----> 9 print(result)

NameError: name 'result' is not defined

In this example, we can see that we have access to the global variable **name** in our function. Also, we have used the **str()** built-in function. However, the **result** variable has a local scope again and it cannot be accessed outside of the sum_numbers function.

result = 100

def sum_numbers(number1, number2):
    result = number1 + number2
    return result

print(sum_numbers(10, 5))
print(result)

Output:

15
100

Here, we defined a result variable globally, then we defined another variable in our function with the same name. We can see that we get a value of 100 for the global scope because our global variable has this value. Also, we get 15 for the sum_numbers(10, 5) because the value of the local variable result is calculated inside the function.

subject = "programming"

def change_subject(new_value):
    """Change the value fo the global variable subject"""
    global subject # Use subject in global scope
    subject = new_value
    
print(subject)
change_subject("machine learning")
print(subject)

Output:

programming
machine learning

We can use the **global** keyword in cases when we want to change the value of a global variable inside some function.

Keyword Arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.> Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
Source: https://www.tutorialspoint.com/python/python_functions.htm

We can use the keyword arguments using the argument name and the **=** sign.

def raise_value(number, power):
    """
    Raise number to the power
    
    Parameters
    ----------
    number : int, the number we want to raise
    power : int, the power we want to use
    """
    return number ** power

print(raise_value(2, 3))
print(raise_value(number = 2, power = 3))
print(raise_value(power = 2, number = 3))

Output:

8
8
9

Default Arguments

In some cases, we have a function with multiple parameters and we have a common value for some of them. We can specify default arguments for some of the function parameters. In these cases, we can call our function without specifying the values for the parameters with default arguments. To do this in Python, we can use the = sign followed by the default value.

def raise_value(number, power = 2):
    """
    Raise number to the power
    
    Parameters
    ----------
    number : int, the number we want to raise
    power : int, default 2, the power we want to use
    """
    return number ** power

print(raise_value(9))
print(raise_value(2))
print(raise_value(2, 3))

Output:

81
4
8

From the example above, we can see that the power parameter have a default value of 2. When we don’t specify the value for it, the default value is used. However, as we can see, we can pass a different value.

def raise_value(number, power = 2, details = False):
    """Raise number to the power"""
    result = number ** power
    if details:
        return "The number " + str(number) + " raised to the power " + str(power) + " is: " + str(result)
    else:
        return result

print(raise_value(2, details = True))
print(raise_value(2, 3))
print(raise_value(3))

Output:

The number 2 raised to the power 2 is: 4
8
9

Flexible Arguments

Sometimes, we want more flexible functions. For example, we may want to define a function which accepts more arguments than we have specified in the function. In other words, we may need to pass any number of arguments to our function. We can use the *special syntax args and **kwargs in our function definitions to achieve that.

*args

These arguments are called non-named variable-length arguments.

def args_example(*args):
    print(type(args))
    print(args)
    
args_example(1, 23, 4, 52, 2, 123)

Output:

<class 'tuple'>
(1, 23, 4, 52, 2, 123)

We can see that the *args syntax passed all arguments to the function as a tuple called **args**. So, we can do everything that we can do with the tuples data type.

def args_example(*args):
    for arg in args:
        print(arg)
        
args_example(5, 10, 15)

Output:

5
10
15
def get_average(*args):
    return sum(args) / len(args)
        
print(get_average(5, 10, 15))
print(get_average(5, 10, 15, 20, 40))
print(get_average(1, 2, 3, 4, 0, 19, 20, 49, 17, 30, 1, 3, 2, 6, 7, 88))

Output:

10.0
18.0
15.75

**kwargs

These arguments are called named variable-length arguments.

def kwargs_example(**kwargs):
    print(type(kwargs))
    print(kwargs)
    
kwargs_example(age = 24, position = "data analyst")
kwargs_example(name = "Jake", email = "[email protected]", position = "machine learning engineer")

Output:

<class 'dict'>
{'age': 24, 'position': 'data analyst'}
<class 'dict'>
{'name': 'Jake', 'email': '[email protected]', 'position': 'machine learning engineer'}

We can see that the **kwargs syntax passed all arguments to the function as a dictionary called **kwargs**. So, we can do everything that we can do with the dictionary data type.

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(key, value)
        
print_info(age = 24, position = "data analyst")
print()
print_info(name = "Jake", email = "[email protected]", position = "machine learning engineer")

Output:

age 24
position data analyst

name Jake
email [email protected]
position machine learning engineer

Actually, the variable name can be whatever, we just need to insert one asterisk ***** **or two asterisks **** before it.

def get_average(*arguments):
    return sum(arguments) / len(arguments)
        
print(get_average(5, 10, 15))
print()

def print_info(**key_value_pairs):
    for key, value in key_value_pairs.items():
        print(key, value)
        
print_info(age = 24, position = "data analyst")

Output:

10.0

age 24
position data analyst

Using * and ** When Calling a Function

We have seen that we can use this special syntax in our function definitions. However, we can use it when we’re calling functions, too.

def print_info(name, position, email):
    print("name:", name)
    print("position:", position)
    print("email:", email)
    
details = ("data analyst", "[email protected]")
print_info("Jake", *details)

Output:

name: Jake
position: data analyst
email: [email protected]
def print_info(name, position, email):
    print("name:", name)
    print("position:", position)
    print("email:", email)
    
details = {"email": "[email protected]", "position": "data analyst"}
print_info("Jake", **details)

Output:

name: Jake
position: data analyst
email: [email protected]

Python Exceptions

In many cases, when we’re using a function incorrectly it raises an exception (error).

For example, we can see part from the documentation for the [int()]([https://docs.python.org/3/library/functions.html#int)](https://docs.python.org/3/library/functions.html#int) "https://docs.python.org/3/library/functions.html#int)") built-in function: “Return an integer object constructed from a number or string x, or return _0_ if no arguments are given.”

print(int(6.99))
print(int("7"))
print(int("Hi"))

Output:

6
7

--------------------------------------------------------------------
ValueError                         Traceback (most recent call last)
<ipython-input-1-dea319bbd9d9> in <module>()
      1 print(int(6.99))
      2 print(int("7"))
----> 3 print(int("Hi"))

ValueError: invalid literal for int() with base 10: 'Hi'

We can see that a ValueError is raised when we have passed the “Hello” string as input.

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.#### Exception Handling

Sometimes, we may want to handle the raised exceptions without stopping the program execution. In Python, we can do that using the try-except clause.

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements
try:
    # Write your operations here
    print(numbers)
except:
    # If there is an error, the code in this block will be executed
    # For example, here you can log the error details
print("An exception occured")

Output:

An exception occured

The code above raises a NameError because the name numbers is not defined. When we don’t specify what exception type we’re looking for, the except will handle all the exception types.

Of course, we can write an except block that is looking for a specific kind of exception.

try:
    print(numbers)
except NameError:
print("An NameError occured")

Output:

An NameError occured

We can define as many as we want except blocks when we want to execute a different piece of code for each of the handled exceptions.

try:
    print(int("Hello"))
except NameError:
    print("A NameError occured")
except TypeError:
    print("A TypeError occured")
except ValueError:
    print("A ValueError occured")
except:
print("Another type of error occured")

Output:

A ValueError occured

Also, when we want more information about the exception we can save it to a variable using **as** syntax. For example, we may wish to log the error message.

try:
    print(int("Hello"))
except ValueError as error:
    # Use your logger to log the error
    # Example:
# logger.error(error)

We can also add an **else** block which will be executed if no errors were raised.

try:
    print(sorted(1))
except Exception as error:
    print("Something went wrong")
    print(error)
else:
print("Nothing went wrong")

Output:

Something went wrong
'int' object is not iterable
try:
    print(sorted([1, 2, 3]))
except Exception as error:
    print("Something went wrong")
    print(error)
else:
print("Nothing went wrong")

Output:

[1, 2, 3]
Nothing went wrong

Also, we can use a **finally** block instead of **else** block if we want to execute some code regardless if the try block raised an error or not.

Imagine that we have a file filename.txt in your working directory and you’re trying to write some text in it.

try:
    file = open("filename.txt")
    file.write("Python is awesome!")
except:
    print("An error occured when writing to the file")
finally:
file.close()

Output:

An error occured when writing to the file

An error occurred because by default the open built-in function is using the “read” mode. However, the **finally** block is closing the file connection in both cases (if there was an error or not). In this case, we use this block to be sure that our file is closed.

Throwing Errors

When we’re defining our own functions we may want to raise errors and write more meaningful error messages. Let’s define a function that returns if two words are anagrams.

def check_anagrams(word1, word2):
    """
    Check if the two passed words are anagrams.
    Returns True if the word1 and word2 are anagrams, otherwise returns False
    """
    return sorted(word1) == sorted(word2)

print(check_anagrams("silent", "listen"))
print(check_anagrams("silent", 5))

Output:

True

--------------------------------------------------------------------
TypeError                          Traceback (most recent call last)
<ipython-input-61-f1a30da1d38d> in <module>()
      7 
      8 print(check_anagrams("silent", "listen"))
----> 9 print(check_anagrams("silent", 5))

<ipython-input-61-f1a30da1d38d> in check_anagrams(word1, word2)
      4     Returns True if the word1 and word2 are anagrams, otherwise returns False
      5     """
----> 6     return sorted(word1) == sorted(word2)
      7 
      8 print(check_anagrams("silent", "listen"))

TypeError: 'int' object is not iterable

With the second call of the function, we used it incorrectly with passing the integer 5 for the word2. A TypeError was thrown in this situation. We can see that the message is a little bit confusing. So, we can try to check that the two words are passed as strings and thrown an error with a more descriptive message. We can use the **raise** keyword to throw an error.

def check_anagrams(word1, word2):
    """
    Check if the two passed words are anagrams.
    Returns True if the word1 and word2 are anagrams, otherwise returns False
    """
    if type(word1) != str or type(word2) != str:
        raise TypeError("The word1 and word2 must be strings")
    
    return sorted(word1) == sorted(word2)

print(check_anagrams("silent", "listen"))
print(check_anagrams("silent", 5))

Output:

True

--------------------------------------------------------------------
TypeError                          Traceback (most recent call last)
<ipython-input-3-afb475aa2f4f> in <module>()
     10 
     11 print(check_anagrams("silent", "listen"))
---> 12 print(check_anagrams("silent", 5))

<ipython-input-3-afb475aa2f4f> in check_anagrams(word1, word2)
      5     """
      6     if type(word1) != str or type(word2) != str:
----> 7         raise TypeError("The word1 and word2 must be strings")
      8 
      9     return sorted(word1) == sorted(word2)

TypeError: The word1 and word2 must be strings

Now, the message is much specific about the problem. Try to catch more specific exceptions and to write specific and clear error messages. You can check all the exception types from the docs.

Assert Statements

Assert statements are a convenient way to sanity-check our code. They’re boolean expressions that check if the conditions return True or False. If a condition returns True, the program moves to the next line of code. Otherwise, an error is raised and the program execution is stopped.

We can think of the assert statements as “raise-if-not” statements.

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
Source: https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement

def check_anagrams(word1, word2):
    """
    Check if the two passed words are anagrams.
    Returns True if the word1 and word2 are anagrams, otherwise returns False
    """
    assert type(word1) == str
    assert type(word12) == str
    
    return sorted(word1) == sorted(word2)

print(check_anagrams("silent", "listen"))
print(check_anagrams("silent", 5))

Output:

True

--------------------------------------------------------------------
AssertionError                     Traceback (most recent call last)
<ipython-input-68-e5a7f4b2ffc2> in <module>()
     10 
     11 print(check_anagrams("silent", "listen"))
---> 12 print(check_anagrams("silent", 5))

<ipython-input-68-e5a7f4b2ffc2> in check_anagrams(word1, word2)
      5     """
      6     assert type(word1) == str
----> 7     assert type(word2) == str
      8 
      9     return sorted(word1) == sorted(word2)

AssertionError:

Hmmm, but there is no error message. What if we want to add a message to this AssertionError? We can pass it separated with a comma, right after our expression.

def check_anagrams(word1, word2):
    """
    Check if the two passed words are anagrams.
    Returns True if the word1 and word2 are anagrams, otherwise returns False
    """
    assert type(word1) == str, "The word1 must be a string"
    assert type(word2) == str, "The word2 must be a string"
    
    return sorted(word1) == sorted(word2)

print(check_anagrams("silent", "listen"))
print(check_anagrams("silent", 5))

Output:

True

--------------------------------------------------------------------
AssertionError                     Traceback (most recent call last)
<ipython-input-66-5f2e42abf116> in <module>()
     10 
     11 print(check_anagrams("silent", "listen"))
---> 12 print(check_anagrams("silent", 5))

<ipython-input-66-5f2e42abf116> in check_anagrams(word1, word2)
      5     """
      6     assert type(word1) == str, "The word1 must be a string"
----> 7     assert type(word2) == str, "The word2 must be a string"
      8 
      9     return sorted(word1) == sorted(word2)

AssertionError: The word2 must be a string

Type Hints

Python is a dynamically-typed language. When we’re defining your variables, functions, classes, etc. we don’t need to specify data types. This allows us to write code faster.

However, from Python version 3.5 we have the ability to add type hints in our function definitions. We can say what are the expected data types for the arguments and what data type the function returns.

def greeting(name: str) -> str:
    return 'Hello ' + name

print(greeting("Ventsi"))
print(greeting(42))

Output:

Hello Ventsi

--------------------------------------------------------------------TypeError                          Traceback (most recent call last)
<ipython-input-28-b1c33d5121c9> in <module>()
      1 print(greeting("Ventsi"))
----> 2 print(greeting(42))

<ipython-input-1-311aff60a9bd> in greeting(name)
      1 def greeting(name: str) -> str:
----> 2     return 'Hello ' + name

TypeError: must be str, not int

We can also define type aliases.

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(new_vector)

Output:

[2.0, -8.4, 10.8]

You can find more information here.

Passing mutable vs immutable objects

We have to be careful when we’re passing mutable objects to our functions. The arguments passed in a function call are using the object reference, not the value of the object. So, keep in mind that some functions can change the value of the passed objects.

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

def capitalize_sentences(sentences):
    for index, item in enumerate(sentences):
        sentences[index] = item.capitalize()

sentences = ["this is test sentence", "I love Python", "positive thinking is nice!"]
print("Before calling the function:", sentences)
capitalize_sentences(sentences)
print("After calling the function:", sentences)

Output:

Before calling the function: ['this is test sentence', 'I love Python', 'positive thinking is nice!']
After calling the function: ['This is test sentence', 'I love python', 'Positive thinking is nice!']

We can see that after we called our function, we have changed the contents of the sentences list.

If we want to save the result in a different variable, we can copy the sentences list in our function, do the capitalization for the copy version and return it. This way, we won’t change the sentences list itself (which is what you want in some cases).

def capitalize_sentences(sentences):
    result = sentences.copy()
    for index, item in enumerate(result):
        result[index] = item.capitalize()
    return result

sentences = ["this is test sentence", "I love Python", "positive thinking is nice!"]
print("Before calling the function:", sentences)
capitalized_sentences = capitalize_sentences(sentences)
print("After calling the function:", sentences)
print("Capitalized sentences (result of the function):", capitalized_sentences)

Output:

Before calling the function: ['this is test sentence', 'I love Python', 'positive thinking is nice!']
After calling the function: ['this is test sentence', 'I love Python', 'positive thinking is nice!']
Capitalized sentences (result of the function): ['This is test sentence', 'I love python', 'Positive thinking is nice!']

Summary

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements

Final Words

Thank you for the read. I hope that you have enjoyed the article. If you like it, please hold the clap button and share it with your friends. I’ll be happy to hear your feedback. Let me know if you want a blog post about lambda functions. If you have some questions, feel free to ask them. 😉

Learn More

Complete Python Bootcamp: Go from zero to hero in Python 3

Complete Python Masterclass

Learn Python by Building a Blockchain & Cryptocurrency

Python and Django Full Stack Web Developer Bootcamp

The Python Bible™ | Everything You Need to Program in Python

Learning Python for Data Analysis and Visualization

Python for Financial Analysis and Algorithmic Trading

The Modern Python 3 Bootcamp

Resources:

  • What are functions and how to define them
  • What are the parameters and arguments
  • How to return values from functions
  • How to define a function documentation
  • What represents the scope in Python
  • What are keyword arguments
  • Flexible and Default arguments
  • What are the Python exceptions and how to handle and how to raise them
  • Assert Statements

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Download free Exercise files.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: