Python is a dynamically typed, interpreted, object-oriented and high-level programming language that is designed to be clear and concise, emphasizing readability through the use of whitespace indentation rather than traditional braces or keywords. It has solidified itself as a favorite among developers for its versatility and readability. This readability, often referred to as the "Pythonic" way, contributes to the language's ease of learning and maintenance.
Introduction to the language
History & Versions
Python was developed by Guido van Rossum, from the Netherlands. He aimed to create a language that emphasized code readability and ease of use, allowing developers to express concepts in fewer lines of code than languages like C++ or Java.
Python has gone through 3 major release cycles.
- Python 1.0 (1994)
- Initial release by Guido van Rossum.
- Core features included exception handling, functions, and modules.
- Introduced lambda, map, filter, and reduce functions.
- Marked the foundation of Python's design principles.
- Python 2.0 (2000)
- Introduced list comprehensions, a concise way to create lists.
- Added garbage collection for better memory management.
- Unicode support was introduced.
- Saw the introduction of the 'print' statement.
- Python 3.0 (2008)
- A major overhaul for code readability and simplicity.
- Removed legacy features from Python 2 that caused inconsistencies.
- Print became a function (print()).
- Introduced
bytesandbytearraytypes for handling binary data. - Unicode support was strengthened.
- Improved syntax and exception handling.
Since Python 3.0, the development of Python has been guided by a commitment to improving readability, simplicity, and addressing inconsistencies. The Python Software Foundation (PSF) and the Python community aim to maintain Python's position as a versatile and accessible programming language. The focus has been on introducing features that enhance developer productivity, encourage best practices, and support emerging trends in software development. Recent versions, have introduced modern syntax enhancements, structural pattern matching, and performance improvements. The mission is to continue evolving Python to meet the needs of a diverse range of developers, from beginners to experienced professionals, fostering a vibrant and collaborative ecosystem. The community-driven development model and adherence to the principles of the Zen of Python contribute to Python's enduring popularity and influence in the software development landscape.
Features & Reasons for Popularity and Adoption
Python is in wide adoption across several industries. Here is a quick rundown of the reasons for python's popularity.
- Readability and Simplicity - Python's syntax is designed for readability and clarity, making it easy for beginners to learn and for experienced developers to maintain and understand code.
- Versatility - Python is a versatile language that can be used for a wide range of applications, including web development, data science, machine learning, automation, scripting, and more.
- Extensive Standard Library - Python comes with a comprehensive standard library that includes modules and packages for a wide array of tasks, reducing the need for external libraries for many common functionalities.
- Large and Active Community - Python has a vast and active community of developers, which contributes to a wealth of resources, documentation, and third-party libraries. The community fosters collaboration and support, making Python accessible and friendly.
- Compatibility and Portability - Python is cross-platform, meaning code written in Python can run on various operating systems without modification. This portability enhances its usability and makes it an attractive choice for development.
- Diversity of Libraries and Frameworks - Python has an extensive ecosystem of libraries and frameworks catering to different domains, such as Django and Flask for web development, NumPy and Pandas for data science, and TensorFlow for machine learning.
- Adoption in Emerging Technologies - Python has become a language of choice in emerging technologies like artificial intelligence, machine learning, and data science, contributing to its continued growth and relevance.
- Ease of Learning - Python's clean and straightforward syntax reduces the learning curve for new developers, making it an ideal language for beginners. This ease of learning contributes to its popularity in educational settings.
- Community-Driven Development - Python's development is guided by a collaborative and community-driven model, where decisions are made openly. This ensures that the language evolves in a way that reflects the needs and preferences of its user base.
- Strong Industry Support - Many companies and organizations across various industries use Python for their projects, contributing to its widespread adoption and support.
Use Cases for the Language
- Web Development:
- Frameworks: Django, Flask, FastAPI.
- Use Cases: Building websites, web applications, and APIs.
- Data Science and Analytics:
- Libraries: NumPy, Pandas, Matplotlib, Seaborn.
- Use Cases: Data analysis, visualization, statistical modeling.
- Machine Learning and Artificial Intelligence:
- Libraries: Scikit-Learn, TensorFlow, PyTorch.
- Use Cases: Developing and deploying machine learning models, natural language processing.
- Automation and Scripting:
- Use Cases: Task automation, system administration, scripting.
- Scientific Computing:
- Libraries: SciPy, SymPy.
- Use Cases: Numerical simulations, scientific research.
- Databases and Data Storage:
- Libraries: SQLAlchemy, SQLite.
- Use Cases: Database interaction, data storage.
- Network Programming:
- Libraries: Requests, Socket.
- Use Cases: Network protocols, web scraping, API interactions.
- Game Development:
- Frameworks: Pygame.
- Use Cases: 2D game development, simulations.
- **Cybersecurity:
- Libraries: PyCryptodome.
- Use Cases: Cryptography, security analysis.
- Desktop GUI Applications:
- Libraries: Tkinter, PyQt, Kivy.
- Use Cases: Developing graphical user interfaces.
- DevOps and Automation:
- Tools: Ansible, SaltStack.
- Use Cases: Configuration management, automation of IT tasks.
- Education:
- Use Cases: Teaching programming concepts, as a first programming language.
- IoT (Internet of Things):
- Libraries: MicroPython.
- Use Cases: Programming IoT devices.
- Finance:
- Libraries: Pandas, NumPy.
- Use Cases: Financial modeling, data analysis in finance.
- Bioinformatics:
- Libraries: Biopython.
- Use Cases: Analyzing biological data, genomic research.
Current Trends
Programming languages constantly evolve and improve. Python is no different to this. Some of the latest trends observed in python as showcased below.
- Machine Learning and Artificial Intelligence (AI) - Python remains a dominant language in the field of machine learning and AI. Libraries like TensorFlow and PyTorch continue to be widely used for developing and deploying machine learning models.
- Data Science and Analytics - Python's popularity in data science continues to grow. Pandas and NumPy are extensively used for data manipulation and analysis, while tools like Jupyter Notebooks enhance the interactive data exploration experience.
- Web Development - Web development with Python, particularly using frameworks like Django and Flask, continues to be a strong trend. The emphasis is on building scalable and efficient web applications.
- Serverless Computing - The adoption of serverless architecture and platforms, such as AWS Lambda and Azure Functions, is growing. Python is often a preferred language for writing serverless functions due to its simplicity.
- DevOps and Automation - Python's role in DevOps and automation is on the rise. Tools like Ansible and SaltStack, both written in Python, are widely used for configuration management and automation of IT tasks.
- Data Engineering - With the increasing focus on data-driven decision-making, Python is frequently used in data engineering tasks. Libraries like Apache Spark with PySpark enable scalable data processing.
- Containerization and Microservices - Python is commonly used in containerization technologies like Docker. Microservices architectures, often implemented using Python-based frameworks like FastAPI, are gaining popularity.
- Blockchain Development - Python is used in blockchain development, particularly in the creation of smart contracts. Libraries like Web3.py facilitate interaction with Ethereum-based smart contracts.
- Natural Language Processing (NLP) - NLP applications are expanding, with Python libraries such as NLTK and spaCy being widely used for tasks like sentiment analysis, chatbots, and language translation.
- Quantum Computing - As quantum computing gains attention, Python is being used for quantum programming. Libraries like Qiskit provide a Python interface for working with quantum computers.
- Cybersecurity - Python is used for various cybersecurity tasks, including penetration testing, scripting for security automation, and developing security tools.
- Cross-Platform Mobile App Development - Python frameworks such as Kivy and BeeWare are gaining traction for cross-platform mobile app development, offering the ability to write once and deploy on multiple platforms.
Foundations
Syntactical Fundamentals
Input and Output
Commenting
Indentation
Overview
Python is a high-level, interpreted, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.
Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming.
Basics of Python
Print
One of the most common actions to be done when working with code is to print output to the screen/console. To print in Python, the following syntax is used.
---
# Python Print Syntax
print("Something to be printed")
# print statement
print("Something on line 1 \n Something on the next line")
# printing in a new line
print("Some text " + "Other text")
# Concatenation in print statements
---By using \n, it is possible to manually insert line return within the print statement. The slash \ here is used to escape characters. It is possible to concatenate strings using + when printing to the screen/console. It is important to note that, only strings can be concatenated, thus any and if numbers exist, they need to be converted to numbers in order to perform the concatenation operation.
It is also possible to combine variables in the print statements without the use of a concatenation. These type of strings are called as f-Strings. It is accomplished by adding an f before the first quote within the print function, followed by mentioning the variable name within curly brackets.
---
# Python Print with f-Strings
a = 10
print(f"The value stored in the variable a is {a}")
---Input
The next important action might be to get input from the user. This is accomplished by the following syntax.
---
# Python Input Syntax
input("Something to ask the user")
---When python sees the input statement, it waits for the user to provide a response in order for it to process in the flow of code execution. Generally, most input statements get saved in variables for later use within the code. Usually, input statements take in strings as inputs. This means that any numbers that are taken as inputs from the user will be considered as strings, unless they are converted before storing in a variable.
Comments
One of the most important aspects of Programming and Scripting is documentation. Commenting is key to documentation and the code should be self-documenting. To make comments in Python, the following syntax is used.
---
# This is a python comment
---Indentation
Indentation or insetting or whitespace at the beginning the code is very important in python as it does not use brackets or parentheses to differentiate a code block. The standard is 4 spaces. Most IDEs use 1 tab as 4 spaces, so that tabs can be used easily instead of typing spaces 4 times each time.
---
# Indentation in python
a = 10
b = 20
if b > a:
print("b is greater than a")
# Correct indentation practice
a = 10
b = 20
if b > a:
print("b is greater than a")
# Incorrect indentation practice - throws an error
---Data Types
Any data that can be stored in computer memory to be utilized when the program is executed belongs to a particular type. Some of the most common data types used in Python are given below classified into related types.
| Data Type Group | Data Types |
|---|---|
| Text Types | str |
| Numeric Type | int, float, complex |
| Sequence Type | list, tuple, range |
| Mapping Type | dict |
| Boolean Type | bool |
| Binary Type | bytes, bytearray, memoryview |
| None Type | NoneType |
to know the data type of a variable, the type() function can be used to get the data type. The syntax for the type function is give below.
---
x = 10
print("x is of type: " + type(x))
# Here the data type of x (int) is printed to the screen/console
---These data types can be declared when a variable is defined. However, it is also possible to convert the data type of a variable to another. There are 2 types of data type conversions available in python.
- Implicit Conversions - Data types that are converted into another by the python interpreter during execution.
---
x = 10
y = 2.5
x = x + y
print("x is of type: " + type(x))
# Here x is converted to float data type
---- Explicit Conversions - Data type conversions that are explicitly mentioned by the program. Explicit conversions offer additional arguments in certain conversions. ^print-conversions
---
x = 10
x = float(x)
print("x is of type: " + type(x))
# Here x is converted to float data type
---Read More: Type Conversion in Python - Geeks for Geeks
Arrays
Arrays or collections are ways to store a multitude of information in a variable. Python offers 4 types of such array data types. They are
- List - Collection which is ordered and changeable. It allows duplicates.
- Tuple - Collection that is ordered and unchangeable. It allows duplicates.
- Set - Collection that is unordered, unchangeable and unindexed. No duplicates allowed.
- Dictionary - Collection that is ordered and changeable. No duplicates allowed.
| Attribute | Description |
|---|---|
| Ordered | Items have a defined order which does not change. New items are added in the end. |
| Changeable | Items can be added, removed or modified after the creation. |
| Duplicates | When an array is indexed, it can support duplicate entries. |
List
- Lists are used to store collections of data that are indexed, ordered and changeable.
- A list is declared by using square brackets
[]. - Since the list is indexed, there can be duplicates in the list as well.
- Lists can have collection of any data types, but the list in itself is an object of the data type
list. - Lists are mutable in nature.
- For lists, reference is made whenever it is passed as an argument or assignment.
- This means that any changes made in any one of the lists will be reflected in the other as well.
---
# List declarations and data types
myList = [10,11,12,13,12] # myList - list of integers
otherList = ['cat','dog','mouse', 10, 12, 20] # otherList - mix of str and integers
someList = [['cat','dog','mouse'],[10, 12, 20]] # someList - list of lists
---- Indexing and accessing data
- Python is a 0 indexed language, hence lists are indexed from 0.
- The individual entries of a list can be accessed by their index.
- If a negative index is provided, it fetches the data from the end.
- It is also possible to provide a range of indices to fetch.
- If a range is given, the lower limit is included and the upper limit is excluded from the list, meaning a
listName[2:4]will retrievelistName[2], listName[3]and omitslistName[4]. - If the lower range index is omitted, then the list is fetched from the beginning till the specified index, but not including it.
- If the upper range index is omitted, then the list is fetched from the specified lower limit till the end of the list.
- Negative index ranges can also be used to retrieve a list of entries from the end.
- Lists can have lists within them accessed by the respective nested indexing.
---
# Indexing and accessing data
myList = [10,11,12,13,12] # myList - list of integers
someList = [['cat','dog','mouse'],[10, 12, 20]] # someList - list of lists
print(myList[3]) # 4th List item - index 3
print(myList[-1]) # Last list item
print(myList[1:4]) # Entries with the index 1,2,3
print(myList[:3]) # All entries from start till index 2
print(myList[1:]) # All entries from index 1 till end
print(myList[-1:-3]) # Last 2 entries
print(someList[0][2])
# Output
> 13
> 12
> 12,13,14
> 10,11,12,13
> 11,12,13,12
> 13,12
> mouse
---- Changing items in a list
- The process or changing an element is a list is same as changing any variable after the list item is accessed.
- Changing a range of values is the same as accessing a range of values, then passing a list to be replaced in its place.
- To insert an item in a list, the
insert()function can be used. - The insert function takes two arguments
insert(location, value to be inserted).
---
# Changing items in a list
myList = [10,11,12,13,12]
myList[1] = 400
print(myList)
myList[2:4] = [100,200]
myList.insert(1,69)
print(myList)
# Output
> 13
> 12
> 12,13,14
> 20
> 10,400,12,13,12
> 10,400,100,200,12
> 10,69,100,200,12
---- List Methods
- Python by default provides a list of methods to work on lists.
- These enable actions such as add, remove, sort items from or to a list.
| Method | Description | syntax |
|---|---|---|
| append() | Adds an element at the end of the list | listName.append(element) |
| clear() | Removes all the elements from the list | listName.clear() |
| copy() | Returns a copy of the list | listName.copy() |
| count() | Returns the number of elements with the specified value | listName.count(element) |
| extend() | Add the elements of a list (or any iterable), to the end of the current list | listName.extend(iterable) |
| index() | Returns the index of the first element with the specified value | listName.index(element) |
| insert() | Adds an element at the specified position | listName.insert(position, element) |
| pop() | Removes the element at the specified position | listName.pop(position) |
| remove() | Removes the first occurrence of the item with the specified value | listName.remove(element) |
| reverse() | Reverses the order of the list | listName.reverse() |
| sort() | Sorts the list in an ASCII-betical order | listName.sort(reverse=True/False,Key=myfunc) |
- Adding and removing list items
- Looping through lists
- List Comprehension
- Actions on List
Tuple
Set
Dictionary
- Dictionaries are used to store data in key-value pairs.
- They are ordered, mutable and do not allow duplicates.
- They are declared using the curly brackets
{}and have keys and the values associated with them. - No duplicate can exist as a dictionary cannot have two keys of the same name.
- Dictionary values can be of any data type, but the dictionary itself is of the data type
dict.
---
# Dictionary declarations and data types
myCat = {
'name': 'Florence',
'breed': 'Persian',
'color': 'grey'
}
---- Accessing items
- Values in a list are accessed using the keys they are associated with.
- Keys can be integers and strings.
- To check if a key exists in a dictionary, use the
inoperator - Accessing a key that does not exist in the dictionary results in a
KeyError. - In order to avoid the missing key error, the
get()method can be used. - The
get()method takes 2 arguments - the key to get and the value to default to if it is not available. - Accessing the dictionary can be done via 3 special methods specific to dictionaries, namely,
- Accessing keys - All keys of a dictionary can be accessed via the
keys()method. - Accessing values - All values of a dictionary can be accessed via the
values()method. - Accessing items - All items of a dictionary can be accessed via the
items()method.
- Accessing keys - All keys of a dictionary can be accessed via the
---
# Dictionary declarations and data types
myCat = {
'name': 'Florence',
'breed': 'Persian',
'color': 'grey'
}
print(myCat['name'])
'name' in myCat
'name' not in myCat
myCat.keys()
myCat.values()
myCat.items()
myCat.get('species','')
# Output
> 'Florence'
> True
> False
> dict_keys(['name', 'breed', 'color'])
> dict_values(['Florence', 'Persian', 'grey'])
> dict_items([('name', 'Florence'), ('breed', 'Persian'), ('color', 'grey')])
> ''
---- Changing items
- Once the items are accessed from a dictionary, values can be assigned to them.
- Dictionaries also support multiple assignment.
- To set a default value to a key, the
setdefault()method is used. - It assigns a value to a key if it does not exist.
- It takes two arguments - they key to set for and the default value to set.
---
# Dictionary declarations and data types
myCat = {
'name': 'Florence',
'breed': 'Persian',
'color': 'grey'
}
myCat['name'] = 'Dalia'
print(myCat['name'])
myCat.setdefault('species','cat')
print([myCat['species']])
# Output
> 'Dalia'
> `cat`
---- Dictionary methods
Variables
Variables can be declared with a variable name and a value to it. The equals to (-``python --- a = "a string" # Both single and double quotes can be used
b = 10
# int assignment
c = 10.5
# float assignment
d = [1,2,3,4,5]
# list assignment
# It is also possible to explicitly mention the data type when declaring variables
e = float(3)
f = str(100542212)
---
The **scope of a variable** is the region of code to which the variable would be available for use. The scope of variables in python are *within the block in which they are declared*. There can be two types of scopes for variables in python, namely
1. **Global Scope** - Available to the entirety of the program/code to access it.
2. **Local Scope** - Available only to the block of code it is associated with.
Following is a showcase of scope of variables.
Some of the rules for scoping of variables are
- Code in the global scope cannot use local variables.
- Code in a local scope can access global variables.
- Code in one function's local scope cannot access variables in another function's local scope.
- Variable names can repeat across local scopes.
The order of preference for variable scoping by python is done by the following assumption
- *Local Scope* - If assignment statement is present
- *Global Scope* - If assignment statement is absent
```python
---
# Variable Scope
n = 10
# Value of n is 10 - Global Scope
def some_function():
n = "a string"
# Value of n is "a string" - Local Scope
def otherfunction():
global n
n = n + 1
print(n)
# N is assiged a value of n+1 which uses the global n variable
---Python also allows for multiple variable assignment which enables to assign a multitude of variables in a single declaration. It can be used for single value variables or sequences.
---
# Multiple variable assignment
cat = ['Persion', 'White', 4]
catBreed, catColor, catAge
---Rules for naming variables
- Can have alphanumeric characters - make meaningful variable names.
- Cannot begin with a number - But can take numbers from the second character of the variable name.
- No space can be present - Use underscore (_) or hyphen (-) to mimic spaces when using multiple words.
- Do not use keywords as variable names - The interpreter does not throw an error, but it is good practice not to use the keywords as variable names to avoid conflicts.
Operators
Operators perform actions on variables and values.
Arithmetic Operators
Arithmetic operators are used with numeric values to make mathematical calculation.
| Operator | Name | Example |
|---|---|---|
| + | Addition | x + y |
| - | Subtraction | x - y |
| * | Multiplication | x * y |
| / | Division | x / y |
| % | Modulus | x % y |
| ** | Exponentiation | x ** y |
| // | Floor Division | x // y |
Comparison Operators
They are used to compare two values.
| Operator | Name | Example |
|---|---|---|
| == | Equal | x == y |
| != | Not Equal | x != |
| > | Greater Than | x > y |
| < | Lesser Than | x < y |
| >= | Greater Than or Equal To | x >= y |
| <= | Lesser Than or Equal To | x <= y |
Logical Operators
Logical Operators are used to combine conditional statements.
| Operator | Description | Example |
|---|---|---|
| and | Returns true if both statements are true | x < 5 and x < 10 |
| or | Returns true if any of the statements is true | x < 5 or x < 4 |
| not | Reverses the result - true is false and vice versa | not (x < 5) |
Identity Operators
Identity operators are used to compare objects if they are the actual same objects. These do not check for the similarity of content within the variable, but the actual memory location.
| Operator | Description | Example |
|---|---|---|
| is | Returns true if both variables are the same object | x is y |
| is not | Returns true is both variables are different objects | x is not y |
Membership Operators
Membership operators are used to test if a sequence is presented in an object of comparison.
| Operator | Description | Example |
|---|---|---|
| in | Returns true if a sequence with the specified value is present in the object | x in y |
| not in | Returns true if a sequence with the specified value is not present in the object | x not in y |
Bitwise Operators
Bitwise operators are used to compare binary numbers.
| Operator | Name | Description |
|---|---|---|
| & | AND | Sets each bit to 1 if both bits are 1 |
| | | OR | Sets each bit to 1 if one of the two bits is 1 |
| ^ | XOR | Sets each bit to 1 if only one of two bits is 1 |
| ~ | NOT | Inverts the bits |
| << | Zero Fill Left Shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |
| >> | Signed Right Shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
Assignment Operators
The assignment operators are used to assign values to variables.
| Operator | Example | Same As |
|---|---|---|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| %= | x %= 3 | x = x % 3 |
| //= | x //= 3 | x = x // 3 |
| **= | x **= 3 | x = x ** 3 |
| &= | x &= 3 | x = x & 3 |
| |= | x |= 3 | x = x | 3 |
| ^= | x ^= 3 | x = x ^ 3 |
| >>= | x >>= 3 | x = x >> 3 |
| <<= | x <<= 3 | x = x <<= 3 |
Functions
Functions are pre-made blocks of code that runs when they are called for. Functions can have parameters or arguments, which are inputs to the functions. A function can perform a task and/or return an output.
In python, functions can be from 3 different sources
- In-built Functions
- User-defined Functions
In-built Functions
In-built functions are pre-defined functions that the user can use to perform actions with the code.
User-defined Functions
Defining
In python, functions can be defined using the def keyword. A semi-colon is used to mark the start of a function. The general syntax of a function is given below.
---
# Defining (creating) a function
def some_function():
x = 10
y = 20
print(x+y)
---Calling
The functions that are already created, can be called at any point in the program with the following syntax.
---
# Calling a function as a part of a program
def some_function():
x = 10
y = 20
print(x+y)
print("Part of a larger program")
some_function()
print("Part of a larger program")
---Passing Parameters
Parameters or Arguments are information that is passed into a function so that it can process it. They are specified within parentheses after the function name. A function can have multiple arguments.
[!faq] Parameters and Arguments Parameters and arguments are terms used to refer the same thing, the information that is passed into a function. But from a function's perspective, they can be differentiated as given below
- A parameter is the variable listed inside the parentheses in the function's definition.
- An argument (abbreviated as args in python documentation) is the value that is sent to the function when it is executed/called.
Any data type sent as argument is preserved inside the function it is sent to. By default, a function should be called with the same number of arguments it expects as per its definition, no more, no less. If a function is passed with either, it throws an error. However, it is possible to set up a function to pass n arguments when the number of arguments that might be passed is not known beforehand.
This type of arguments are known as Arbitrary Arguments (*args in python documentation). Here, the function receives a tuple of arguments and they can be accessed later within the function. An example of *args is given below for syntax reference.
---
# Arbitrary Arguments in action
def fruit_fifo_tracker(*fruits):
print("The first fruit is " + fruits[0])
# prints the first fruit in the tuple
fruit_fifo_tracker("Apple","Orange","Papaya")
---Python functions also accept keyword pairs as arguments. These are referred to as Keyword Arguments (kwargs in python documentation). In such a case, the order of the arguments does not matter. Arbitrary Keyword Arguments (**kwargs in python documentation) can also be passed to a function. In this case, a dictionary (dict) is sent to the function from which the data can be accessed.
---
# Keyword Arguments in action
def staples(popular,profitable,cheap):
print("The profitable staple is " + profitable)
# prints the argument
staples(cheap = "Maida", profitable = "Rice",popular = "Wheat")
---
# Arbitrary Keyword Arguments in action
def staples(**staples_set):
print("The profitable staple is " + staples_set["profitable"])
# prints the argument
staples(profitable = "Rice",popular = "Wheat")
---It is also possible to set a default argument for a function that will be considered, if no argument is passed to the function when it is called. Below is an example of how it is done.
---
# Setting Default Arguments
def fav_fruit(best_fruit = "apple"):
print("The best fruit is " + best_fruit)
# prints apple if no arguments are passed.
fav_fruit("Papaya")
# papaya is printed
fav_fruit()
# apple is printed
---Return Values
Functions can also return values to when they are called in a part of a program. A example of how this is accomplished is given below for syntax reference.
---
# Returning values
def numerical_sum(a,b):
return a + b
c = numerical_sum(5,8)
print("The sum is " + c)
# The sum, of value 13 is printed on the screen/console
---Pass Statement
Function definitions cannot be empty, by default. To circumvent this, and to have an empty function without any content within it, the pass statement can be added into the function. A example of how this is accomplished is given below for syntax reference.
---
# Pass statement in a function
def numerical_sum():
pass
---Function Libraries
Branching
Branching in programming allows to execute different blocks of code based on a condition. Branching is accomplished in Python by if, else and elif .
- The
ifstatement is the most basic branching statement. It checks for a condition and allows to either execute or skip the block of code. It can be a standalone condition in code. - The
elifstatement is used to check for another condition if the if condition fails. It cannot be a standalone conditional check. - The
elsestatement is used to execute another block if theifor theelifconditions fail. It cannot be a standalone conditional check.
---
# Branching in python
a = int(input("Enter a number between 1 and 10"))
if a > 10:
print("Enter a number less than 10")
elif a < 0:
print("Enter a number greater than 0")
else:
print("You have entered a correct number")
---It is also possible to write the entire conditional flow in a single line, when there is only one action to be performed based on a branching condition. if, elif and else branches can be used in a similar way. This technique is known as Ternary Operators or Conditional Expressions.
---
# Single-line branching in python
a = 10
b = 20
if a > b: print("a > b")
# For branches with only if condition
print("a > b") if a > b else print("a < b")
# For branches with if and else conditions
print("a > b") if a > b else print("a = b") if a == b else print("a < b")
# For branches with if, elif and else conditions
---Logical operators can be used to evaluate logical conditions when branching. The use of and, or and not logical operators is possible.
---
# Logical operators for branching in python
a = 10
b = 20
c = 15
if a > c and b > c:
print("c is the smallest")
elif a > c or b > c:
print("Either a or b is larger than c")
elif not(a == c):
print("a is not equal to c")
else:
print("Above conditions failed")
---Branches can be nested as well, meaning an if branch can sit within an if branch and so on. Indentation is very important in such cases for the flow of programmatic execution.
---
# Nested branching in python
a = 10
b = 20
c = 5
if a > b:
if c > a:
print("c is the largest")
else:
print("a is not greater")
---The pass statement can be used in branching as well, to skip a block of branching code if no code is to be entered.
---
# Pass from a block for branching in python
a = 10
b = 20
if a > b:
pass
# The branch is skipped
---Loops
Python has two primitive loop types, namely
- For Loops - A conditional iterative looping mechanism.
- While Loops - A mechanism to loop as long as a condition is true.
FOR Loops
The for loop is used to iterate over a sequence. This sequence can be a list, tuple, dictionary, set, or a string. The loop runs once for every item in the sequence. It does not need a variable to be initialized beforehand for execution. The general syntax of a for loop is give below for reference.
---
# Basic for loop in python
fruits = ["Apple", "Banana", "Pineapple"]
for x in fruits:
print(x)
---for loops can loop through the following iteratable entities.
- list
- string
- tuple
- dictionary
- set
---
# Looping through a string
for x in "banana":
print(x)
---The break statement is used to exit a loop before the entire iteration is performed. The most common use case might be to check for a condition and exit the loop. Alternatively, a continue statement is used to send the flow of execution back to the beginning of the loop. An example of this is given below.
---
# Break statement in python
fruits = ["Apple", "Banana", "Pineapple"]
for x in fruits:
if x == "banana":
break
print(x)
# Outputs
> Apple
---
# Continue statement in python
fruits = ["Apple", "Banana", "Pineapple"]
for x in fruits:
if x == "banana":
continue
print(x)
# Outputs
> Apple
> Pineapple
---The range() function is used to iterate over a sequence of numbers. It takes a number and starts counting from 0 and increments by 1 (by default). The function takes 3 arguments. The structure is as follows in its various forms along with examples for usage syntax.
---
# range() function in python
# 1 argument form:
> range(end number)
for i in range(5):
print(i)
# starts from 0, iterates 5 times as 0, 1, 2 ,3, 4
# 2 argument form:
> range(start number, end number)
for i in range(2,6):
print(i)
# starts from 2, iterates 4 times as 2 ,3, 4, 5
# 2 argument form:
> range(start number, end number, increment)
for i in range(2,10,2):
print(i)
# starts from 2, iterates 4 times as 2 ,4, 6, 8 incrementing by 2
---Whenever an end number is provided, the number is not included in the iterative values it generates. So a range(2,5) has the values 2,3,4
The else condition can be used with the for loop to execute a block of code when the loop completes its iteration. The else block is not executed if the loop is terminated by a break statement.
---
# else statement with for loops in action
fruits = ["Apple", "Banana", "Pineapple"]
for x in fruits:
print(x)
else:
print("The looping is completed")
---Nested loops can be used in for loops. the inner block is executed each time an outer block iteration occurs.
WHILE Loops
The while loop is used to execute a block of code as long as the condition remains true. This type of loops are more prone to infinite loops and thus care must be taken to set the conditions correctly for termination of the loop. while loops need a variable to be initiated before the start of the execution in order for the loop to check the condition.
---
# Basic while loop
i = 1
while x < 5:
print(x)
x += 1
---While loop also takes the continue and break statements to skip iteration or exit the loop respectively. The else statement can be used in conjunction to execute a code block when the while loop completes its execution.
Recursion
Recursion is a common mathematical and programming concept where a function can call itself until a condition is met. Python allows for recursion of functions. Care must be taken when recursive functions, which could easily end up in an infinite loop or end up taking too much memory and processor capacity. An example of recursion in action is given below for reference.
---
# Recursive function
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
# Executes the recursive function
---Errors and Exceptions
Errors are problems in the program due to which the program could not be executed. Exceptions are cases where the normal flow of the program is affected due to some event in the code execution.
Syntax errors are thrown when the proper syntax of the code is not followed. Logical errors or exceptions are observed when there is a mistake in logic of the code is not behaving in a normal flow of operation. Some of the common types of exceptions are noted below.
| Exception | Description |
|---|---|
| IndexError | When the wrong index of a list is retrieved |
| AssertionError | Occurs when the assert statement fails |
| AttribueError | Occurs when an attribute assignment is failed |
| ImportError | Occurs when an imported module is not found |
| KeyError | Occurs when the key of the dictionary is not found |
| NameError | Occurs when the variable is not defined |
| MemoryError | Occurs when a program runs out of memory |
| TypeError | Occurs when a function and operation are applied in an incorrect type |
Error Handling can be done using the try - except - finally method. The code to try out is in the try section, the fallback code is in the except section, and the finally section contains the code to run in the end.
---
# Error handling with try - except - finally method
try:
print("Code Beginning")
print(1/0) # Unsafe Code
except:
print("Encountered Error") # Fallback code
finally:
print("Code End") # Final code
---It is also possible to raise exceptions by using the raise statement. It is possible to define the type of error to raise and the text to print to the user. An example of raising an exception is given below for syntax reference.
---
# Raising exceptions
x = "hello"
if not type(x) is int:
raise TypeError("Only intergers are allowed")
# Here, a TypeError exception is raised with the message specified
---