Python Tutorial: Python Is All You Need
Welcome to the “Python Is All You Need” tutorial series! In this series, we will be diving into the world of Python programming, starting from the basics and working our way up to more advanced topics. Python is a powerful and versatile programming language that can be used for a wide range of tasks, from web development to data analysis to machine learning. Whether you’re a beginner looking to learn your first programming language or an experienced developer looking to add Python to your toolset, this series has something for you.
Throughout the course, we’ll be using real-world examples and hands-on exercises to help you understand and apply the concepts you learn. This course also has video-based tutorials as well.
By the end of the series, you’ll have the knowledge and skills you need to start using Python to solve problems and build projects on your own. So let’s get started!
Buy Python Ebook at only RS. 59 (INR): https://techport.stores.instamojo.com/product/3513410/python-is-all-you-need/
Python Tutorial Playlist: https://www.youtube.com/playlist?list=PLIfUaQYD8YwhKvTnfbCZa6YUDRTAd9QZD
1. What is Python?
Python is a high-level, interpreted programming language that is widely used for web development, data analysis, artificial intelligence, and scientific computing. It is known for its simplicity and easy-to-read syntax, making it an excellent language for beginners to learn.
2. Why Python?
Python is a versatile language that can be used for a wide range of tasks, from web development to data analysis. It also has a large and active community, which means there are many resources and libraries available to help you with your projects. Additionally, Python is in high demand in the job market, making it a valuable skill to have.
3. Getting Started To get started with Python
You will need to first download and install the software on your computer. You can download Python from the official website at python.org.
4. Installation
To install Python, simply download the installer for your operating system and run it. The installer will guide you through the installation process. Once you have installed Python, you can start writing and running your own Python code.
5. Where and How to Code
There are a few different ways to write and run Python code. One popular option is to use an integrated development environment (IDE) like PyCharm or IDLE. These programs provide a text editor and a console for running your code. Another option is to use a simple text editor like Notepad and run your code in the command line.
6. First Program
To write your first Python program, open up an IDE or text editor and start a new file. In this file, you can write Python code and save it with a .py file extension. Here’s an example of a simple Python program that prints “Hello, World!” to the console
print("Hello, World!")
7. Keywords and Identifiers
In Python, keywords are predefined words that have a specific meaning and cannot be used as identifiers. Some examples of Python keywords include “if”, “else”, and “for”. Identifiers, on the other hand, are used to name variables, functions, and other elements in a Python program. They can be any combination of letters, numbers, and underscores, but cannot start with a number.
8. Comments, Statement, and Indentation
In Python, comments are used to explain what a particular piece of code is doing. They are ignored by the Python interpreter and start with the “#” symbol. An example of a comment in Python would be:
# This is a comment
Statements in Python are used to perform actions, such as assigning a value to a variable or calling a function. Indentation is used to indicate the structure of the program and to separate different code blocks.
9. Python Variables, Constants, and Literals
In Python, variables are used to store data, constants are used to store data that will not change, and literals are used to represent fixed values in the code. Here is an example of a variable and a constant being defined in Python:
x = 5 # variable
PI = 3.14 # constant
10. Python Data Types
Python is a powerful programming language that provides a wide range of data types to work with. In this article, we will take a closer look at some of the most commonly used data types in Python: numeric, string, list, tuple, and dictionary.
Python Numeric Data Type
Numeric data types include integers (int) and floating-point numbers (float). For example, the following code defines a variable x as an integer with a value of 10:
x = 10
print(x)
#Similarly, we can define a variable y as a floating-point number with a value of 3.14:
y = 3.14
print(y)
Python String Data Type
Strings in Python are sequences of characters enclosed in quotation marks (either single or double). For example, the following code defines a variable s as a string with a value of “Hello, World!”:
s = "Hello, World!"
print(s)
# In Python, we can also use the + operator to concatenate strings together. For example:
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)
Python List Data Type
A list in Python is an ordered collection of items. Lists are enclosed in square brackets [] and items are separated by commas. For example, the following code defines a variable lst as a list of integers:
lst = [1, 2, 3, 4, 5]
print(lst)
# We can also use the append() method to add an item to a list. For example:
lst.append(6)
print(lst)
Python Tuple
A tuple is similar to a list in Python, but it is immutable, meaning that its elements cannot be changed once defined. Tuples are also enclosed in parentheses () and commas as separate items. For example, the following code defines a variable t as a tuple of integers:
t = (1, 2, 3, 4, 5)
print(t)
We cannot add or remove items from a tuple, but we can access them by index. For example:
print(t[2])
Python Dictionary
A Python dictionary is an unordered collection of items, each with a key-value pair. Dictionaries are also known as associative arrays or hash maps in other programming languages. They are enclosed by curly braces { } and values can be assigned and accessed using square brackets []. The keys of a dictionary must be unique and of an immutable data type, such as strings or numbers.
# Creating a dictionary
my_dict = {'name': 'John', 'age': 25, 'gender': 'male'}
# Accessing values using keys
print(my_dict['name']) # Output: 'John'
print(my_dict['age']) # Output: 25
# Adding new key-value pair
my_dict['location'] = 'New York'
# Updating values using keys
my_dict['age'] = 30
# Deleting a key-value pair
del my_dict['gender']
# Print the dictionary
print(my_dict)
# Output: {'name': 'John', 'age': 30, 'location': 'New York'}
In the above example, a dictionary my_dict
is created with three key-value pairs, 'name', 'age' and 'gender'. We can access the values of the dictionary using the keys. We can also add new key-value pairs, update existing values and delete key-value pairs from the dictionary.
11. Python Type Conversion and Type Casting
Type Conversion: In Python, type conversion refers to the process of converting one data type to another. For example, converting an integer to a string or a float to an integer.
Implicit Type Conversion: Implicit type conversion, also known as “type coercion,” is the automatic conversion of one data type to another. This can occur when performing operations on mixed data types. For example, when adding an integer and a float, Python will implicitly convert the integer to a float before performing the addition.
x = 5
y = 2.5
print(x+y)
# Output: 7.5
In this example, Python implicitly converts the integer x to a float before performing the addition operation, resulting in the output 7.5.
Explicit Type Conversion: Explicit type conversion, also known as “type casting”, is the conversion of one data type to another using a specific function or method. Python provides several built-in functions for type casting, such as int(), float(), str(), etc.
x = 5
y = "10"
z = int(y)
print(x+z)
Output: 15
In this example, the string y is explicitly converted to an integer using the int() function, allowing it to be added to the integer x and resulting in the output 15.
12. Python Input, Output, and Import statements
Python provides several built-in functions to handle input and output operations, as well as to import modules and packages. In this blog post, we will take a look at some of the most commonly used input and output functions, and how to use the import statement in Python.
Input function
The input() function is used to take input from the user in Python. The input is returned as a string, which can then be converted to any other data type as needed. For example, consider the following code:
name = input("What is your name? ")
print("Hello, " + name + "!")
When this code is run, it will prompt the user to enter their name, and then print a greeting using the input.
Output function
The print() function is used to output or display text on the screen in Python. The print() function can take multiple arguments, and it will concatenate them together and print them to the screen. For example, consider the following code:
x = 10
y = 20
print("The value of x is:", x)
print("The value of y is:", y)
When this code is run, it will print the value of x and y on the screen.
Import statement
The import statement is used to include a module or package in a Python program. For example, the math module can be imported as follows:
import math
print(math.sqrt(16))
In this example, the sqrt() function from the math module is used to calculate the square root of 16.
In this way, we can use the Input, Output, and Import statements in python.
13. Operators in Python
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand. For example: in the expression 4 + 5 = 9, 4 and 5 are the operands and + is the operator that performs the addition.
We will be discussing the different types of operators available in Python including arithmetic, comparison, logical, bitwise, assignment and special operators.
Arithmetic Operators: Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division. The following are the arithmetic operators in Python:
+
(addition)-
(subtraction)*
(multiplication)/
(division)%
(modulus)**
(exponentiation)//
(floor division)
For example:
x = 15
y = 4
print(x + y) # Output: 19
print(x - y) # Output: 11
print(x * y) # Output: 60
print(x / y) # Output: 3.75
print(x % y) # Output: 3
print(x ** y) # Output: 50625
print(x // y) # Output: 3
Comparison Operators: Comparison operators are used to compare two values and return a Boolean value indicating whether the comparison is true or false. The following are the comparison operators in Python:
==
(equal to)!=
(not equal to)>
(greater than)<
(less than)>=
(greater than or equal to)<=
(less than or equal to)
For example:
x = 5
y = 8
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: False
print(x < y) # Output: True
print(x >= y) # Output: False
print(x <= y) # Output: True
Logical Operators: Logical operators are used to combine multiple conditions and return a Boolean value indicating whether the combined conditions are true or false. The following are the logical operators in Python:
and
(True if both conditions are true)or
(True if either condition is true)not
(True if the condition is false)
For example:
x = 5
print(x > 0 and x < 10) # Output: True
print(x > 0 or x < 10) # Output: True
print(not(x > 0 and x < 10)) # Output: False
Bitwise Operators: Bitwise operators are used to perform operations on binary numbers. The following are the bitwise operators in Python:
&
(and)|
(or)^
(xor)~
(complement)​
oaicite:{"index":0,"invalid_reason":"Malformed citation <<(left shift)\n-
>>"}​
(right shift)
For example:
x = 5 # binary: 0101
y = 3 # binary: 0011
print(x & y) # Output: 1
Python Assignment Operators: In Python, assignment operators are used to assign values to variables. The basic assignment operator is the “=” operator, which assigns the value on the right side of the operator to the variable on the left side. Here are some examples of using the assignment operator:
x = 5 # assigns the value 5 to the variable x
y = x + 2 # assigns the value of x + 2 to the variable y
z = "hello" # assigns the string "hello" to the variable z
In addition to the basic assignment operator, Python also provides a number of shorthand assignment operators that allow you to perform a mathematical operation and then assign the result to a variable in a single line of code. Here are some examples of using shorthand assignment operators:
x += 2 # adds 2 to the value of x and assigns the result to x
y *= 3 # multiplies the value of y by 3 and assigns the result to y
z /= 2 # divides the value of z by 2 and assigns the result to z
Python Special Operators: In addition to the basic assignment operator and the shorthand assignment operators, Python also provides a number of special operators that perform specific operations. Here are some examples of special operators:
Identity Operators: is and is not The “is” operator is used to determine if two variables refer to the same object in memory. The “is not” operator is used to determine if two variables do not refer to the same object in memory. Here is an example of using the identity operators:
x = [1, 2, 3]
y = [1, 2, 3]
z = x print(x is y) # False print(x is z) # True
Membership Operators: in and not in The “in” operator is used to determine if an element is present in a list or a string. The “not in” operator is used to determine if an element is not present in a list or a string. Here is an example of using the membership operators:
x = [1, 2, 3]
print(1 in x) # True print(4 in x) # False
14. Python If…Else Condition
In Python, the if…else statement is used to control the flow of execution of a program based on a certain condition. The basic syntax of the if…else statement is as follows:
if condition:
# execute this block if the condition is true
else:
# execute this block if the condition is false
The condition
in the if statement can be any expression that evaluates to either True
or False
. If the condition is True
, the block of code following the if
statement will be executed. If the condition is False
, the block of code following the else
statement will be executed.
Example:
x = 5
if x > 0:
print("x is positive")
else:
print("x is negative")
# Output: x is positive
Python If Condition:
The if statement in Python is used to check whether a certain condition is true or not. If the condition is true, a block of code will be executed. If the condition is false, the block of code will be skipped.
The basic syntax of the if statement is:
if condition:
# execute this block of code
Example:
x = 5
if x > 0:
print("x is positive")
# Output: x is positive
Python Else Condition:
The else statement in Python is used to execute a block of code when the if statement condition is false. The basic syntax of the else statement is:
if condition:
# execute this block of code
else:
# execute this block of code
Example:
x = -5
if x > 0:
print("x is positive")
else:
print("x is negative")
# output: x is negative
Python Elif Condition:
The elif (short for “else if”) statement in Python is used to check multiple conditions. The basic syntax of the elif statement is:
if condition1:
# execute this block of code
elif condition2:
# execute this block of code
else:
# execute this block of code
Example:
x = 0
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
# Output: x is zero
Python Nested If statements:
In Python, it is possible to nest if statements inside another if statement. This is called a nested if statement. The basic syntax of a nested if statement is:
if condition1:
# execute this block of code
if condition2:
# execute this block of code
else:
# execute this block of code
else:
# execute this block of code
Example:
x = -5
y = 10
if x > 0:
print("x is positive")
if y > 0:
print("y is positive")
else:
print("y is negative")
else:
print("x is negative")
15. Python for Loop and while loop
A for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. The general syntax for a for loop is:
for variable in sequence:
# code to execute
For example, to print each item in a list of numbers:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# Output: 1 2 3 4 5
Looping Through a String We can also use a for loop to iterate over a string. Each time through the loop, the next character in the string will be assigned to the variable.
word = "hello"
for letter in word:
print(letter)
# Output: h e l l o
The break Statement: The break
statement is used to exit a for loop early, before it has iterated through all of the items in the sequence. For example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break
print(num)
# Output: 1 2
The continue Statement: The continue
statement is used to skip over the current item in the sequence and continue with the next item. For example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
# Output: 1 2 4 5
The range() Function: The range()
function is used to generate a sequence of numbers. The general syntax for the range()
function is:
range(start, stop, step)
For example, to generate a sequence of numbers from 1 to 5:
for num in range(1,6):
print(num)
# Output: 1 2 3 4 5
Else in For Loop: The else
clause in a for loop is executed when the loop has finished iterating through the sequence. For example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
else:
print("The loop is finished.")
# Output: 1 2 3 4 5 The loop is finished.
Nested Loops: A nested loop is a loop that is inside of another loop. For example:
for num1 in range(1,3):
for num2 in range(1,4):
print(num1, num2)
# Output: 1 1 1 2 1 3 2 1 2 2 2 3
The pass Statement: The pass
statement is used as a placeholder in Python. It does nothing when executed and is used to prevent an error if a block of code is empty. For example:
for num in range(1,6):
pass
This code will not produce any output because the block of code inside the for loop is empty and only the pass
statement is present.
In conclusion, loops are an essential part of any programming language.
16. While Loop-
A while loop in Python is used to repeatedly execute a block of code as long as a certain condition is true. The general syntax for a while loop is:
while condition:
# code to execute
For example, to print the numbers from 1 to 5:
num = 1
while num <= 5:
print(num)
num += 1
# Output: 1 2 3 4 5
It’s important to make sure that the condition will eventually be false, otherwise the loop will run forever, which is known as an infinite loop.
We can also use the break
and continue
statements inside a while loop just like in for loops. For example, to print the numbers from 1 to 5, but skip 3:
num = 1
while num <= 5:
if num == 3:
num += 1
continue
print(num)
num += 1
# Output: 1 2 4 5
In conclusion, while loops are useful when we don’t know how many times we need to iterate in advance, or when we want to keep iterating until a certain condition is met.
17. List in Python-
A list in Python is an ordered collection of items, which can be of any data type (strings, integers, etc.). The items in a list are enclosed in square brackets [], and separated by commas. For example:
fruits = ["apple", "banana", "cherry"]
List Items — Data Types A list can contain items of different data types, for example:
mixed_list = ["apple", 2, 3.14, True]
What is the data type of a list? In Python, a list is an instance of the list
class and its data type is also list
. You can use the type()
function to check the data type of a variable, for example:
fruits = ["apple", "banana", "cherry"]
print(type(fruits))
Output:
<class 'list'>
Access Items We can access the items in a list by referring to their index number. The index numbers start from 0. For example:
fruits = ["apple", "banana", "cherry"]
print(fruits[1])
Output:
banana
Change List Items We can change an item in a list by referring to its index number. For example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)
Output:
["apple", "orange", "cherry"]
Add Items List We can add an item to a list using the append()
method. For example:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
Output:
["apple", "banana", "cherry", "orange"]
List Methods
There are many built-in methods available for lists in Python, some of the most commonly used methods are:
append()
- Adds an element to the end of the list.extend()
- Adds all the elements of an iterable (list, tuple, etc.) to the end of the list.insert()
- Inserts an element at a specified position.remove()
- Removes the first occurrence of the specified element.pop()
- Removes the element at the specified position.clear()
- Removes all the elements from the list.index()
- Returns the index of the first occurrence of the specified element.count()
- Returns the number of times the specified element appears in the list.sort()
- Sorts the list in ascending order.reverse()
- Reverses the order of the list.
In conclusion, Lists are one of the most commonly used data structures in Python, they allow us to store multiple items in a single variable and perform various operations on them.
18. Tuples in Python
A tuple is a collection of ordered and immutable elements. They are similar to lists in Python, but unlike lists, tuples cannot be modified once created. This makes them useful for storing data that should not be changed, such as the coordinates of a point in a 2D space.
Creating a Tuple
Creating a tuple is simple. You can create an empty tuple by using the tuple() function with no arguments, or by using the parentheses () with no elements inside. Here’s an example of creating a tuple with some elements:
# Creating a tuple with elements
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple) # (1, 2, 3, 4, 5)
# Creating an empty tuple
my_empty_tuple = tuple()
print(my_empty_tuple) # ()
Accessing of Tuples
Accessing the elements of a tuple is similar to accessing the elements of a list. You can use the indexing operator [] to access an element of the tuple. Here’s an example:
# Accessing the first element of the tuple
first_element = my_tuple[0]
print(first_element) # 1
# Accessing the last element of the tuple
last_element = my_tuple[-1]
print(last_element) # 5
Concatenation of Tuples
You can concatenate two tuples by using the + operator. Here’s an example:
# Concatenating two tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple) # (1, 2, 3, 4, 5, 6)
Deleting a Tuple
Tuples are immutable, so you cannot delete an element from a tuple. However, you can delete the entire tuple using the del keyword. Here’s an example:
# Deleting a tuple
del my_tuple
Built-In Methods
There are a few built-in methods that you can use with tuples. For example, you can use the count() method to count the number of occurrences of a specific element in a tuple. Here’s an example:
# Counting the occurrences of an element
my_tuple = (1, 2, 3, 3, 4, 5)
count = my_tuple.count(3)
print(count) # 2
Built-In Functions
There are also a few built-in functions that you can use with tuples. For example, you can use the len() function to find the length of a tuple. Here’s an example:
# Finding the length of a tuple
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print(length) # 5
Tuples VS Lists
In Python, both tuples and lists are used to store multiple values. However, there are a few key differences between the two:
- The main difference between tuples and lists in Python is that tuples are immutable, meaning their elements cannot be modified once they are created, while lists are mutable, meaning their elements can be modified. This makes tuples useful for storing data that should not be changed, such as the coordinates of a point in a 2D space, while lists are more suitable for storing data that can be changed, such as a list of items in a shopping cart. Additionally, tuples are generally faster and use less memory than lists because they are immutable, while lists require more memory to allow for changes to be made.
- Another difference is that Tuples can be used as key in a dictionary while lists cannot be used.
- In summary, tuples are more efficient and suitable for storing data that should not be modified, while lists are more flexible and suitable for storing data that can be modified.
19. Dictionary in Python
A dictionary in Python is an unordered collection of items, where each item is a key-value pair. Dictionaries are enclosed in curly braces { } and values can be accessed by keys. They are also known as associative arrays, maps, or hash maps.
Creating a Python Dictionary
Creating a dictionary in Python is as simple as enclosing a comma-separated list of key-value pairs in curly braces. The keys must be unique, but the values do not have to be. Here is an example of creating a dictionary:
# Creating a dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
print(my_dict)
Accessing Elements from Dictionary
You can access the elements of a dictionary by referring to its key name, inside square brackets []. Here is an example of accessing a value from a dictionary:
# Accessing a value from a dictionary
name = my_dict['name']
print(name)
Changing and Adding Dictionary Elements
You can change the value of a specific item by referring to its key name. If the key is not present, a new (key: value) pair is added to the dictionary. Here is an example of changing a value in a dictionary:
# Changing a value in a dictionary
my_dict['age'] = 30
print(my_dict)
# Adding a new key-value pair to the dictionary
my_dict['gender'] = 'male'
print(my_dict)
Removing elements from Dictionary
You can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value. The popitem() method can be used to remove and return an arbitrary (key, value) item pair. The del keyword can also be used to remove individual items or the entire dictionary itself. Here is an example of removing an item from a dictionary:
# Removing an item from a dictionary
my_dict.pop('gender')
print(my_dict)
# Removing an arbitrary (key, value) pair
my_dict.popitem()
print(my_dict)# Removing the entire dictionary
del my_dict
Python List Comprehension
List comprehension is a concise and memory-efficient way to create lists in Python. It is a syntactic construct that allows you to create a new list by applying an expression to each item in an existing list, and optionally filtering the items based on a condition. Here is an example of using list comprehension to create a new list of squares:
# Using list comprehension to create a new list of squares
squares = [x**2 for x in range(10)]
print(squares)
Python Dictionary Comprehension
Dictionary comprehension is a concise and memory-efficient way to create dictionaries in Python. It is similar to list comprehension but with a key-value pair format. Here is an example of using dictionary comprehension to create a new dictionary of squares:
# Using dictionary comprehension to create a new dictionary of squares
squares_dict = {x: x**2 for x in range(10)}
print(squares_dict)
20. Sets in Python
A set in Python is an unordered collection of unique items. Sets are enclosed in curly braces {} or the set() function, and items in a set must be unique. Sets are often used to remove duplicates from a list or to perform mathematical set operations like union and intersection.
Creating Python Sets
Creating a set in Python is as simple as enclosing a comma-separated list of items in curly braces {} or using the set() function. Here is an example of creating a set:
# Creating a set with curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set)
# Creating a set with the set() function
my_set = set([1, 2, 3, 4, 5])
print(my_set)
Other Python Set Methods
There are several built-in methods that can be used to perform operations on sets, such as adding or removing items, performing set operations, and others. Here are some examples of commonly used set methods:
- add() — adds an element to the set
my_set.add(6)
print(my_set)
- remove() — removes an element from the set, raises an error if the element is not present
my_set.remove(6)
print(my_set)
- union() — returns a set containing all items from both sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1.union(set2)
print(set3)
- intersection() — returns a set containing only items that exist in both sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1.intersection(set2)
print(set3)
- difference() — returns a set containing items that exist only in the first set, and not in the second set
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1.difference(set2)
print(set3)
- clear() — removes all items from the set
my_set.clear()
print(my_set)
In summary, sets are an extremely useful data structure in Python, allowing you to store unique items and perform set operations quickly and efficiently. The built-in set methods make it easy to add, remove, and manipulate items in a set.
21. Python Functions
Functions are a fundamental building block in Python, allowing you to group together a block of code and execute it multiple times. Functions can take in parameters, perform a set of operations, and return a value.
Creating a Function
def my_function(param1, param2):
# function code here
return result
Calling a Function
result = my_function(arg1, arg2)
Arguments
When calling a function, the values passed in are known as arguments. These values are passed to the function, where they can be used in the function’s code.
def my_function(param1, param2):
# function code here
return result
result = my_function(arg1, arg2)
Parameters vs Arguments
A function’s parameters are the variables defined in the function definition, while the arguments are the values passed in when the function is called.
Arbitrary Arguments, *args
In some cases, you may not know how many arguments a function will be passed. Python allows you to handle this situation using the *args syntax. *args allows you to pass a variable number of arguments to a function.
def my_function(*args):
for arg in args:
print(arg)
my_function(1, 2, 3, 4, 5)
Keyword Arguments
You can also pass arguments to a function using keyword arguments. This allows you to explicitly specify the parameter name for each argument.
def my_function(param1, param2):
print(param1, param2)
my_function(param2=2, param1=1)
Arbitrary Keyword Arguments, **kwargs
Just like *args, Python also allows you to handle a variable number of keyword arguments using the **kwargs syntax.
def my_function(**kwargs):
for key, value in kwargs.items():
print(key, value)
my_function(param1=1, param2=2, param3=3)
Default Parameter Value
You can give a default value to a parameter in a function, if the caller of the function does not pass a value for that parameter, the default value will be used.
def my_function(param1, param2 = "default_value"):
print(param1, param2)
my_function(1)
In summary, functions are a powerful feature in Python, allowing you to group together and reuse code. You can define functions with parameters and default values, and pass in arguments using various techniques such as *args and **kwargs. The ability to pass and handle variable numbers of arguments and keyword arguments can make your functions more flexible and useful.
Recursion
Recursion is a technique in computer science where a function calls itself. It can be a powerful tool to solve problems and simplify code, but it’s important to use it judiciously, as it can also lead to infinite loops and stack overflow errors if not used correctly.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
In the above example, the function factorial is defined to take in an integer n, and it returns the factorial of that integer. The function calls itself with the argument n-1 until the base case (n==0) is reached, and then it returns the factorial.
Python Lambda / Anonymous Function
A lambda function is a small anonymous function, it can have any number of arguments but only one expression. The lambda function can be used wherever a function object is required.
double = lambda x: x * 2
print(double(5))
In the above example, we define a lambda function double, which takes in a single argument x and returns its value multiplied by 2.
Why Use Lambda Functions?
Lambda functions are useful in situations where you need a small function to be used only once. They are commonly used in places where a function is required as an argument, such as the sorted()
and filter()
built-in functions.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
In this example, we use a lambda function to filter a list of numbers, returning only the even numbers.
Lambda functions are also useful when defining short, throwaway functions, such as when working with data inside list comprehensions.
squared = [x**2 for x in range(5)]
In this example, the lambda function is used to raise the number to the power of 2, it’s used only once and only for that list comprehension.
In conclusion, lambda functions can be useful in situations where you need a small, throwaway function, or when you need to pass a function as an argument to another function. They’re concise, easy to read and can make your code more readable and elegant.
22. Python Global, Local and Nonlocal variables
In Python, variables can be classified into three categories: global, local, and nonlocal. Understanding the differences between these types of variables is important for writing efficient and maintainable code.
Global Variables
A global variable is a variable that is defined outside of any function or class, and it can be accessed and modified from anywhere in the code. Global variables are typically used to store data that needs to be shared between different parts of the program.
x = 5 # global variable
def my_function():
print(x) # can access x from within the function
my_function()
In the above example, x
is a global variable that is defined outside of any function. The function my_function
can access and print the value of x
.
Local Variables
A local variable is a variable that is defined within a function, and it can only be accessed within that function. Local variables are typically used to store temporary data that is only needed for the duration of the function call.
def my_function():
x = 5 # local variable
print(x)
my_function()
print(x) # will raise an error, x is not defined outside of the function
In this example, x
is a local variable that is defined within the function my_function
. The function can access and print the value of x
, but trying to access x
outside of the function will raise an error.
Nonlocal Variables
A nonlocal variable is a variable that is defined in an outer scope, but is not global. Nonlocal variables are typically used when a function needs to modify a variable that is defined in an outer scope.
x = 5 # global variable
def outer_function():
x = 10 # nonlocal variable
def inner_function():
nonlocal x
x += 5
print(x)
inner_function()
outer_function()
print(x)
In this example, x
is defined as a global variable with the value of 5. In the outer_function x
is defined as a nonlocal variable with the value of 10, and inner_function modifies the value of x
by adding 5. Finally, when we print x
outside of the functions it will return the value of 15
.
In conclusion, understanding the difference between global, local, and nonlocal variables is important for writing efficient and maintainable code. Knowing when to use each type of variable can help you write code that is easy to understand and debug.
23. Python Modules vs Package vs Libraries vs Frameworks
When working with Python, it’s important to understand the differences between modules, packages, libraries, and frameworks. These concepts are closely related, but they have distinct characteristics that set them apart.
Python Modules
A Python module is a single file that contains Python code. This code can include variables, functions, and classes. Modules are used to organize and reuse code, making it easy to share functionality between different parts of your program.
# mymodule.py
def my_function():
print("Hello, World!")
import mymodule
mymodule.my_function() # prints "Hello, World!"
In this example, mymodule.py
is a module that contains a single function called my_function
. The import
statement is used to make this function available in the current script. By importing mymodule
, we are able to call my_function()
and print "Hello, World!".
Python Package
A Python package is a collection of modules that are organized in a directory hierarchy. Packages are used to organize related modules, making it easy to manage and share functionality.
mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
In this example, mypackage
is a package that contains three modules: module1.py
, module2.py
, and module3.py
which is in the subpackage. The __init__.py
files are used to mark the directories as packages, and they can contain initialization code.
Python Libraries
A Python library is a collection of pre-written code that can be used to perform common tasks. Libraries are typically used to provide functionality that is not included in the Python standard library. For example, the NumPy library provides support for numerical computing, while the Pandas library provides support for data manipulation and analysis.
import numpy as np
x = np.array([1, 2, 3])
print(x) # prints "[1 2 3]"
In this example, we are using the NumPy library to create an array of numbers. The import
statement is used to make the NumPy library available in the current script, and the as
keyword is used to give the library a shorter name (np
) for convenience.
Python Frameworks
A Python framework is a collection of libraries and modules that are organized in a specific way to provide a structure for building web applications. Frameworks provide a set of conventions and best practices for building web applications, making it easier to create consistent and maintainable code. Examples of popular Python web frameworks include Django and Flask.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
In this example, we are using the Flask framework to build a simple web application. The Flask
class is imported from the flask
module, and an instance of the class is created. The route
decorator is used to define a function that will handle requests to the root URL of the application.
In summary, modules, packages, libraries, and frameworks are all important concepts in Python programming. Modules are single files that contain Python code, packages are collections of modules organized in a directory hierarchy, libraries are pre-written code that can be used to perform common tasks, and frameworks are collections of libraries and modules that provide a structure for building web applications. Understanding the differences between these concepts can help you write more organized, maintainable, and reusable code in Python.
24. Python Objects and Classes
Python is an object-oriented programming language, which means that it allows developers to create and manipulate objects that have certain characteristics and behaviors. These characteristics and behaviors are defined by classes, which act as templates for creating objects.
Creating a class in Python is done using the class
keyword, followed by the name of the class and a colon. Within the class, you can define attributes (variables) and methods (functions) that will be available to all objects created from that class. For example:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def start(self):
print(f"The {self.make} {self.model} is starting.")
Creating an object from a class is called instantiation, and is done using the class name followed by parentheses. For example:
my_car = Car("Toyota", "Camry")
Class attributes are variables that are shared among all instances of a class, while instance attributes are specific to a single instance of a class. For example, in the Car class above, make
and model
are instance attributes, while the start
method is an instance method.
Constructors are special methods that are called when an object is created. The __init__
method is a constructor in Python.
Deleting attributes or objects can be done using the del
keyword. For example, if you want to delete the make
attribute from the my_car
object, you would use the following:
del my_car.make
Instance Methods: In addition to instance methods, Python also supports class methods and static methods. A class method is a method that is bound to the class and not the instance of the object. It is defined using the @classmethod
decorator. A static method is a method that belongs to a class rather than an instance of the class. It is defined using the @staticmethod
decorator.
In summary, classes in Python allow developers to create objects with specific characteristics and behaviors. These objects can have attributes and methods that can be manipulated and used to perform tasks. Understanding the concepts of class attributes, instance attributes, constructors, and methods is crucial for effective object-oriented programming in Python.
25. Object-oriented programming (OOP)
Object-oriented programming (OOP) is a programming paradigm that is based on the concept of objects, which are instances of classes that have certain characteristics and behaviors. Python is a fully object-oriented programming language, which means that it supports all the major features of OOP, such as inheritance, polymorphism, encapsulation, and data abstraction.
In this blog post, we will be exploring the fundamentals of OOP in Python, and how to use these concepts in your own code. We’ll start by discussing what OOP is and the major benefits of using it, and then move on to the specific concepts of inheritance, polymorphism, encapsulation, and data abstraction.
What is OOPS in Python?
OOP is a programming paradigm that is based on the concept of objects, which are instances of classes that have certain characteristics and behaviors. In Python, classes are defined using the class keyword, and objects are created by calling the class like a function.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
dog1 = Dog("Fido", "Golden Retriever")
print(dog1.name) # Output: "Fido"
print(dog1.breed) # Output: "Golden Retriever"
Some Major Benefits of OOPS Include
- Reusability: Classes can be reused to create multiple objects, reducing the amount of code that needs to be written.
- Modularity: Classes can be split into separate files, making it easier to manage and maintain large projects.
- Abstraction: Classes can be used to hide the complexity of the underlying code, making it easier to understand and use.
- Inheritance: Classes can be designed to inherit characteristics and behaviors from other classes, reducing the amount of code that needs to be written.
- Polymorphism: Classes can be used to create objects with similar characteristics and behaviors, but with different implementations.
Difference Between Object Oriented & Procedural Oriented Programming
Object-oriented programming and procedural programming are two different programming paradigms. The main difference between them is that object-oriented programming is based on the concept of objects, while procedural programming is based on the concept of procedures.
OOP follows bottom-up approach, which means that it focuses on the objects and their interactions first, while procedural programming follows top-down approach, which means that it focuses on the overall problem first.
Fundamentals of OOPS in Python
Inheritance: Inheritance is the mechanism by which one class can inherit the characteristics and behaviors of another class. This allows you to create a new class that is a modified version of an existing class.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
dog1 = Dog("Fido", "Golden Retriever")
print(dog1.name) # Output: "Fido"
print(dog1.breed) # Output: "Golden Retriever"
Super() in Python
The super() function is used to call a method from the parent class. This is often used in the constructor of a subclass to call the constructor of the parent class.
Hybrid Inheritance: in Python Hybrid Inheritance is a combination of both single and multiple inheritance. It is a powerful feature of object-oriented programming (OOP) that allows a derived class to inherit from more than one base class. This is achieved by combining the properties of both single and multiple inheritance.
An example of hybrid inheritance in Python is shown below:
class A:
def displayA(self):
print("This is class A")
class B:
def displayB(self):
print("This is class B")
class C(A, B):
def displayC(self):
print("This is class C")
c_obj = C()
c_obj.displayA()
c_obj.displayB()
c_obj.displayC()
Output:
This is class A
This is class B
This is class C
In this example, class C is inheriting from both class A and class B. This allows it to access the methods and properties of both classes.
Polymorphism in Python Polymorphism is a feature of OOP that allows objects of different classes to be treated as objects of a common base class. This means that a single method or operator can perform different actions depending on the type of object it is applied to.
An example of polymorphism in Python is shown below:
class A:
def display(self):
print("This is class A")
class B:
def display(self):
print("This is class B")
a_obj = A()
b_obj = B()
for obj in (a_obj, b_obj):
obj.display()
Output:
This is class A
This is class B
In this example, both class A and class B have a method called “display”. When the for loop iterates through the objects, it calls the “display” method on each object. Since the “display” method is defined differently for each class, the output is different for each iteration.
Polymorphism with Class Methods in Python Class methods are methods that are bound to a class and not the instance of the object. They can be called on the class itself, rather than an instance of the class.
An example of polymorphism with class methods in Python is shown below:
class A:
@classmethod
def display(cls):
print(f"This is class {cls.__name__}")
class B:
@classmethod
def display(cls):
print(f"This is class {cls.__name__}")
A.display()
B.display()
Output:
This is class A
This is class B
In this example, both class A and class B have a class method called “display”. When the class methods are called, it calls the “display” method on each class. Since the “display” method is defined differently for each class, the output is different for each class.
Encapsulation in Python Encapsulation is a feature of object-oriented programming (OOP) that allows the implementation details of a class to be hidden from the outside world. This is achieved by using access modifiers, such as private and protected, to control access to the class’s methods and properties. Encapsulation ensures that the internal state of an object is protected from unauthorized access and modification.
An example of encapsulation in Python is shown below:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def set_balance(self, amount):
if amount < 0:
print("Invalid amount")
else:
self.__balance = amount
account = BankAccount(1000)
print(account.get_balance())
account.set_balance(500)
print(account.get_balance())
Output:
1000
500
In this example, the class BankAccount has a private variable called __balance, which is used to store the balance of the account. The get_balance and set_balance methods are used to access and modify the balance. The set_balance method also includes a validation check to ensure that the amount passed is not negative. By using encapsulation, we have protected the internal state of the object from unauthorized access and modification.
Getters and Setters in Python Getters and setters are methods used to access and modify the values of private variables. These methods are used to implement encapsulation in OOP.
An example of getters and setters in Python is shown below:
class Employee:
def __init__(self, name, salary):
self.__name = name
self.__salary = salary
def get_name(self):
return self.__name
def get_salary(self):
return self.__salary
def set_salary(self, amount):
if amount < 0:
print("Invalid amount")
else:
self.__salary = amount
employee = Employee("John Doe", 5000)
print(employee.get_name())
print(employee.get_salary())
employee.set_salary(6000)
print(employee.get_salary())
Output:
John Doe
5000
6000
In this example, the class Employee has a private variable called __name and __salary, which are used to store the name and salary of the employee. The get_name and get_salary methods are used to access the name and salary of the employee. The set_salary method is used to modify the salary of the employee. By using getters and setters, we have protected the internal state of the object from unauthorized access and modification.
Access Modifiers in Python Access modifiers are used to control access to the methods and properties of a class. Python supports three types of access modifiers: public, private, and protected.
- Public methods and properties can be accessed from anywhere.
- Private methods and properties can be accessed only within the class. They are denoted by a double underscore prefix (__).
- Protected methods and properties can be accessed within the class and its subclasses. They are denoted by a single underscore prefix (_).
An example of using access modifiers (public, private, and protected) in Python is shown below:
class MyClass:
def __init__(self):
self.public_var = "I am a public variable"
self.__private_var = "I am a private variable"
self._protected_var = "I am a protected variable"
def public_method(self):
print("I am a public method")
def __private_method(self):
print("I am a private method")
def _protected_method(self):
print("I am a protected method")
obj = MyClass()
# Accessing public variable
print(obj.public_var) # Output: I am a public variable
# Accessing private variable
# This will raise an AttributeError
print(obj.__private_var)
# Accessing protected variable
print(obj._protected_var) # Output: I am a protected variable
# Accessing public method
obj.public_method() # Output: I am a public method
# Accessing private method
# This will raise an AttributeError
obj.__private_method()
# Accessing protected method
obj._protected_method() # Output: I am a protected method
In this example, the class MyClass has public, private and protected variables and methods. Public variables and methods can be accessed from anywhere, private variables and methods can only be accessed within the class and protected variables and methods can be accessed within the class and its subclasses.
It’s worth noting that, in python, the naming convention of using double underscore prefix (__) is used to indicate to the developer that the variable/method is intended to be private but it doesn’t make it truly private, it’s just a naming convention and can be accessed using the _classname__variablename.
Data abstraction is a concept in object-oriented programming that refers to the practice of hiding the implementation details of a class from the user and only exposing the necessary information. The idea is to create a simplified version of the class that is easy to understand and use. This is accomplished by using abstract classes and interfaces.
For example, consider a class that represents a bank account. The user does not need to know the details of how the account balance is stored or how transactions are processed. Instead, the user only needs to know how to deposit money, withdraw money, and check the balance. These methods can be made available to the user while the implementation details of the class are hidden.
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if self.__balance >= amount:
self.__balance -= amount
else:
print("Insufficient funds")
def check_balance(self):
return self.__balance
In this example, the implementation details of the class BankAccount
such as the variable __balance
is hidden from the user and the user can only access the methods deposit()
, withdraw()
and check_balance()
which expose only the necessary information to the user.
Advantages of OOPS in Python:
- OOP in Python allows for the creation of reusable and modular code.
- OOP allows for the encapsulation of data, making it easier to protect the data from outside access and modification.
- OOP allows for the creation of complex and large software systems in a manageable way.
- OOP in Python allows for easy and efficient code maintenance.
- OOP allows for the creation of real-world models in code, making it easier to understand and relate to the problem being solved.
- The use of inheritance and polymorphism in OOP allows for code to be reused and extended in a logical way.
- OOP allows for the design of code that is easy to test and debug.
Overall, OOP in Python provides a powerful and flexible approach to software development that allows for the creation of efficient, reusable, and maintainable code.
26. Python Exception Handling
Python exception handling is a mechanism to handle run-time errors that occur during the execution of a program. Exception handling allows the program to continue to run even if an error occurs, instead of abruptly halting and exiting.
The basic syntax of exception handling in Python is the try-except block. The code that could potentially raise an exception is placed in the try block, and the code to handle the exception is placed in the except block. The finally block, if present, is executed regardless of whether an exception occurred.
try:
# code that could raise an exception
x = 5 / 0
except ZeroDivisionError:
# code to handle the exception
print("division by zero!")
In this example, the try block contains the code that raises an exception (division by zero), and the except block contains the code to handle the exception (printing an error message).
You can also catch multiple exception in a single except block by providing a tuple of exception types.
try:
# code that could raise an exception
x = int("abc")
except (ZeroDivisionError, ValueError):
# code to handle the exception
print("division by zero or invalid input!")
You can also use the try-with-else clause. The else block will be executed if no exception is raised in the try block.
try:
# code that could raise an exception
x = 5 / 2
except ZeroDivisionError:
# code to handle the exception
print("division by zero!")
else:
print("no exception occured")
Catching exceptions in Python can help you handle run-time errors in your code, allowing your program to continue running even if an error occurs. Try-except blocks, multiple exception handling and try-with-else clauses provide flexibility and control over how your program responds to exceptions, making it easier to write robust and reliable code.
27. Python Custom Exceptions
Customizing exception classes in Python allows you to create your own exception types that can be used to handle specific errors in your code. This allows for more fine-grained control over how your program responds to exceptions, and makes it easier to understand the cause of an error.
To create a custom exception class, you need to create a new class that inherits from the built-in Exception
class. You can then add any additional methods or properties that you need.
class MyException(Exception):
def __init__(self, message):
self.message = message
try:
raise MyException("An error has occurred.")
except MyException as e:
print(e.message)
In this example, we have created a custom exception class MyException
that takes a message as an argument. We raise an instance of this exception in the try block, and catch it in the except block. The message property of the exception can then be accessed and printed.
You can also customize the behavior of your exception class by overloading the built-in methods of the Exception
class, such as the __str__
method, which is used to return a string representation of the exception.
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
try:
raise MyException("An error has occurred.")
except MyException as e:
print(e)
In this example, the __str__
method is overloaded and returns the message property of the exception, so when we print the exception object, it will print the message,
Customizing exception classes in Python allows you to create specific exception types that are tailored to the needs of your program. This can make it easier to understand the cause of an error, and provide more control over how your program responds to exceptions.
28. File Handling in Python
File handling is an important aspect of programming and is a common task for developers. Python provides several built-in functions and classes for handling files and directories. In this blog post, we will discuss the basics of file handling in Python and provide an example of how to read and write to a file.
The first step in file handling is to open a file. The built-in open()
function is used for this purpose. The function takes two arguments: the file name and the mode in which the file should be opened. The mode can be 'r' for reading, 'w' for writing, 'a' for appending, and 'b' for binary mode.
# Open a file for reading
file = open("example.txt", "r")
Once the file is open, you can read its contents using the read()
function. This function takes an optional argument that specifies the number of bytes to be read. If no argument is provided, the entire file will be read.
# Read the entire file
file_contents = file.read()
print(file_contents)
You can also read the file line by line using the readline()
function. This function reads a single line from the file and returns it as a string. To read all the lines in the file, you can use a for loop.
# Read the file line by line
for line in file:
print(line)
To write to a file, you need to open the file in write mode. The write()
function is used to write to the file.
# Open a file for writing
file = open("example.txt", "w")
file.write("Hello, world!")
When you are done with the file, it is important to close it. This can be done using the close()
function.
# Close the file
file.close()
Another way to handle file is using with open
statement. It is a good practice to use it as it automatically handles the closing of file after the block is executed.
with open("example.txt", "r") as file:
file_contents = file.read()
print(file_contents)
In this way, you don’t have to explicitly close the file as it automatically closed after the block is executed.
In conclusion, file handling in Python is simple and easy to use. The built-in open()
function and related functions make it easy to read from and write to files. By using the with open
statement, you can ensure that your files are properly closed and resources are freed up when you are done with them.
29. Python Iterators
Iterators are objects that can be iterated (looped) upon. They represent a stream of data. In Python, an iterator is an object that implements two methods, iter() and next().
The iter() method returns the iterator object itself. The next() method returns the next value from the iterator. If there are no more items to return, it should raise StopIteration.
Here is an example of creating an iterator in Python:
class MyIterator:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.start >= self.end:
raise StopIteration
current = self.start
self.start += 1
return current
it = MyIterator(1, 10)
for i in it:
print(i)
30. Python Generators
A generator is a special type of iterator, which is a simpler and more memory-efficient way of creating iterators. A generator is defined as a function that uses the yield statement to return a value, rather than returning the value directly. When the generator function is called, it returns a generator object, but it does not start executing the function. The execution starts only when the next() method is called on the generator object.
Here is an example of a generator function in Python:
def my_range(start, end):
current = start
while current < end:
yield current
current += 1
gen = my_range(1, 10)
for i in gen:
print(i)
31. Python Closures
A closure is a function object that remembers values in the enclosing scope even if they are not present in memory. It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.
Here is an example of a closure in Python:
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
closure = outer_function(10)
print(closure(5)) # Output: 15
32. Python Decorator
A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. Decorators are defined as a callable function that takes a function as an argument and returns a new function.
Here is an example of a decorator in Python:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
def say_whee():
print("Whee!")
say_whee = my_decorator(say_whee)
say_whee()
Python programming provides us with a built-in @property decorator which makes usage of getter and setters much easier in Object-Oriented Programming.
Class Without Getters and Setters
# Class Without Getters and Setters
class Celsius:
def __init__(self, temperature=0):
self.temperature = temperature
def to_fahrenheit(self):
return (self.temperature * 1.8) + 32
# Create a new object
human = Celsius()
# Set the temperature
human.temperature = 37
# Get the temperature attribute
print(human.temperature)
# Get the to_fahrenheit method
print(human.to_fahrenheit())
Output-
37
98.60000000000001
Using Getters and Setters
# Making Getters and Setter methods
class Celsius:
def __init__(self, temperature=0):
self.set_temperature(temperature)
def to_fahrenheit(self):
return (self.get_temperature() * 1.8) + 32
# getter method
def get_temperature(self):
return self._temperature
# setter method
def set_temperature(self, value):
if value < -273.15:
raise ValueError("Temperature below -273.15 is not possible.")
self._temperature = value
# Create a new object, set_temperature() internally called by __init__
human = Celsius(37)
# Get the temperature attribute via a getter
print(human.get_temperature())
# Get the to_fahrenheit method, get_temperature() called by the method itself
print(human.to_fahrenheit())
# new constraint implementation
human.set_temperature(-300)
# Get the to_fahreheit method
print(human.to_fahrenheit())
Output-
Traceback (most recent call last):
File "D:\Projects\tutorial\welcome\__init__.py", line 30, in <module>
human.set_temperature(-300)
File "D:\Projects\tutorial\welcome\__init__.py", line 16, in set_temperature
raise ValueError("Temperature below -273.15 is not possible.")
ValueError: Temperature below -273.15 is not possible.
37
98.60000000000001
33. The property Class
Python’s property() is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property() is a built-in function, you can use it without importing anything.
Example-
# using property class
class Celsius:
def __init__(self, temperature=0):
self.temperature = temperature
def to_fahrenheit(self):
return (self.temperature * 1.8) + 32
# getter
def get_temperature(self):
print("Getting value...")
return self._temperature
# setter
def set_temperature(self, value):
print("Setting value...")
if value < -273.15:
raise ValueError("Temperature below -273.15 is not possible")
self._temperature = value
# creating a property object
temperature = property(get_temperature, set_temperature)
human = Celsius(37)
print(human.temperature)
print(human.to_fahrenheit())
human.temperature = -300
Output-
Traceback (most recent call last):
File "D:\Projects\tutorial\welcome\__init__.py", line 30, in <module>
human.set_temperature(-300)
File "D:\Projects\tutorial\welcome\__init__.py", line 16, in set_temperature
raise ValueError("Temperature below -273.15 is not possible.")
ValueError: Temperature below -273.15 is not possible.
37
98.60000000000001
34. Python datetime Module
Python’s datetime
module provides a set of classes for manipulating dates and times. These classes include date
, time
, datetime
, timedelta
, and tzinfo
, each of which offers a different level of date and time information.
Here is an example of using the datetime
class to create a date object representing today's date:
from datetime import datetime
today = datetime.now()
print(today)
This will output something like:
2022-10-28 12:34:56.789012
You can also create a datetime
object by specifying the year, month, and day:
birthday = datetime(1997, 7, 15)
print(birthday)
This will output:
1997-07-15 00:00:00
The datetime
class also includes methods for working with dates and times. For example, you can use the strftime()
method to format a datetime
object as a string:
formatted_birthday = birthday.strftime("%B %d, %Y")
print(formatted_birthday)
This will output:
July 15, 1997
The timedelta
class is used to represent a duration of time, and can be used to perform arithmetic with datetime
objects:
from datetime import timedelta
ten_days_later = today + timedelta(days=10)
print(ten_days_later)
This will output something like:
2022-11-07 12:34:56.789012
The datetime
module also includes support for time zones through the pytz
library, which can be used to create tzinfo
objects for different time zones.
More Examples-
import datetime
from datetime import time
# date and time
datetime_object = datetime.datetime.now()
print(datetime_object)
# today’s date
date_object = datetime.date.today()
print(date_object)
# create custom date
d = datetime.date(2019, 4, 13)
print(d)
# date object of today's date
today = datetime.date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(11, 34, 56)
print("b =", b)
# time(hour, minute and second)
c = time(hour = 11, minute = 34, second = 56)
print("c =", c)
# time(hour, minute, second, microsecond)
d = time(11, 34, 56, 234566)
print("d =", d)
Output-
2022-11-04 13:14:15.291401
2022-11-04
2019-04-13
Current year: 2022
Current month: 11
Current day: 4
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566
In summary, the datetime
module provides a powerful set of classes for working with dates and times in Python. Whether you need to create date objects, perform arithmetic with dates, or format dates as strings, the datetime
module has you covered.
35. What Next?
Now you know basic and advance concept of python. Now, I would like to recommended you please follow below suggestion-
Create programs for each and every topic till now.
Solve some of the interview programs, you can get basic / advance question from websites like hacker rank, geeks for geeks etc.
What should I learn next?
Now, you need to decide what you want to do next. You need to figure out what you want to become in your life, accordingly you can choose Python framework.
Read some cool stuff-
https://medium.com/@dipeshpal17/
You must learn atleast on Database Management Software & Tools-
Relational databases any one of them-
- PostgreSQL
- MySQL
- SQLite
If you want to be Machine Learning / Data Scientist / AI-ML Engineer-
- Python
- Machine Learning Course Theory (https://www.coursera.org/learn/machine-learning)
- Machine Learning Frameworks
- Numpy
- Pandas
- scikit-learn
- Tensorflow Keras
- Transformers
- NLTK
- Spacy
- Learn Matplotlib
- Build Project with your own ideas
- Keep Learning
If you want to be fullstack python developer-
- Web Frameworks
- FastAPI / Django / Flask
- Jinja2
- HTML
- CSS and Bootstrap
- Responsive Design
- Task queues
- Celery
- Redis Queue (RQ)
- Networking
- HTTPS
- WebSockets
- WebRTC
- Web APIs
- Microservices
- Webhooks
- Bots
- API integration
- Twilio
- Stripe
- Keep Learning
36. About Author
Data Scientist with 4 years of experience in building data-intensive applications, overcoming complex architectural, and scalability issues in diverse industries. Proficient in predictive modeling, data processing, as well as scripting languages, including Python. Capable of creating, developing, testing, and deploying highly adaptive diverse services to translate business and functional qualifications into substantial deliverables.
You can read more about me here: http://dipeshpal.in
Thanks me: https://www.youtube.com/techportofficial
Buy me a coffee: https://www.buymeacoffee.com/dipeshpal
Contact-