Python lessons with example tutorials cover all the basic and intermediate concepts of Python 3 programming. All Python lessons and tutorials in this free programming course are explained with detailed code and example.
Python lesson: How to write a comment in Python
Use a hash character # at the beginning of the text to write a comment in Python. Hash works with a single line, use # on the next line to comment again.
Code:
# I am just a comment # Begin with # to write a comment # It is so easy to write a comment in Python
Output:
Python lesson: Datatypes and Variables in Python
In this lesson, we will learn about:
- Why we need data types
- How data is stored in the Program
- Different data types that are available in Python
- Rules for declaring a variable in Python
- How to define the variables of different data types in Python.
- How to assign values to multiple variables in one line
Why we need data types
The two major components of any programming code are Program logic and Data. We execute program logic to process input data to get the desired output.
To process the input data, we need to store the data. Data types help to set the boundary for the data being stored, it helps to differentiate raw data by classifying them into different types. It would make the life of a programmer easier if one knows the nature/format of data in prior. Based on the nature or type of data we design our program logic. In short, it is hard to imagine any program without data types.
How data is stored in the Program
Data is stored using variables in Python. We define variables based on the type of data we want to use for our program logic.
Data Types available in Python
Python programming language offers various built-in data types. Given below is the list of available data types with the category.
| Data type Category | Data Type |
|---|---|
| Text Type | str |
| Numeric Types | int, float, complex |
| Sequence Types | list, tuple, range |
| Mapping Type | dict |
| Set Types | set, frozenset |
| Boolean Type | bool |
| Binary Types | bytes, bytearray, memoryview |
Rules for declaring a variable in Python
- A variable name in Python can only begin with an underscore or a letter. You cannot begin the variable name with a number.
- A variable name should only contain alphanumeric characters and underscores. (a-z, A-Z, 0-9, _ )
- Variable names are Case-sensitive. City, city, CITY are three different variables.
Define the variables of different data types in Python.
A variable in python is defined or set when you assign a value to the variable. Like in other programming languages such as C or C++ we do not need to declare the variable in Python.
The Python code given below shows how to set the variable for different data types.
Code:
# Set String value (str data type) to a variable
a_str = "I am a string data type value"
print(a_str)
# Set Integer value (int data type) to a variable
a_int = 41
print(a_int)
# Set Float value (float data type) to a variable
a_float = 53.5
print(a_float)
# Set Complex value (complex data type) to a variable
a_complex = 5j
print(a_complex)
# Set List value (list data type) to a variable
a_list = ["Asia", "America", "Africa"]
print(a_list)
# Set Tuple value (tuple data type) to a variable
a_tuple = ("Asia", "America", "Africa")
print(a_tuple)
# Set Range value (Range data type) to a variable
a_range = range(11)
print(a_range)
# Set Dictionary value (dict data type) to a variable
a_dict = {"Employee_id": 70923, "Employee_name": "Jonathan"}
print(a_dict)
# Set SET value (set data type) to a variable
a_set = {"Asia", "America", "Africa"}
print(a_set)
# Set frozenset value (frozenset data type) to a variable
a_frozenset = frozenset({"Asia", "America", "Africa"})
print(a_frozenset)
# Set Boolean value (bool data type) to a variable
a_bool = True
print(a_bool)
# Set Bytes value (bytes data type) to a variable
a_bytes = b"Hello"
print(a_bytes)
# Set Bytearray value (bytearray data type) to a variable
a_bytearray = bytearray(5)
print(a_bytearray)
# Set memoryview value (memoryview data type) to a variable
a_memoryview = memoryview(bytes(5))
print(a_memoryview)
# Use type() function to return class type of the argument(object) passed as parameter.
print(type(a_str))
print(type(a_int))
print(type(a_float))
print(type(a_complex))
print(type(a_list))
print(type(a_tuple))
print(type(a_range))
print(type(a_dict))
print(type(a_set))
print(type(a_frozenset))
print(type(a_bool))
print(type(a_bytes))
print(type(a_bytearray))
print(type(a_memoryview))
Output:
I am a string data type value
41
53.5
5j
['Asia', 'America', 'Africa']
('Asia', 'America', 'Africa')
range(0, 11)
{'Employee_id': 70923, 'Employee_name': 'Jonathan'}
{'Africa', 'America', 'Asia'}
frozenset({'Africa', 'America', 'Asia'})
True
b'Hello'
bytearray(b'\x00\x00\x00\x00\x00')
<memory at 0x00000271C43CDD08>
<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>
Assign values to multiple variables in one line
Like other programming languages, Python also provides the feature to set values to multiple variables in a single line.
Code:
# Assigning Multiple values to Multiple Variables in single line a_continent, b_continent, c_continent = "Asia", "America", "Africa" print(a_continent) print(b_continent) print(c_continent) # You can also assign same value to multiple variables in single line a_continent = b_continent = c_continent = "Asia" print(a_continent, b_continent, c_continent)
Output:
Asia America Africa Asia Asia Asia
Python lesson: Typecasting in Python
In this lesson, we will learn about
- What do you mean by Type Casting
- Why do we need Type Casting
- How to perform Type Casting in Python
- Type Conversion available in Python (with example codes)
What do you mean by Type Casting
Typecast is used in a program to cast the data type/value from one data type to another. For example, there is a float data and you want to convert it into an integer data value.
Why do we need Type Casting
-
Sometimes we purposely need to round off float data to get the required integer value. Then type casting float to int will be required.
-
Also, when we are not sure about the input data, we forcefully use the typecast in that case.
In Python 3 the default data type of input value is a string (str). For example please go through the mentioned code and output given below:
Note: We are purposely using the input() function in the given code. We will explain the input() function in greater detail in the upcoming section. Please bear with us.
In the given code we should see, what would be the consequence, if we are not using the required typecast.
Code: When Typecast is not used
# File name: type_cast_not_used.py a = input() b = a + 3 print(b)
Output:
3 Traceback (most recent call last): File "type_cast_not_used.py", line 2, in <module> b = a + 3 TypeError: can only concatenate str (not "int") to str
Explanation:
When you execute the above python script and entered 3 as input. Now we assume that a+3 will be calculated as 3 + 3 and print will return 6. But, it is not the case as input value will be treated as string type and string can only concatenate string type. Thus, TypeError will be returned.
Code: When Typecast is used
a = int(input()) b = a + 3 print(b)
Output:
3 6
Explanation:
When you execute the above python script and enter 3 as input. Sring type will be converted to int data type because we have used the int typecast in front of input() function. Thus, a variable will contain integer value and, b will perform the calculation correctly. The final output will be 6.
Type Conversion available in Python (with example codes)
Available Type Conversions
| Typecast | Function |
|---|---|
| int(a, base) | Converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string. |
| float() | Convert any data type to a floating-point number type. |
| ord() | Convert a character data type to an integer type. |
| hex() | Convert an integer data type to a hexadecimal string type. |
| oct() | Convert an integer data type to an octal string type. |
| tuple() | Convert to a tuple data type. |
| set() | Returns the type after converting to set. |
| list() | Convert any data type to a list data type. |
| dict() | Convert a tuple of order (key, value) into a dictionary. |
| str() | Is used to convert an integer into a string |
| complex(real, imag) | Converts real numbers to complex(real, imag) number. |
Python lesson: String Literals in Python
This lesson explains what is string literal and what are the different ways to assign strings literal to a string variable using single and double-quotes.
What is a String Literal
Literal refers to a specific value or a fixed value or a constant that is used in the program. Normally when literal consists of a single character, it refers to character literal. When literal consists of more than one character, it refers to as String literal. But, in the case of Python language, there is no character data type, so all single characters are strings with length one.
Code:
a_string_variable = 'Python Programming Course'
In the above code, the ‘Python Programming Course’ is a string literal and a_string_variable is a string variable. In short, the string variable points to a string literal. Different string variables can point to a single literal but one string variable can point to only one literal at a given time.
How to represent string literal in Python
String literal can be placed inside single quotes or double-quotes. The more formal way is to say that String literal is represented using single or double-quote delimiters.
Assigning string literal to a variable using single quotes as delimiters.
Code:
single_quote_variable = 'Hi I am placed inside single quotes'
Assigning string literal to a variable using double quotes as delimiters.
Code:
double_quote_variable = "Hi I am placed inside double quotes"
Combination of Single quote and Double quotes to represent String Literal
In python programming, there is no difference between string literal when placed inside single or double-quotes. It means there is no semantic difference between these two representations, it differs only in syntax.
Code:
single_quote_variable = 'Hi I am placed inside single quotes' double_quote_variable = "Hi I am placed inside double quotes"
There may be a scenario when you want to use a single quote or double quote as a character in the string literal. Python is so cool regarding that.
You can simply place a double quote inside the string literal when using single quotes as delimiters. Similarly, you can place a single quote inside the string literal when using single quotes as delimiters. If you are confused, go through the below python code and output.
Code:
print('Place " double quotes when using single quote as delimiter')
print("Place ' single quotes when using double quote as delimiter")
a_double_inside_single = 'Place "Watch me" double quotes when using single quote as delimiter'
b_single_inside_double = "Place 'Watch me' single quotes when using double quote as delimiter"
print(a_double_inside_single)
print(b_single_inside_double)
Output:
Place " double quotes when using single quote as delimiter Place ' single quotes when using double quote as delimiter Place "Watch me" double quotes when using single quote as delimiter Place 'Watch me' single quotes when using double quote as delimiter
Backslash character has special interpretation when placed inside Single quote and Double quotes.
Before explaining the importance of Backslash character. Think of a scenario when you need to place a single quote in string literal delimited by single quotes. Similarly, how will you place a double quote in string literal delimited by double quotes?
Code:
print('Place ' single quote when using single quote as delimiter')
print("Place " double quotes when using double quote as delimiter")
Output:
print('Place ' single quote when using single quote as delimiter')
^
SyntaxError: invalid syntax
Explanation:
As soon as you place, the single quote character inside the string literal delimited by single quotes, the placed single quote character will act as the delimiter and the remaining string will not be delimited.
So, here comes the backslash character to the rescue. When a single quote is preceded by a backslash, it instructs the Python Interpreter to ignore the special meaning of a single quote and consider it as an ordinary character. The same goes for the double-quotes.
Code:
print('Place \' single quote with backslash when using single quote as delimiter')
print("Place \" double quotes with backslash when using double quote as delimiter")
Output:
Place ' single quote with backslash when using single quote as delimiter Place " double quotes with backslash when using double quote as delimiter
Wait, it does not end here. Backslash has another purpose too. As we see, the backslash hides the special meaning of a single quote and double quote. Similarly, some characters when preceded by a backslash have special meaning. In the below code we are using \n i.e when n is preceded by a backslash it refers to new-line.
Code:
print("I am a message and \nI will print in two separate lines")
print(r"I am a message and \nI will print in two separate lines")
Output:
I am a message and I will print in two separate lines I am a message and \nI will print in two separate lines
The first print function will print in two separate lines because of the new-line character. But in the second case, r hides the special meaning of character preceded with a backslash.
You can use triple quotes to enclose strings with more than one line
Triple quotes can be a combination of either single quotes or double quotes
Code:
print('''I am a string literal
... has more than one
... line
....placed inside triple single quotes ''')
print("""I am a string literal
... has more than one
... line
....placed inside triple double quotes """)
Output:
I am a string literal ... has more than one ... line ....placed inside triple single quotes I am a string literal ... has more than one ... line ....placed inside triple double quotes
Python lesson: Print() Function in Detail
In this lesson, we will learn about
- A basic thumb rule to remember
- Print function with Single and Double Quotes
- Printing Variables using print() function
- Performing mathematics inside print() function
- Printing using f-String
- Use of Backslash preceded characters inside the print() function
- String Formatting using {} Curly Brackets and format()
- String Formatting using C Programming Language % style format specifiers
- String concatenation, end = ” ” concept inside print() function
A basic thumb rule to remember
The print function in Python takes arguments separated by commas. An argument can be simply a text placed inside a single/double quote or it can be a name of a variable.
For example:
print(“I am demo text”, x,’print me’,”why not”,y)
print(Arg1, Arg2, Arg3, Arg4,……,ArgN)
Print function with Single and Double Quotes
You can print any text if placed inside single and double quotes inside the print() function.
Code: When using single and Double quotes
print('Demo print: Enclosed inside single quotes')
print("Demo print: Enclosed inside double quotes")
Output:
Demo print: Enclosed inside single quotes Demo print: Enclosed inside double quotes
Printing Variables using print() function
Now, we will discuss how to print variables without a format specifier. As you we discussed in thumb rule, you can simply use any number of argument inside a print function. To print a variable without format specifier just print the name of the variable.
Code: Printing Variable without Format String
x = 5
print("Let's print Variable x",x, 'See it is working')
Output:
Let's print Variable x 5 See it is working
Explanation:
In the above code we used three-argument:
- The first argument is a string: text placed inside Double Quotes
- The second argument is a variable name
- The third argument is a string: text placed inside Single Quotes
Performing mathematics inside print() function
We can also perform mathematic operations inside the print() function. The mathematics expression will evaluate to a numeric data value, thus should not be placed inside quotes.
Code: Performing maths operation inside print() function
x = 5
y = 10
z = 10
print("Let's perform addition", x + y + z)
print("Let's perform Subtraction", x - y, z - x)
print("Let's perform Multiplication", x * y * z)
print("Let's perform Division", z / x)
Output:
Let's perform addition 25 Let's perform Subtraction -5 5 Let's perform Multiplication 500 Let's perform Division 2.0
Printing using f-String
Let’s take an example to understand the need for the format string. If you want to display the value of a variable inside a string placed between a single or double-quotes. Please go through the following code and output.
Code: Trying to print
x = 105
y = "Python 3 Program"
print("x y")
print(f"{x} {y}")
Output:
x y 105 Python 3 Program
Explanation:
In the above code, you can see that when we are trying to print the value of x and y at Line number 3, the only variable name is printed not value. Here f-string comes to use, when a string with single and double quotes is started with f character, we can print the actual value of any variable enclosed within brackets {} often referred to as Curly brackets.
So, the f-string is a way to format strings. The code below will help you to understand this concept better.
Code: Assigning format string to a variable and use it to print
x = 1209
y = "The value of x is"
z = f"{y} {x}"
print(f"{x}")
print(f"{y}")
print(z)
print(f"x value is : {x}")
print(f"The value y is : {y}")
Output:
1209 The value of x is The value of x is 1209 x value is : 1209 The value y is : The value of x is
Use of Backslash preceded characters inside the print() function
We have already studied about Backslash character in the post String Literals in Python, Backslash helps to hide the meaning of single and double quotes but it also helps to print some important characters in the Terminal output listed in the table given below:
| Escape Sequence | Meaning |
|---|---|
| \\ | Backslash (\) |
| \' | Single-quote (') |
| \" | Double-quote (") |
| \a | ASCII bell (BEL) |
| \b | ASCII backspace (BS) |
| \f | ASCII formfeed (FF) |
| \n | ASCII linefeed (LF) |
| \N{name} | Character named name in the Unicode database (Unicode only) |
| \r | Carriage return (CR) |
| \t | Horizontal tab (TAB) |
| \uxxxx | Character with 16-bit hex value xxxx |
| \Uxxxxxxxx | Character with 32-bit hex value xxxxxxxx |
| \v | ASCII vertical tab (VT) |
| \000 | Character with octal value 000 |
| \xhh | Character with hex value hh |
Code: Printing Backslash Characters
print("Print New Line character \n")
print("Print Single quote: \'")
print("Print Double quote: \"")
print("Print HorizontalTab: \t")
print("Print Vertical Tab \v")
Output:
Print New Line character Print Single quote: ' Print Double quote: " Print HorizontalTab: Print Vertical Tab
String Formatting using {} Curly Brackets and format()
-
format() function to allow multiple substitutions and value formatting
We discussed f-String in the above section which helps to substitute the value of a variable inside the string. There is a function called format() which facilitates to allow multiple substitutions inside a string through positional formatting.
Positional formatting refers to the usage of any number of curly braces inside a string and with the help of format function, we will substitute the value based on the position of curly braces.
Usage can be understood from the given example:
"I am a {} programmer with {} years of experience".format("Python", 10)
The below syntax refers to the above usage:
string.format()
- Where string refers to a string variable or string placed using single or double quotes
- Dot format .format() is the syntax to call the function
Input type: format() takes input as any Data type.
Return type: string.format() function returns a string with substituted values used for curly brackets positions.
a = "I am a {} programmer with {} years of experience".format("Python", 10)
print(a)
print("Learn {} {} by practise".format("Python", "Programming"))
format_string = "{} {} {} {}"
print(format_string.format(1, 3, 4, 9))
print(format_string.format("I am", "a", "Python", "Programmer"))
print(format_string.format("I have", 10, "years of experience", "In Python"))
print(format_string)
Output:
I am a Python programmer with 10 years of experience
Learn Python Programming by practise
1 3 4 9
I am a Python Programmer
I have 10 years of experience In Python
{} {} {} {}
Advanced Printing using C Programming Language % style format specifiers
Just now we have studied the concept of format string using curly braces {} and format function that helps to print different data types using the print function. You can achieve the same with the % format string.
If you have studied C Programming language, you must be aware of format specifiers mentioned below
| % Format Specifier | Type |
|---|---|
| %d | integer |
| %f | float |
| %s | string |
| %x | hexadecimal |
| %o | octal |
The following syntax is used for % format strings
print("%d %s %d....%f" %(var1, var2, var3....varN)
The following code will help you to grasp the concept of the format string
Code: Printing using % format string
a = 5
b = "I am "
c = "a"
d = "Python Programmer"
print("%s %s %s with %d years of experience" % (b, c, d, a))
Output:
I am a Python Programmer with 5 years of experience
String concatenation, end = ” ” concept inside print() function
In this section, we will discuss
-
String concatenation inside the print function
-
Multiplying a string by a number to print multiple strings
- end = ‘ ‘ in python
-
String concatenation inside the print function
Code: String Concatenation Inside Print Function
var_1 = "I " var_2 = "am " var_3 = "a " var_4 = "Python " var_5 = "Program " print(var_1 + var_2 + var_3 + var_4 + var_5)
Output:
I am a Python Program
-
Multiplying a string by a number to print multiple strings
Code: Multiplying a string inside Print Function
var_1 = "I "
print(var_1 * 10)
print("Python " * 3)
Output:
I I I I I I I I I I Python Python Python
-
end = ” ” in python
end = ” ” or end = ‘ ‘ is used when the programmer wants to stay on the same line, instead of going to the next line which is the default behavior of print() function after printing anything.
Code: Display the use of end = ” ” or end = ‘ ‘
var_1 = "I "
print(var_1 * 10, end=" ")
print("Python " * 3)
Output:
I I I I I I I I I I Python Python Python
Python lesson: Input function in Python 3
In this lesson, we will learn about
- Python 3 builtin function: input()
You can simply use input() function for input data, the data entered using input is treated as a string.
Code: How to use the input function
print("Enter your age")
a=input()
print("Entered age is {}".format(a))
print("The type of value entered is {}".format(type(a)))
Output:
Enter your age 34 Entered age is 34 The type of value entered is <class 'str'>
Explanation:
The type returned as a string in the output for the age data because input data is treated as a string.
You can also print message while input
Code: Print message while input
a = int(input("Enter your age: "))
print("Entered age is %d" % a)
Output:
Enter your age: 345 Entered age is 345
Python lesson: Input method to pass a variable to Python Script
We have already discussed input() function which is a builtin function in Python 3. In this lesson, we will explore another method which one can use to pass variable while executing the Python Script.
This method is similar to passing arguments while executing a command in Linux. It can also be related to the C/C++ programming language main function arguments:
int main(int argc, char *argv[]) { /* ... */ }
Let’s dive in to explore how to use it in Python. Do not worry, if you are not aware of the above function. Just look at the code given below and seek out the explanation given for the code.
Code: Input method to pass arguments to a Python script
# Save the script as test.py
from sys import argv
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
Executing the script:
> python test.py Learn Python Programming
Output:
The script is called: test.py Your first variable is: Learn Your second variable is: Python Your third variable is: Programming
Explanation:
The first line in the program from sys import argv refers to import the specific function from the sys package. Instead of importing the complete sys package we imported specific module argv to keep the code minimum. You will learn it better when you will build your own modules, in the upcoming sections.
script, first, second, third = argv This line unpack argv and get assigned to four variables script, first, second, and third. It refers to Assigning Multiple values to Multiple Variables in a single line
The rest of the code is simply printing the value stored in the variables.
Python lesson: Operators in Python 3
In this lesson, we will learn about various Python operators divided into the following categories:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Arithmetic operators in Python
Operator Name Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus a % b
** Exponentiation a ** b
// Floor division a // b
Assignment operators in Python
| Operator | Example | Equivalent to |
|---|---|---|
| = | a = 5 | a = 5 |
| += | a += 3 | a= a + 3 |
| -= | a -= 3 | a = a - 3 |
| *= | a *= 3 | a = a * 3 |
| /= | a /= 3 | a= a / 3 |
| %= | a %= 3 | a = a % 3 |
| //= | a //= 3 | a = a // 3 |
| **= | a **= 3 | a = a ** 3 |
| &= | a &= 3 | a = a & 3 |
| |= | a |= 3 | a = a | 3 |
| ^= | a^= 3 | a= a ^ 3 |
| >>= | a >>= 3 | a = a >> 3 |
| <<= | a <<= 3 | a = a << 3 |
Comparison operators in Python
| Operator | Name | Example |
|---|---|---|
| == | Equal | a == b |
| != | Not equal | a != b |
| > | Greater than | a > b |
| < | Less than | a < b |
| >= | Greater than or equal to | a >= b |
| <= | Less than or equal to | a <= b |
Logical operators in Python
| Operator | Description | Example |
|---|---|---|
| AND | Returns True if both statements are true | a < 4 and a < 11 |
| OR | Returns True if one of the statements is true | a < 7 or x < 3 |
| NOT | Reverse the result, returns False if the result is true | not(a < 1 and a < 5) |
Identity operators in Python
| Operator | Description | Example |
|---|---|---|
| is | Returns true if both variables are the same object | a is b |
| is not | Returns true if both variables are not the same object | a is not b |
Membership operators in Python
| Operator | Description | Example |
|---|---|---|
| in | Returns True if a sequence with the specified value is present in the object | a in b |
| not in | Returns True if a sequence with the specified value is not present in the object | a not in b |
Bitwise operators in Python
| Operator | Name | Description |
|---|---|---|
| & | AND | Sets each bit to 1 if both bits are 1 |
| | | OR | Sets each bit to 1 if one of two bits is 1 |
| ^ | XOR | Sets each bit to 1 if only one of two bits is 1 |
| ~ | NOT | Inverts all 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 |
Python lesson: Boolean Operators in Python 3
In this lesson, we will discuss Python Booleans
Boolean represents one of two values: True or False. In Python when you evaluate an expression using comparison operator, logical operators, Identity operators or Membership operators, the value returned is either True or False.
Printing Boolean Value using comparison operators
Code:
a = 3 b = 4 print(a == b) print(a != b) print(a > b) print(a < b) print(a >= b) print(a <= b)
Output:
False True False True False True
Printing Boolean Value using logical operators
Code:
a = 3 b = 4 print(a < b and a < 10) print(a > b or a < 5) print(not(a > b or a < 5))
Output:
True True False
Printing Boolean Value using Identity operators
Code:
a = 3 b = 4 print(a is b) print(a is not b)
Output:
False True
Printing Boolean Value using Membership operators
Code:
a = [2, 3, 4, 5] b = 4 c = 1 print(b in a) print(c not in a)
Output:
True True
Python lesson: Flow Control in Python 3, if else, for loop, while loop
In this lesson, we will discuss if block, if-else block, if-elif-else block. Then we will discuss, While and For loop in Python 3 Programming.
Python Programming with if construct
You must have studied comparison operators in previous lesson Python Operators. With the help of a comparison operator, we can build expressions that will result in either True or False value. Thus, using if conditional construct we can take action or execute a line of codes based on the returned value is True or False.
Note: The use of operators in the conditional expression is not limited to comparison operators.
Code:
a = 6
b = 4
c = 4
if a > b:
print("{} is greater than {}".format(a, b))
if a > c:
print("{} is less than {}".format(c, a))
if b == c:
print("{} is equal to {}".format(b, c))
if a != c:
print("{} is not equal to {}".format(a, c))
if a >= b:
print("{} is greater than equal to {}".format(a, b))
if a > c:
print("{} is less than equal to {}".format(c, a))
Output:
6 is greater than 4 4 is less than 6 4 is equal to 4 6 is not equal to 4 6 is greater than equal to 4 4 is less than equal to 6
Python Programming with if-else block
We will make a program to find the lowest integer number out of two unique integers.
Code:
a = int(input("Enter first integer: "))
b = int(input("Enter Second integer: "))
if a < b:
print("{} is the lowest integer".format(a))
else:
print("{} is the lowest integer".format(b))
Output:
Enter first integer: 4 Enter Second integer: 3 3 is the lowest integer
Python Programming with if-elif-else block
Code:
a = b = 4
c = 5
if a > b:
print("{} is greater than {}".format(a, b))
elif b == c:
print("{} is equal to {}".format(b, c))
else:
print("Neither a is greater than b Nor b is equal to c ")
Output:
Neither a is greater than b Nor b is equal to c
Python Programming with Nested if
We will make a program to find the greatest number out of three unique integer numbers.
Test Cases:
# a b c # 3 4 5 # 3 5 4 # 4 3 5 # 4 5 3 # 5 3 4 # 5 4 3
Code:
a = int(input("Enter first integer: "))
b = int(input("Enter Second integer: "))
c = int(input("Enter Third integer: "))
if a > b:
if a > c:
print("{} is the greatest element".format(a))
else:
print("{} is the greatest element".format(c))
elif b > c:
print("{} is the greatest element".format(b))
else:
print("{} is the greatest element".format(c))
Output:
Enter first integer: 3 Enter Second integer: 4 Enter Third integer: 5 5 is the greatest element
Python Programming with for loop
You need a loop construct when you need to perform the operation which is to be repeated over a list or range of data. In this section, we will discuss the possible uses of for loop in Python 3 programming.
Programming for loop over a list of Data
Code:
a = [0, 1, 2, 3, 4]
for i in a:
a[i] += 1
print("List after increment: {}".format(a))
Output:
List after increment: [1, 2, 3, 4, 5]
Programming for loop over a range of numbers
We will also use the range data type, which we discussed in an earlier lesson Data Types available in Python
Code:
a = ["one", "two", "three", "four", "five"]
for i in range(0, 5):
print("Value of i at {} step is {}".format(a[i], i + 1))
Output:
Value of i at one step is 1 Value of i at two step is 2 Value of i at three step is 3 Value of i at four step is 4 Value of i at five step is 5
Python Programming using while loop
Code:
a = ["one", "two", "three", "four", "five"]
i = 0
while i < 5:
print(a[i])
i += 1
Output:
one two three four five
Python lesson: Functions in Python 3
In this lesson, we will learn how to define functions, using the function with variables and function returning value.
In Python, we define a function with a keyword starting with def than the name of the function. A function can have zero or any number of arguments. We will further use the line of codes under the function. To call a function we can call with function name with or without variables.
Syntax:
def funtion_name(var1, Var2, Var3.....varN):
Code line 1...
Code line 2...
Programming function with Zero Argument
Code:
def greater_function():
print("a is greater than b")
def smaller_function():
print("a is smaller than b")
a = 3
b = 7
if a > b:
greater_function()
else:
smaller_function()
Output:
a is smaller than b
Programming function that accepts arguments
We will make a program with basic calculator functionalities that provide addition, multiplication, subtraction and division functions.
Code:
def addition_fun(a, b):
return a + b
def multiply_fun(a, b):
return a * b
def subtraction_fun(a, b):
return a - b
def division_fun(a, b):
return a / b
x = int(input("Enter any integer value: "))
y = int(input("Enter any integer value: "))
print("Result after Addition is {}".format(addition_fun(x, y)))
print("Result after Multiplication is {}".format(multiply_fun(x, y)))
print("Result after Subtraction is {}".format(subtraction_fun(x, y)))
print("Result after Division is {}".format(division_fun(x, y)))
Output:
Enter any integer value: 10 Enter any integer value: 5 Result after Addition is 15 Result after Multiplication is 50 Result after Subtraction is 5 Result after Division is 2.0
Python lesson: Scope of a Variable in Python 3
In this lesson, we will discuss an important concept, the scope of a variable in Python 3. In Python, there are four scopes possible for a given variable which refers to LGEB: Local, Enclosed, Global and Built-in Scopes.
- Local(L): Defined inside a function/class or enclosed within a nested loop or conditional construct.
- Enclosed(E): Defined inside enclosing functions (Nested functions)
- Global(G): Defined at the topmost level
- Built-in(B): Reserved Keywords in Python built-in functions/modules/classes
In simple terms, it is the order in which the namespaces are to be searched for scope resolution.
Note: Namespaces are named program regions used to limit the scope of variables inside the program.
Given below is the image which shows the hierarchal order in which the namespaces are to be searched for scope resolution: the first order is local, the second-order is enclosed, the third-order is global and the last order is Built-in.

Program to explain the local scope of a variable
Code:
var_scope = 'I am a variable with global scope'
def local_scope_func():
var_scope = "I am a variable with local scope"
print(var_scope)
local_scope_func()
Output:
I am a variable with local scope
Explanation:
In the above program, though we have defined two variables with the same name, one is at the topmost level and the other is inside the function. We can clearly see after executing our program that the variable inside the function is printed. It means the function searches the variable inside the local boundary first, If it is not found then only it will access the global variable.
Program to explain the local and global scope of a variable
Code:
var_scope = 'I am a variable with global scope'
def local_scope_func():
var_scope = "I am a variable with local scope"
print(var_scope)
local_scope_func()
print(var_scope)
Output:
I am a variable with local scope I am a variable with global scope
Explanation:
The output for the first line is clearly understood as discussed above. The print(var_scope) does not have access to the variable defined inside the function local_scope_fun() so it will access the global variable var_scope declared at the topmost level without any doubt.
Program to explain the local, enclosed and global scope of a variable
Code:
var_a = 'global variable'
def Function_at_level_one():
var_a = 'variable at level one'
def Function_at_level_two():
# var_a = 'variable at level two'
nonlocal var_a
print(var_a)
Function_at_level_two()
Function_at_level_one()
print(var_a)
Output:
variable at level one global variable
Explanation:
In this program, we have used keyword nonlocal, which is used to access the variable declared in the outer function.
Program to explain the local, enclosed, global and Built-in scope of a variable
Code:
from math import pi
# pi = 'global pi variable'
def outer():
# pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
print(pi)
inner()
outer()
Output:
3.141592653589793
Explanation:
In this program, we have imported built-in variable pi from the math package. When we execute the function, it first searches the pi variable inside inner(), when it is not found it searches inside the outer() function, when it is not found, it searches the variable at the global level. When it is not found at global level, it uses the built-in pi variable to print
Python lesson: File handling in Python 3
Earlier you have learned about how to get input from the user using input and argv method. In this lesson, you will learn about how to read from a file and various functions that are important for file handing using Python 3.
List of functions you will study in this post regarding File Handling.
| Name of the Function | Role of Function |
|---|---|
| open | It is use to open the given file. |
| close | Closes the file. |
| read | Reads the contents of the file. You can assign the result to a variable. |
| readline | Reads just one line of a text file. |
| truncate | Empties the file. |
| write('stuff') | Writes “stuff” to the file. |
| seek(0) | Moves the read/write location to the beginning of the file. |
Program Implemetation: Open | Truncate | Write | Close
Code:
from sys import argv
program_name, filename = argv
print("We are going to erase the content of the given file first, if the file exists")
print("Opening the File....")
destination = open(filename, 'w')
print("Erasing the content of the file....")
destination.truncate()
print("Now Enter the data you want: In three lines")
Line1 = input("Line 1: ")
Line2 = input("Line 2: ")
Line3 = input("Line 3: ")
print("These three lines will be written")
destination.write(Line1)
destination.write("\n")
destination.write(Line2)
destination.write("\n")
destination.write(Line3)
destination.write("\n")
print("Now the file is set to close")
destination.close()
Output:
We are going to erase the content of the given file first, if the file exists Opening the File.... Erasing the content of the file.... Now Enter the data you want: In three lines Line 1: I love Python Programming Line 2: I love to code using Python Line 3: I am good at Python Programming These three lines will be written Now the file is set to close
Program Implementation: Copy data of One File to Another
Code:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
# we could do these two on one line, how?
input_file = open(from_file)
input_data = input_file.read()
print(f"The input file is {len(input_data)} bytes long")
print(f"Does the output file exist? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
output_file = open(to_file, 'w')
output_file.write(input_data)
print("File is Copied Successfully")
Output:
Copying from sample.txt to sample_copy.txt The input file is 86 bytes long Does the output file exist? False Ready, hit RETURN to continue, CTRL-C to abort. File is Copied Successfully
Python lesson: Important Built-in Function in Python 3
In this lesson, we will discuss important built-in function in Python 3.
type() function in Python
Role of type() Function:
The type() returns the type of an object
Syntax:
type(object)
Code:
a_string = "I am a string" a_integer = 3 a_float = 5.9 a_complex = 3 + 4j a_list = [1, 2, 3, 4] print(type(a_string)) print(type(a_integer)) print(type(a_float)) print(type(a_complex)) print(type(a_list))
Output:
<class 'str'> <class 'int'> <class 'float'> <class 'complex'> <class 'list'>
abs() function in Python
Role of abs() Function:
The abs() function is used to return the absolute value of a number.
Syntax:
abs(number) number : Can be integer, a floating point number or a complex number
Code:
# Floating point number
x_float = -101.89
print('Absolute value of float is:', abs(x_float))
# Integer Number
y_int = -61
print('Absolute value of integer is:', abs(y_int))
# Complex number
z_complex = (-4 - 3j)
print('Absolute value or Magnitude of complex is:', abs(z_complex))
Output:
Absolute value of float is: 101.89 Absolute value of integer is: 61 Absolute value or Magnitude of complex is: 5.0
all () function in Python
Role of all() Function:
The all() function returns True if all items in an iterable object are true
Syntax:
all(object) object can be a list
Code:
x = [False, True, True, True, True] print(all(x)) x = [True, True, True, True, True] print(all(x))
Output:
False True
any () function in Python
Role of any() Function:
The any() function returns True if any item in an iterable object is true
Syntax:
any(object) object can be a list
Code:
x = [False, True, True, True, True] print(any(x)) x = [True, True, True, True, True] print(any(x))
Output:
True True
bin () function in Python
Role of bin() Function:
The bin() function returns the binary version of a number
Syntax:
bin(number) object can be a list
Code:
x = 32 print(bin(x)) y = 255 print(bin(y))
Output:
0b100000 0b11111111
bool () function in Python
Role of bool() Function:
The bool() function returns the boolean value of the specified object
Code:
print(bool(3 < 5)) print(bool(3 == 5))
Output:
True False
float () function in Python
Role of float() Function:
The float() function returns the float value
Code:
a = input("Enter a Float number: ")
if type(a) == float:
print("Entered number is not float")
else:
print("Entered Number is {}".format(type(a)))
print("Let's convert string type to float type")
a = float(a)
if type(a) == float:
print("String Type is finally converted to float")
Output:
Enter a Float number: 3.0 Entered Number is <class 'str'> Let's convert string type to float type String Type is finally converted to float
int () function in Python
Role of int() Function:
The int() function returns the integer value
Code:
a = input("Enter a Integer number: ")
if type(a) == float:
print("Entered number is not Integer")
else:
print("Entered Number is {}".format(type(a)))
print("Let's convert string type to Integer type")
a = float(a)
if type(a) == float:
print("String Type is finally converted to Integer")
Output:
Enter a Integer number: 3 Entered Number is <class 'str'> Let's convert string type to Integer type String Type is finally converted to Integer
str () function in Python
Role of str() Function:
The str() function returns the string data type
Code:
a_string = "I am a string" a_integer = 3 a_float = 5.9 a_complex = 3 + 4j a_list = [1, 2, 3, 4] print(type(str(a_string))) print(type(str(a_integer))) print(type(str(a_float))) print(type(str(a_complex))) print(type(str(a_list)))
Output:
<class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'>
len () function in Python
Role of len() Function:
The len() function returns the length of an object
Code:
a = input("Enter some Text: ")
print("The length of the text entered is: {} ".format(len(a)))
a_list = ["I", "am", "a", "Python", "Programmer"]
print("The length of the list is: {} ".format(len(a_list)))
Output:
Enter some Text: I am a Python Programmer The length of the text entered is: 24 The length of the list is: 5
list () function in Python
Role of list() Function:
The list() function returns a list
Code:
a = input("Enter some Text: ")
print("Now we will convert the text in to list: ")
a = list(a)
print(a)
Output:
Enter some Text: Python Now we will convert the text in to list: ['P', 'y', 't', 'h', 'o', 'n']
sorted () function in Python
Role of sorted() Function:
The sorted() function returns a sorted list
Code:
a = [5, 104, 109, -1, 12, 3]
print("Printing the sorted list: ")
print(sorted(a))
Output:
Printing the sorted list: [-1, 3, 5, 12, 104, 109]
reversed () function in Python
Role of reversed() Function:
The reversed() function returns a reversed iterator
Code:
a = [5, 104, 109, -1, 12, 3]
a_iterator = reversed(a)
a = list(a_iterator)
print("Printing the reversed list: ")
print(list(a))
Output:
Printing the reversed list: [3, 12, -1, 109, 104, 5]
round () function in Python
Role of round() Function:
The round() function returns a round value
Code:
print(round(3.5)) print(round(-3.48)) print(round(5.19)) print(round(7.9))
Output:
4 -3 5 8
iter () function in Python
Role of iter() Function:
The iter() function returns an iterator object
Code:
a = iter([5, 4, 3, 2, 1])
print(a)
print("We will pass the list_iterator object to sort the list ")
b = sorted(a)
print("Sorted List is: ")
print(b)
Output:
<list_iterator object at 0x000001B9CC263208> We will pass the list_iterator object to sort the list Sorted List is: [1, 2, 3, 4, 5]
next () function in Python
Role of next() Function:
The next() function returns the next item in an iterable
Code:
a_list = [5, 4, 3, 2, 1]
a_iter = iter(a_list)
a_length = len(a_list)
print("Length of the list is: {}".format(a_length))
print("We will run the for loop {} times".format(a_length))
for i in range(0,a_length):
print(next(a_iter))
Output:
Length of the list is: 5 We will run the for loop 5 times 5 4 3 2 1
range () function in Python
Role of range() Function:
The range() function returns a sequence of numbers, starting from 0 and increments by 1 (by default)
Code:
a_list = [5, 4, 3, 2, 1]
a_length = len(a_list)
a_iter = iter(a_list)
print("Length of the list is: {}".format(a_length))
print("We will run the for loop {} times".format(a_length))
for i in range(0,a_length):
print(next(a_iter))
#Default increment value is 1 in range function
#Now we will change the increment/step value to 3
for i in range(0, 15, 3):
print("Value of i is {}".format(i))
Output:
Length of the list is: 5 We will run the for loop 5 times 5 4 3 2 1 Value of i is 0 Value of i is 3 Value of i is 6 Value of i is 9 Value of i is 12
sum () function in Python
Role of sum() Function:
The sum() function sums the items of an iterator
Code:
a_list = [5, 4, 3, 2, 1]
print("Sum of all integers in the list is: {}".format(sum(a_list)))
Output:
Sum of all integers in the list is: 15
min () function in Python
Role of min() Function:
The min() function returns the smallest item in an iterable
Code:
a_list = [5, 4, 3, 2, 1]
print("Minimum of all integers in the list is: {}".format(min(a_list)))
Output:
Minimum of all integers in the list is: 1
max () function in Python
Role of max() Function:
The max() function returns the largest item in an iterable
Code:
a_list = [5, 4, 3, 2, 1]
print("Largest of all integers in the list is: {}".format(max(a_list)))
Output:
Largest of all integers in the list is: 5
Python lesson: Strings in Python 3
In, this lesson we will learn how to manipulate strings and also discuss some functions to handle strings.
Accessing String using the concept of Array
As we know that string can be placed inside single or double-quotes. We have also read some string handling in past lessons. Now, we will learn how to access string using the concept of arrays. In simple terms, a string is an array of characters. In Python, we can access the individual character of a string using the index method. Let’s understand it with an example.
The first character of the string can be accessed using index 0, the second character using index 1. It means that a string of n characters can be accessed using index 0 to n-1 from first to the last character.
One more interesting thing you will discover that string can also be accessed in a reverse manner, using a negative index. It means that a string of n characters can be accessed in a reverse manner using index -1 to -n from last to the first character.
Enough Talking, Let’s understand this concept using Python Program
Code:
a_string = "Python"
a_length = len(a_string)
print("Length of the String is {}".format(a_length))
print("Let's Print the character of String using index 0 to index n-1")
index = 0
for index in range(0, a_length):
print(a_string[index], end=" ")
print("\nLet's Print the character of String in reverse using index -1 to index -n")
for index in range(1, a_length+1):
print(a_string[-index], end=" ")
print("\n")
print(a_string[0:a_length])
print(a_string[-a_length:-1])
Output:
Length of the String is 6 Let's Print the character of String using index 0 to index n-1 P y t h o n Let's Print the character of String in reverse using index -1 to index -n n o h t y P Python Pytho
Now let’s Study some String functions
capitalize() method
Converts the first character to upper case
Code:
a_string = "python"
print("String after Capitalization is {}".format(a_string.capitalize()))
Output:
String after Capitalization is Python
casefold() method
Converts string into lower case
Code:
a_string = "PYTHON"
print("String after Capitalization is {}".format(a_string.casefold()))
Output:
String after Capitalization is python
center() method
Will center align the string, using a specified character (space is default) as the fill character.
Syntax:
string.center(length, character)
| Parameter | Description |
|---|---|
| length | Required. The length of the returned string |
| character | Optional. The character to fill the missing space on each side. Default is ” ” (space) |
Code:
a_string = "PYTHON"
print("Using the character S as padding character")
print(a_string.center(10, 'S'))
Output:
Using the character S as padding character SSPYTHONSS
count() method
Returns the number of times a specified value occurs in a string
Syntax:
string.count(value, start, end)
| Parameter | Description |
|---|---|
| value | Required. A String. The string to value to search for |
| start | Optional. An Integer. The position to start the search. Default is 0 |
| end | Optional. An Integer. The position to end the search. Default is the end of the string |
Code:
a_string = "Python is no better than Python so I use Python Python"
length = len(a_string)
print(a_string.count("python", 0, length))
print(a_string.count("Python", 0, length))
Output:
0 4
encode() method
method encodes the string, using the specified encoding.
If no encoding is specified, UTF-8 will be used.
Syntax:
string.encode(encoding=encoding, errors=errors)
| Parameter | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| encoding | Optional. A String specifying the encoding to use. Default is UTF-8 | ||||||||||||
| errors | Optional. A String specifying the error method. Legal values are:
|
Code:
a = "I would like to study in Luleå tekniska universitet"
print(a.encode(encoding="utf-8",errors="backslashreplace"))
print(a.encode(encoding="utf-8",errors="ignore"))
print(a.encode(encoding="utf-8",errors="namereplace"))
print(a.encode(encoding="utf-8",errors="replace"))
print(a.encode(encoding="utf-8",errors="xmlcharrefreplace"))
print(a.encode(encoding="utf-8",errors="strict"))
print("The special character 'å' which is not supported in ASCII ")
print(" Can be encoded using UTF-8")
print(a)
Output:
b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' The special character 'å' which is not supported in ASCII Can be encoded using UTF-8 I would like to study in Luleå tekniska universitet
endswith() method
returns True if the string ends with the specified value, otherwise False.
Syntax:
string.endswith(value, start, end)
| Parameter | Description |
|---|---|
| value | Required. The value to check if the string ends with |
| start | Optional. An Integer specifying at which position to start the search |
| end | Optional. An Integer specifying at which position to end the search |
Code:
a_string = "Welcome to the World of Python Programming"
True_or_False = a_string.endswith("Programming", 0, len(a_string))
print(True_or_False)
Output:
True
expandtabs() method
sets the tab size to the specified number of whitespaces.
Syntax:
string.exandtabs(tabsize)
| Parameter | Description |
|---|---|
| tabsize | Optional. A number specifying the tabsize. Default tabsize is 8 |
Code:
programming = "P\tr\to\tg\tr\ta\tm\tm\ti\tn\tg" print(programming) print(programming.expandtabs()) print(programming.expandtabs(2)) print(programming.expandtabs(4)) print(programming.expandtabs(10))
Output:
P r o g r a m m i n g P r o g r a m m i n g P r o g r a m m i n g P r o g r a m m i n g P r o g r a m m i n g
find() method
- finds the first occurrence of the specified value.
- find() method returns -1 if the value is not found.
- find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found.
Syntax:
string.find(value, start, end)
| Parameter | Description |
|---|---|
| value | Required. The value to search for |
| start | Optional. Where to start the search. Default is 0 |
| end | Optional. Where to end the search. Default is to the end of the string |
Code:
programming = "Welcome to world of Python Programming"
value = programming.find("to", 0, len(programming))
print(value)
print(programming.find("q"))
print(programming.index("q"))
Output:
8
-1
Traceback (most recent call last):
File "practise.py", line 6, in <module>
print(programming.index("q"))
ValueError: substring not found
format() method
We have already discussed the format() method in previous lessons String Formatting using {} Curly Brackets and format(). you can visit the link if you want to revise the concept.
index() method
- The index() method finds the first occurrence of the specified value.
- The index() method raises an exception if the value is not found.
- The index() method is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found. (See example below)
Syntax:
string.index(value, start, end)
| Parameter | Description |
|---|---|
| value | Required. The value to search for |
| start | Optional. Where to start the search. Default is 0 |
| end | Optional. Where to end the search. Default is to the end of the string |
Code:
programming = "Welcome to world of Python Programming"
value = programming.index("to", 0, len(programming))
print(value)
print(programming.find("q"))
print(programming.index("q"))
Output:
8
-1
Traceback (most recent call last):
File "practise.py", line 6, in <module>
print(programming.index("q"))
ValueError: substring not found
isalnum() Method
- returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Syntax:
string.isalnum()
Code:
programming = "Welcome to world of Python Programming 3" programming_1 = "WelcometoworldofPythonProgramming3" x = programming.isalnum() print(x) x = programming_1.isalnum() print(x)
Output:
False True
isdecimal() Method
- isdecimal() method returns True if all the characters are decimals (0-9). This method is used on unicode objects.
Syntax:
string.isdecimal()
Code:
a = "\u0030" #unicode for 0 b = "\u0047" #unicode for G c = "11" print(a.isdecimal()) print(b.isdecimal()) print(c.isdecimal())
Output:
True False True
isdigit() Method
- isdigit() method returns True if all the characters are digits, otherwise False. Exponents, like ², are also considered to be a digit.
Syntax:
string.isdigit()
Code:
a = "\u0030" #unicode for 0 b = "\u00B2" #unicode for ² c = "32" print(a.isdigit()) print(b.isdigit()) print(c.isdigit())
Output:
True True True
isidentifier() Method
- isidentifier() method returns True if the string is a valid identifier, otherwise False.A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.
Syntax:
string.isidentifier()
Code:
a = "_Python" b = "3Python" c = "Python" d = "Python 3" e = "Python_3" print(a.isidentifier()) print(b.isidentifier()) print(c.isidentifier()) print(d.isidentifier()) print(e.isidentifier())
Output:
True False True False True
islower() Method
- The islower() method returns True if all the characters are in lower case, otherwise False.Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax:
string.islower()
Code:
a = "_python" b = "3Python" c = "python" d = "Python 3" e = "python_3" print(a.islower()) print(b.islower()) print(c.islower()) print(d.islower()) print(e.islower())
Output:
True False True False True
isnumeric() Method
- The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.Exponents, like ² and ¾ are also considered to be numeric values.
Syntax:
string.isnumeric()
Code:
a = "_python" b = "35909" c = "45 789" d = "1033" e = "python_33" print(a.isnumeric()) print(b.isnumeric()) print(c.isnumeric()) print(d.isnumeric()) print(e.isnumeric())
Output:
False True False True False
isprintable() Method
- The isprintable() method returns True if all the characters are printable, otherwise False.Examples of none printable characters can be carriage return and line feed.
Syntax:
string.isprintable()
Code:
programmer = "Hello!\n I am a #Python Programmer" x = programmer.isprintable() print(x)
Output:
False
isspace() Method
- The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Syntax:
string.isspace()
Code:
programmer = "I am a #Python Programmer" code = " " x = programmer.isspace() print(x) y = code.isspace() print(y)
Output:
False True
istitle() Method
- The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False.Symbols and numbers are ignored.
Syntax:
string.istitle()
Code:
a = "WELCOME TO PYTHON PROGRAMMING" b = "Welcome, To World Of Python" c = "22 Python is good" d = "This Is Python" print(a.istitle()) print(b.istitle()) print(c.istitle()) print(d.istitle())
Output:
False True False True
isupper() Method
- The isupper() method returns True if all the characters are in upper case, otherwise False.Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax:
string.isupper()
Code:
a = "3 PYTHON 123 PROGRAMMING" b = "Welcome, To World Of Python" c = "22 is good" d = "@THIS IS PYTHON" print(a.isupper()) print(b.isupper()) print(c.isupper()) print(d.isupper())
Output:
True False False True
join() Method
- The join() method takes all items in an iterable and joins them into one string.A string must be specified as the separator.
Syntax:
string.join(iterable)
| Parameter | Description |
|---|---|
| iterable | Required. Any iterable object where all the returned values are strings |
Code:
demo_list = ["Program_number_", "Python_Version_", "Test_case_"] test_string = "3" result_list = test_string.join(demo_list) print(result_list, "\n")
Output:
Program_number_3Python_Version_3Test_case_
ljust() Method
- The ljust() method will left align the string, using a specified character (space is default) as the fill character.
Syntax:
string.ljust(length, character)
| Parameter | Description |
|---|---|
| length | Required. The length of the returned string |
| character | Optional. A character to fill the missing space (to the right of the string). Default is ” ” (space). |
Code:
programming = "Python" x = programming.ljust(20, "3") print(x)
Output:
Python33333333333333
lower() Method
- The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.
Syntax:
string.lower()
Code:
string_1 = "Python 3 Programs" string_2 = "PYTHON_3_PROGRAMMING" x = string_1.lower() y = string_2.lower() print(x) print(y)
Output:
python 3 programs python_3_programming
lstrip() Method
- The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax:
string.lstrip(characters)
Code:
string_1 = "P ython Programs"
string_2 = " p h t h o n p r o g r a m s"
x = string_1.lstrip("P ")
y = string_2.lstrip("p h")
print(x)
print(y)
Output:
ython Programs t h o n p r o g r a m s
lstrip() Method
- The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax:
string.lstrip(characters)
Code:
string_1 = "P ython Programs"
string_2 = " p h t h o n p r o g r a m s"
x = string_1.lstrip("P ")
y = string_2.lstrip("p h")
print(x)
print(y)
Output:
ython Programs t h o n p r o g r a m s
partition() Method
- The partition() method searches for a specified string and splits the string into a tuple containing three elements.The first element contains the part before the specified string.The second element contains the specified string.The third element contains the part after the string.Note: This method search for the first occurrence of the specified string.
Syntax:
string.partition(value)
| Parameter | Description |
|---|---|
| value | Required. The string to search for |
Code:
string_1 = "I could eat bananas all day"
x = string_1.partition("bananas")
print(x)
Output:
('I could eat ', 'bananas', ' all day')
replace() Method
- The replace() method replaces a specified phrase with another specified phrase.Note: All occurrences of the specified phrase will be replaced if nothing else is specified.
Syntax:
string.replace(oldvalue, newvalue, count)
Code:
string_1 = "C++ Programming is good C++ is best"
x = string_1.replace("C++", "Python")
print(x)
string_2 = "C++ Programming is C++ good C++ is best"
x = string_2.replace("C++", "Python", 2)
print(x)
Output:
Python Programming is good Python is best Python Programming is Python good C++ is best
rfind() Method
- The rfind() method finds the last occurrence of the specified value.The rfind() method returns -1 if the value is not found.The rfind() method is almost the same as the rindex() method.
Syntax:
string.rfind(value, start, end)
Code:
string_1 = "Python Programming, Is Python Programming"
x = string_1.rfind("Python")
print(x)
Output:
23
rjust() Method
- The rjust() method will right-align the string, using a specified character (space is the default) as the fill character.
Syntax:
string.rjust(length, character)
| Parameter | Description |
|---|---|
| length | Required. The length of the returned string |
| character | Optional. A character to fill the missing space (to the left of the string). Default is ” ” (space). |
Code:
programming = "Python" x = programming.rjust(20, "3") print(x)
Output:
33333333333333Python
rpartition() Method
- The rpartition() method searches for the last occurrence of a specified string, and splits the string into a tuple containing three elements.The first element contains the part before the specified string.The second element contains the specified string.The third element contains the part after the string.
Syntax:
string.rpartition(value)
| Parameter | Description |
|---|---|
| value | Required. The string to search for |
Code:
string_1 = "Python Programming is Python Programming"
x = string_1.rpartition("Python")
print(x)
Output:
('Python Programming is ', 'Python', ' Programming')
rsplit() Method
- The rsplit() method splits a string into a list, starting from the right.If no “max” is specified, this method will return the same as the split() method.Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax:
string.rsplit(separator, maxsplit)
| Parameter | Description |
|---|---|
| separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
| maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is “all occurrences” |
Code:
string_1 = "Long, Live, Python, Programming"
x = string_1.rsplit(",")
print(x)
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = string_1.rsplit(",",1)
print(x)
# setting the maxsplit parameter to 2, will return a list with 3 elements!
x = string_1.rsplit(",",2)
print(x)
# setting the maxsplit parameter to 3, will return a list with 4 elements!
x = string_1.rsplit(",",3)
print(x)
Output:
['Long', ' Live', ' Python', ' Programming'] ['Long, Live, Python', ' Programming'] ['Long, Live', ' Python', ' Programming'] ['Long', ' Live', ' Python', ' Programming']
rstrip() Method
- The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
Syntax:
string.rstrip(characters)
| Parameter | Description |
|---|---|
| characters | Optional. A set of characters to remove as trailing characters |
Code:
string_1 = "Python Programm ing"
x = string_1.rstrip("ing")
print(x)
Output:
Python Programm
split() Method
- The split() method splits a string into a list.You can specify the separator, default separator is any whitespace.Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax:
string.split(separator, maxsplit)
| Parameter | Description |
|---|---|
| separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
| maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is “all occurrences” |
Code:
#Split the string, using comma, followed by a space, as a separator:
string_1 = "I, love, Python, Programming"
x = string_1.split(", ")
print(x)
string_2 = "I#love#Python#Programming"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = string_2.split("#", 1)
print(x)
Output:
['I', 'love', 'Python', 'Programming'] ['I', 'love#Python#Programming']
splitlines() Method
- The splitlines() method splits a string into a list. The splitting is done at line breaks.
Syntax:
string.splitlines(keeplinebreaks)
| Parameter | Description |
|---|---|
| keeplinebreaks | Optional. Specifies if the line breaks should be included (True), or not (False). Default value is not (False) |
Code:
string_1 = "I\nLove\nPython Programming" x = string_1.splitlines(True) print(x) y = string_1.splitlines(False) print(y)
Output:
['I\n', 'Love\n', 'Python Programming'] ['I', 'Love', 'Python Programming']
startswith() Method
- The startswith() method returns True if the string starts with the specified value, otherwise False.
Syntax:
string.startswith(value, start, end)
| Parameter | Description |
|---|---|
| value | Required. The value to check if the string starts with |
| start | Optional. An Integer specifying at which position to start the search |
| end | Optional. An Integer specifying at which position to end the search |
Code:
#Check if position 2 to End of string, starts with the characters "thon"
string_1 = "Python Programming"
x = string_1.startswith("thon", 2, len(string_1))
print(x)
Output:
False
strip() Method
- The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove)
Syntax:
string.strip(characters)
| Parameter | Description |
|---|---|
| characters | Optional. A set of characters to remove as leading/trailing characters |
Code:
string_1 = ",,,,,Python Programming@@@@@"
x = string_1.strip(",@")
print(x)
Output:
Python Programming
swapcase() Method
- The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
Syntax:
string.swapcase()
Code:
string_1 = "Python Programming" string_2 = "I LOVE PYTHON" string_3 = "python is cool" x = string_1.swapcase() print(x) x = string_2.swapcase() print(x) x = string_3.swapcase() print(x)
Output:
pYTHON pROGRAMMING i love python PYTHON IS COOL
title() Method
- The title() method returns a string where the first character in every word is upper case. Like a header, or a title.If the word contains a number or a symbol, the first letter after that will be converted to upper case.
Syntax:
string.title()
Code:
string_1 = "python programming" string_2 = "i love pYthon" string_3 = "Python is cOOL" x = string_1.title() print(x) x = string_2.title() print(x) x = string_3.title() print(x)
Output:
Python Programming I Love Python Python Is Cool
upper() Method
- The upper() method returns a string where all characters are in upper case.Symbols and Numbers are ignored.
Syntax:
string.upper()
Code:
string_1 = "python programming" string_2 = "i love pYthon" string_3 = "Python is cOOL" x = string_1.upper() print(x) x = string_2.upper() print(x) x = string_3.upper() print(x)
Output:
PYTHON PROGRAMMING I LOVE PYTHON PYTHON IS COOL
zfill() Method
- The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.If the value of the len parameter is less than the length of the string, no filling is done.
Syntax:
string.zfill(len)
| Parameter | Description |
|---|---|
| len | Required. A number specifying the position of the element you want to remove |
Code:
a = "Python" b = "Welcome to the world of Python Programming" c = "109.87" print(a.zfill(10)) print(b.zfill(10)) print(c.zfill(10))
Output:
0000Python Welcome to the world of Python Programming 0000109.87
Python lesson: List in Python 3
Working with list
List literals are enclosed within square brackets. A list can store data in the form of a string literal, integer or any allowed data type in Python. The first element of the list can be accessed using index 0. We can traverse a list using for loop and can process or manipulate the individual element stored in the list. There are different methods or operations that can be performed on the list such as append, insert, extend, index, remove, sort, reverse, pop. We will also discover the use of an empty list. A list can also be used as a single dimensional array or multi-dimensional array.
STORE ITEMS, TRAVERSE LIST, ACCESS USING INDEX
The following code demonstrates how to store items in a list, how to traverse a list, how to access elements of a list using index.
Code:
Nordic_Country_List = ["FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS"]
Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"]
for i in Nordic_Country_List:
print(i, end=" ")
print("\n")
for i in Asian_Country_List:
print(i, end=" ")
print("\n")
#Lets calculate the size of the List
#Then we access element of List using index
Nordic_length = len(Nordic_Country_List)
Asian_length = len(Asian_Country_List)
for i in range(Nordic_length):
print(Nordic_Country_List[i], end=" ")
print("\n")
for i in range(Asian_length):
print(Asian_Country_List[i], end=" ")
Output:
FINLAND ICELAND NORWAY DENMARK SWEDEN FAROE ISLANDS CHINA INDIA INDONESIA PAKISTAN BANGLADESH JAPAN PHILIPPINES VIETNAM FINLAND ICELAND NORWAY DENMARK SWEDEN FAROE ISLANDS CHINA INDIA INDONESIA PAKISTAN BANGLADESH JAPAN PHILIPPINES VIETNAM
Append, Insert, Extend, Index, Remove, Sort, Reverse, Pop.
Syntax:
list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original. list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right. list.extend(list2) -- adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend(). list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError). list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present) list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.) list.reverse() -- reverses the list in place (does not return it) list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
Code:
Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"]
#append element at end of list
Asian_Country_List.append('Thailand')
print(Asian_Country_List)
#insert element at index 0
Asian_Country_List.insert(0, 'Malaysia')
print(Asian_Country_List)
#add list of elements at end
Asian_Country_List.extend(['North Korea', 'South Korea'])
print(Asian_Country_List)
print(Asian_Country_List.index('INDONESIA'))
#search and remove that element
Asian_Country_List.remove('BANGLADESH')
print(Asian_Country_List)
#Remove third element in the list
Asian_Country_List.pop(2)
print(Asian_Country_List)
#sorts the list in place (does not return it)
Asian_Country_List.sort()
print(Asian_Country_List)
#reverses the list in place (does not return it)
Asian_Country_List.reverse()
print(Asian_Country_List)
Output:
['CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand'] ['Malaysia', 'CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand'] ['Malaysia', 'CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand', 'North Korea', 'South Korea'] 3 ['Malaysia', 'CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand', 'North Korea', 'South Korea'] ['Malaysia', 'CHINA', 'INDONESIA', 'PAKISTAN', 'JAPAN', 'PHILIPPINES', 'VIETNAM', 'Thailand', 'North Korea', 'South Korea'] ['CHINA', 'INDONESIA', 'JAPAN', 'Malaysia', 'North Korea', 'PAKISTAN', 'PHILIPPINES', 'South Korea', 'Thailand', 'VIETNAM'] ['VIETNAM', 'Thailand', 'South Korea', 'PHILIPPINES', 'PAKISTAN', 'North Korea', 'Malaysia', 'JAPAN', 'INDONESIA', 'CHINA']
Empty List
One popular trick is to use an empty list [] and use an “append” or “extend” method to add elements to the list.
Code:
Nordic_Country_List = ["FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS"]
Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"]
Country_List = []
for i in range(0, 5):
Country_List.append(Asian_Country_List[i])
print(Country_List)
Country_List_2 = []
Country_List_2.extend(Nordic_Country_List)
print(Country_List_2)
Country_List_3 = []
Country_List_3.extend(["CHINA", "INDIA", "INDONESIA"])
print(Country_List_3)
Output:
['CHINA', 'INDIA', 'INDONESIA', 'PAKISTAN', 'BANGLADESH'] ['FINLAND', 'ICELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS'] ['CHINA', 'INDIA', 'INDONESIA']
List Slices
Slices work on lists just as with strings, and can also be used to change sub-parts of the list.
Code:
Nordic_Country_List = ["FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS"] Asian_Country_List = ["CHINA", "INDIA", "INDONESIA", "PAKISTAN", "BANGLADESH", "JAPAN", "PHILIPPINES", "VIETNAM"] #Replacing first two items in the list with "GREENLAND" Nordic_Country_List[0:1] = ["GREENLAND"] print(Nordic_Country_List) #Replacing first three items in the list with TWO ITEMS "GREENLAND" and "IRELAND" Nordic_Country_List[0:2] = ["GREENLAND", "IRELAND"] print(Nordic_Country_List) #Replacing first four items in the list with TWO ITEMS "GREENLAND" and "IRELAND" Nordic_Country_List[0:4] = ["GREENLAND", "IRELAND"] print(Nordic_Country_List)
Output:
['GREENLAND', 'ICELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS'] ['GREENLAND', 'IRELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS'] ['GREENLAND', 'IRELAND', 'SWEDEN', 'FAROE ISLANDS']
Negative indexes in List
We can use negative indexes to access the list elements from the end. -1 to access the last element, -2 to access second last and so on.
Using Positive index 0 to n-1 from first to the last element. Using Negative index -1 to -n from the last element to the first.
In the below code, we will demonstrate, how to initialize a tuple and traverse the list using a for loop.
a = [1, 2, 3, 4, 5, 6]
a_length = -len(a)
for i in range(-1, a_length-1, -1):
print(a[i])
Output:
6 5 4 3 2 1
Multidimensional List
We can use nest lists within lists. With the help of a single-dimensional list, we can use the concept of an array. Similarly using the concept of a Multidimensional list we can use the concept of Multidimensional array.
Code:
a = [1, 2, 3] # 1Dimensional LIST of order 1 by 3
b = [5, 6, 6] # 1Dimensional LIST of order 1 by 3
c = [102, 5, -7] # 1Dimensional LIST of order 1 by 3
x1 = [[1, 2, 4], [2, 4, 5], [0, 0, 0]] # 2Dimensional LIST of order 3 by 3
x2 = [[5, 6, 7], [11, 14, 45], [90, 87, 73]] # 2Dimensional LIST 3 by 3
x3 = [[7, 11, 19], [15, 154, 415], [190, 807, 723]] # 2Dimensional LIST 3 by 3
d = [a, b, c] # 2Dimensional LIST of order 3 by 3
#D1 D2
D1 = len(d)
D2 = len(d[0])
for i in range(D1):
for j in range(D2):
print(d[i][j], end=" ")
print("\t")
print("\n")
x = [x1, x2, x3] # 3Dimensional LIST of order 3 by 3 by 3
#X1 X2
X1 = len(x)
X2 = len(x[0])
X3 = len(x[0][0])
for i in range(X1):
for j in range(X2):
for k in range(X3):
print(x[i][j][k], end=" ")
print("\t")
print("\n")
Output:
1 2 3 5 6 6 102 5 -7 1 2 4 2 4 5 0 0 0 5 6 7 11 14 45 90 87 73 7 11 19 15 154 415 190 807 723
Python lesson: Sets and Frozensets in Python 3
Working with Sets
You can think of sets in python equivalent to sets in Mathematics. A set is created by placing all the items (elements) inside curly braces {}, separated by a comma. A set can store data in the form of a string literal, integer or any allowed data type in Python. You cannot access elements of the set using an index. Though, you can traverse a set using for loop. There are different methods or operations that can be performed on sets such as union, update, intersection, intersection_update, difference, difference_update, symmetric_difference, symmetric_difference_update, issubset, issuperset and lot more.
Initializing and Traversing a Set
In the below code, we will demonstrate, how to initialize a set and traverse the set using for loop. Sets can be created using the function set().
Code:
a = {1, 2, 3}
for i in a:
print(i)
Output:
1 2 3
How to add elements to a Set
Sets are mutable. But since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Sets does not support it.
We can add a single element using the add() method and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided.
Code:
a = {1, 2, 3}
for i in a:
print(i)
a.add(4)
print(a)
#We are adding list as well as set to a set
#We are also trying to add duplicate element 1 to existing set
a.update([5, 6, 7], {1, 9, 10})
print(a)
Output:
1
2
3
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7, 9, 10}
Remove elements from a Set
A particular item can be removed from the set using methods, discard() and remove().
The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition.
Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.
We can also remove all items from a set using clear().
Code:
a_set = {1, 2, 3, 4, 5, 6}
print(a_set)
a_set.discard(3)
print(a_set)
a_set.remove(5)
print(a_set)
a_set.pop()
print(a_set)
a_set.clear()
print(a_set)
Output:
{1, 2, 3, 4, 5, 6}
{1, 2, 4, 5, 6}
{1, 2, 4, 6}
{2, 4, 6}
set()
Set Membership Test
We can test if an item exists in a set or not, using the keyword in
Code:
a_set = {1, 2, 3, 4, 5, 6}
print(1 in a_set)
print(101 in a_set)
Output:
True False
Set Operations similar to Mathematics
Set Union operation
Union of two sets X and Y is a set of all unique elements from both sets.
A union is performed using | operator. The same can be accomplished using the method union().
Code:
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}
c_set = a_set | b_set
print(c_set)
c_set = a_set.union(b_set)
print(c_set)
Output:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Set Intersection operation
The intersection of two sets X and Y is a set of elements that are common in both sets.
The intersection is performed using & operator. The same can be accomplished using the method intersection().
Code:
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}
c_set = a_set & b_set
print(c_set)
c_set = a_set.intersection(b_set)
print(c_set)
Output:
{1}
{1}
Set Difference operation
A difference of two sets X and Y refers to (X – Y) is a set of elements that are only in X but not in Y. Similarly, Y – X is a set of the element in Y but not in X.
The difference is performed using – minus operator. The same can be accomplished using the method difference().
Code:
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}
c_set = a_set - b_set
print(c_set)
c_set = a_set.difference(b_set)
print(c_set)
d_set = b_set - a_set
print(d_set)
d_set = b_set.difference(a_set)
print(d_set)
Output:
{2, 3, 4, 5, 6}
{2, 3, 4, 5, 6}
{8, 9, 10, 7}
{8, 9, 10, 7}
Set Symmetric Difference operation
Symmetric Difference of two sets X and Y is a set of elements in both X and Y except those that are common in both.
The symmetric difference is performed using ^ operator. The same can be accomplished using the method symmetric_difference().
Code:
a_set = {1, 2, 3, 4, 5, 6}
b_set = {1, 7, 8, 9, 10}
c_set = a_set ^ b_set
print(c_set)
c_set = a_set.symmetric_difference(b_set)
print(c_set)
Output:
{2, 3, 4, 5, 6, 7, 8, 9, 10}
{2, 3, 4, 5, 6, 7, 8, 9, 10}
Other Functions you can try
| Function Name | Description |
|---|---|
| add() | Adds an element to the set |
| copy() | Returns a copy of the set |
| difference_update() | Removes all elements of another set from this set |
| intersection_update() | Updates the set with the intersection of itself and another |
| isdisjoint() | Returns True if two sets have a null intersection |
| issubset() | Returns True if another set contains this set |
| issuperset() | Returns True if this set contains another set |
| symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used with set to perform different tasks.
| Name of Function | Usage |
|---|---|
| all() | Return True if all elements of the set are true (or if the set is empty). |
| any() | Return True if any element of the set is true. If the set is empty, return False. |
| enumerate() | Return an enumerate object. It contains the index and value of all the items of set as a pair. |
| len() | Return the length (the number of items) in the set. |
| max() | Return the largest item in the set. |
| min() | Return the smallest item in the set. |
| sorted() | Return a new sorted list from elements in the set(does not sort the set itself). |
| sum() | Return the sum of all elements in the set. |
Code:
a_set = {10, 3, 4, 0, 9, 123, -1, 3}
print(any(a_set))
print(all(a_set))
print(enumerate(a_set))
print(len(a_set))
print(max(a_set))
print(min(a_set))
print(sorted(a_set))
print(sum(a_set))
Output:
True False <enumerate object at 0x000001C818F6F1D8> 7 123 -1 [-1, 0, 3, 4, 9, 10, 123] 148
Working with Frozenset
Set elements or values can be modified and changed. Sometimes, we need to use values that do not require modification or updation once assigned. Frozensets are immutable sets whose values cannot be changed once assigned. Sets being mutable are unhashable, so they can’t be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the function frozenset().
This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not have method that add or remove elements.
Code:
A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) X = frozenset([1, 2]) c = A.union(B) print(c) c = A.difference(B) print(c) c = A.intersection(B) print(c) c = A.isdisjoint(B) print(c) c = X.issubset(A) print(c) c = A.issuperset(X) print(c) c = A.union(B) print(c)
Output:
frozenset({1, 2, 3, 4, 5, 6})
frozenset({1, 2})
frozenset({3, 4})
False
True
True
frozenset({1, 2, 3, 4, 5, 6})
Python lesson: Tuples in Python 3
Working with Tuples
Unlike Lists, Tuples are immutable lists, that cannot be modified. A Tuple is created by placing all the items (elements) inside () parenthesis, separated by commas. A Tuple can store data in the form of a string literal, integer or any allowed data type in Python. A tuple can have heterogeneous data items, a tuple can have string and list as data items as well. You can access elements of the tuple using an index. Traverse a tuple using the loop. Nested tuples can be created. Like Lists, we can use slicing with Tuples. There are different methods or operations that can be performed on tuples such as Changing the elements of a tuple, delete operation, membership test, etc.
First of all, we will start with listing difference between Tuples and Lists
Difference b/w List & Tuple
| List | Tuple |
|---|---|
| Elements of a list are Mutable | Elements of a tuple are immutable. |
| When you need to change data over time, list is used. | When you need to use data that does not changes over time, tuple is used. |
| Traversing items in a List is slow as compared to Tuple. | Traversing items in a Tuple is fast as compared to List. |
| Elements of list are enclosed in square bracket. | Elements of a tuple are enclosed in parenthesis. |
Initializing and Traversing a Tuple using index & Loop
In the below code, we will demonstrate, how to initialize a tuple and traverse the tuple using a for loop.
Code:
a = (1, 2, 3, 4, 5, 6)
a_length = len(a)
for i in range(a_length):
print(a[i])
Output:
1 2 3 4 5 6
Negative indexes in tuples
Similar to list and strings we can use negative indexes to access the tuple elements from the end. -1 to access the last element, -2 to access second last and so on.
Using Positive index 0 to n-1 from first to the last element. Using Negative index -1 to -n from last element to the first.
In the below code, we will demonstrate, how to initialize a tuple and traverse the tuple using a for loop.
Code:
a = (1, 2, 3, 4, 5, 6)
a_length = -len(a)
for i in range(-1, a_length-1, -1):
print(a[i])
Output:
6 5 4 3 2 1
Using Nested tuples
Code:
a = (1, 2, 3) # 1Dimensional TUPLE of order 1 by 3
b = (5, 6, 6) # 1Dimensional TUPLE of order 1 by 3
c = (102, 5, -7) # 1Dimensional TUPLE of order 1 by 3
x1 = ((1, 2, 4), (2, 4, 5), (0, 0, 0)) # 2Dimensional TUPLE of order 3 by 3
x2 = ((5, 6, 7), (11, 14, 45), (90, 87, 73)) # 2Dimensional TUPLE 3 by 3
x3 = ((7, 11, 19), (15, 154, 415), (190, 807, 723)) # 2Dimensional TUPLE 3 by 3
d = (a, b, c) # 2Dimensional TUPLE of order 3 by 3
#D1 D2
D1 = len(d)
D2 = len(d[0])
for i in range(D1):
for j in range(D2):
print(d[i][j], end=" ")
print("\t")
print("\n")
x = [x1, x2, x3] # 3Dimensional TUPLE of order 3 by 3 by 3
#X1 X2
X1 = len(x)
X2 = len(x[0])
X3 = len(x[0][0])
for i in range(X1):
for j in range(X2):
for k in range(X3):
print(x[i][j][k], end=" ")
print("\t")
print("\n")
Output:
1 2 3 5 6 6 102 5 -7 1 2 4 2 4 5 0 0 0 5 6 7 11 14 45 90 87 73 7 11 19 15 154 415 190 807 723
Changing & Deleting Elements of a Tuple
We cannot change the elements of a tuple because tuple itself is immutable. However, we can change the elements of nested items that are mutable. For example, in the following code, we are changing the element of the list which is present inside the tuple. List items are mutable that’s why it is allowed.
Tuple elements are immutable which also means that we cannot delete the elements of a tuple. However, deleting entire tuple is possible.
Code:
a = (1, 2, 3, ["I", "Love", "Python"], 4, 5, 6) print(a) a[3][0], a[3][1], a[3][2] = "You", "Hate", "Python" print(a) del a #You will get error, as the tuple is deleted print(a)
Output:
(1, 2, 3, ['I', 'Love', 'Python'], 4, 5, 6)
(1, 2, 3, ['You', 'Hate', 'Python'], 4, 5, 6)
Traceback (most recent call last):
File "practise.py", line 10, in <module>
print(a)
NameError: name 'a' is not defined
Slicing in Tuple
Slices work on Tuple just as with strings and lists, and can also be used to change sub-parts of the Tuple.
Code:
Nordic_Country_Tuple = ("FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS")
print(Nordic_Country_Tuple[0:1])
print(Nordic_Country_Tuple[0:2])
print(Nordic_Country_Tuple[0:4])
# displaying entire tuple
print(Nordic_Country_Tuple[:])
print(Nordic_Country_Tuple[4:-1])
Output:
('FINLAND',)
('FINLAND', 'ICELAND')
('FINLAND', 'ICELAND', 'NORWAY', 'DENMARK')
('FINLAND', 'ICELAND', 'NORWAY', 'DENMARK', 'SWEDEN', 'FAROE ISLANDS')
('SWEDEN',)
Membership Test in Tuples
in: Checks whether an element exists in the specified tuple.
not in: Checks whether an element does not exist in the specified tuple.
Code:
Nordic_Country_Tuple = ("FINLAND", "ICELAND", "NORWAY", "DENMARK", "SWEDEN", "FAROE ISLANDS")
print("FINLAND" in Nordic_Country_Tuple)
print("ICELAND" in Nordic_Country_Tuple)
print("FAROE ISLANDS" not in Nordic_Country_Tuple)
print("DENMARK" not in Nordic_Country_Tuple)
Output:
True True False False
Python lesson: Dictionaries in Python 3
Working with Dictionaries
Dictionary can store data like lists but instead of using only numbers to get the data, you can use almost anything. A dictionary has a concept of a key, with the help of key you are able to access the data. Thus, you can refer to the dictionary as a database for storing and organizing data. Dictionary data can be accessed using keys. The key makes sense because data stored in the dictionary is stored in the form of pairs. Where each pair containing two information Key: Value
If keys are used as a number from 0 to n-1 for n pairs. Then, value accessed using keys is similar to value accessed in the list using indexing.
Example:
sample_dictionary_data = { 0: “pink”, 1: “red”}
While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. A dictionary associates one thing to another, no matter what it is. In this post, we will learn how to create a dictionary & store data using a dictionary. How to access elements from a dictionary, change or add elements in a dictionary, delete or remove elements from a dictionary. Traversing a dictionary, using methods with a dictionary. You will also learn about Dictionary Comprehension, Dictionary Membership Test, Built-in Functions with Dictionary.
Creating a dictionary
In the below code, we will demonstrate, how to create or initialize a dictionary. You will also learn the built-in function dict(), which is used to create a dictionary.
Code:
# empty dictionary
sample_dict = {}
print(sample_dict)
# dictionary with integer keys
sample_dict = {1: 'pink', 2: 'red'}
print(sample_dict)
# dictionary with mixed keys
sample_dict = {'name': 'Pythonbaba', "Role": ["Programmer", "Teacher", "Writer"]}
print(sample_dict)
# using dict()
sample_dict = dict({"color1": 'pink', "color2": 'red'})
print(sample_dict)
# from sequence having each item as a pair
sample_dict = dict([("color1", 'pink'), ("color2", 'red')])
print(sample_dict)
Output:
{}
{1: 'pink', 2: 'red'}
{'name': 'Pythonbaba', 'Role': ['Programmer', 'Teacher', 'Writer']}
{'color1': 'pink', 'color2': 'red'}
{'color1': 'pink', 'color2': 'red'}
Access element using Key
You can normally access Dictionary value using indexing as we have done with lists and tuples. You can also use a key placed in quotes inside square brackets or get() method and retrieve the value linked with a key.
Code:
#When Keys are used as integers
#You can access Dictionary value using indexing
sample_dict = {0: 'pink', 1: 'red'}
print(sample_dict)
print(sample_dict[0])
print(sample_dict[1])
print(sample_dict.get(0))
print(sample_dict.get(1))
sample_dict = {'name': 'Pythonbaba', "Role": ["Programmer", "Teacher", "Writer"]}
print(sample_dict)
print(sample_dict["name"])
print(sample_dict.get("name"))
print(sample_dict["Role"])
print(sample_dict["Role"][0])
print(sample_dict.get(["Role"][0]))
print(sample_dict["Role"][1])
print(sample_dict["Role"][0:1])
print(sample_dict["Role"][1:2])
print(sample_dict["Role"][0:2])
print(sample_dict["Role"][:])
Output:
{0: 'pink', 1: 'red'}
pink
red
pink
red
{'name': 'Pythonbaba', 'Role': ['Programmer', 'Teacher', 'Writer']}
Pythonbaba
Pythonbaba
['Programmer', 'Teacher', 'Writer']
Programmer
['Programmer', 'Teacher', 'Writer']
Teacher
['Programmer']
['Teacher']
['Programmer', 'Teacher']
['Programmer', 'Teacher', 'Writer']
Traversing a Dictionary
Testing if a key is present in the dictionary or not using Membership operators in and not in. Membership operators are only used for keys and not for testing values.
Code:
sample = {"color1": 'pink', "color2": 'red', "color3": 'green', "color4": 'blue'}
cube_values = {a: a* a * a for a in range(5)}
print(cube_values)
for i in cube_values:
print(i, ":", cube_values[i])
print(sample)
for i in sample:
print(i, ":", sample[i])
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
0 : 0
1 : 1
2 : 8
3 : 27
4 : 64
{'color1': 'pink', 'color2': 'red', 'color3': 'green', 'color4': 'blue'}
color1 : pink
color2 : red
color3 : green
color4 : blue
Change or add elements in a dictionary
Dictionary is mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, the value gets updated, else a new key: value pair is added to the dictionary.
Code:
sample_dict = {0: 'pink', 1: 'red'}
print(sample_dict)
sample_dict[1] = "Navy Blue"
sample_dict["color2"] = "Saffron"
sample_dict["3"] = "Green"
print(sample_dict)
Output:
{0: 'pink', 1: 'red'}
{0: 'pink', 1: 'Navy Blue', 'color2': 'Saffron', '3': 'Green'}
Delete or remove elements from a dictionary
We can remove a particular item in a dictionary by using the method pop(). This method removes an item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
Code:
sample = {1: 'pink', 2: 'red', 3: 'green', 4: 'blue', 5: 'saffron' }
print(sample)
# remove a particular item
print(sample.pop(4))
print(sample)
# remove an arbitrary item
print(sample.popitem())
print(sample)
# delete a particular item
del sample[1]
print(sample)
# remove all items
sample.clear()
print(sample)
# delete the dictionary itself
del sample
Output:
{1: 'pink', 2: 'red', 3: 'green', 4: 'blue', 5: 'saffron'}
blue
{1: 'pink', 2: 'red', 3: 'green', 5: 'saffron'}
(5, 'saffron')
{1: 'pink', 2: 'red', 3: 'green'}
{2: 'red', 3: 'green'}
{}
Using methods with Dictionaries
| Name of the method | Usage |
|---|---|
| clear() | Remove all items form the dictionary. |
| copy() | Return a shallow copy of the dictionary. |
| fromkeys(seq[, v]) | Return a new dictionary with keys from seq and value equal to v (defaults to None). |
| get(key[,d]) | Return the value of key. If key doesnot exit, return d (defaults to None). |
| items() | Return a new view of the dictionary's items (key, value). |
| keys() | Return a new view of the dictionary's keys. |
| pop(key[,d]) | Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. |
| popitem() | Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty. |
| setdefault(key[,d]) | If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). |
| update([other]) | Update the dictionary with the key/value pairs from other, overwriting existing keys. |
| values() | Return a new view of the dictionary's values |
Dictionary Comprehension
Dictionary comprehension is the easiest way to create a dictionary using an expression. An expression that contains pair (key: value) followed by for statement inside curly braces {}.
Code:
cube_values = {a: a*a*a for a in range(5)}
print(cube_values)
#The above code is similar to
# cube_values = {}
# for a in range(5):
# cube_values[a] = a*a*a
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
Dictionary Membership Test
Testing if a key is present in the dictionary or not using Membership operators in and not in. Membership operators are only used for keys and not for testing values.
Code:
cube_values = {a: a*a*a for a in range(5)}
print(cube_values)
print(2 in cube_values)
print(4 in cube_values)
print(27 in cube_values)
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
True
True
False
Built-in Functions used with Dictionary
We will discuss the following functions:
| Name of Function | Usage |
|---|---|
| all() | Return True if all keys of the dictionary are true (or if the dictionary is empty). |
| any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False. |
| len() | Return the length (the number of items) in the dictionary. |
| sorted() | Return a new sorted list of keys in the dictionary. |
Code:
sample = {4: 'pink', 3: 'red', 1: 'green', 2: 'blue'}
cube_values = {a: a*a*a for a in range(5)}
cube_2 = cube_values
print(cube_values)
print(all(cube_values))
print(any(cube_values))
print(len(cube_values))
print(sorted(sample))
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
False
True
5
[1, 2, 3, 4]
{4: 'pink', 3: 'red', 1: 'green', 2: 'blue'}
Python lesson: Modules in Python 3
Working With Modules
Before proceeding to learn classes in Python, we would like to discuss modules and how to import modules in our Python Program.
What is a module?
A module is a Python script file, that consists of functions, classes, and data (variables or immutable data). At, current moment forget about classes and just focus on functions and data, that we have already discussed.
Why do we need modules?
It is cumbersome to write a large number of lines of codes in a single file. Also, when we like to use functions written by other programmers we need to import their files. In order to group related code and data, we simply write related codes in separate Python script.
Based on our current Python script requirement, we simply import individual functions or complete modules (Python script file), to use in our program.
How to import the module in our Python Script?
We would like to explain things to you from scratch. So, instead of importing the existing module, we will build a module/Python script and then we will import in another Python Program or Script.
Creating a calculator.py Module
The below code is an aggregation of four different functions, that provide basic operations of a calculator such as addition, multiplication, subtraction, division
Code:
def add(a, b):
c = a + b
return c;
def sub(a, b):
c = a - b
return c;
def mul(a, b):
c = a * b
return c;
def div(a, b):
c = a / b
return c;
How to import module in a Python Script/Program
- In order to import a Python module, the module must be placed in the current directory or the default path where python is installed.
- Now there are two methods to access the functions in the module with or without a dot. operator.
Without Using dot operator
- If you want to import all the functions from calculator.py in your current program use
- from calculator import *
- If you want to import specific function from caluclator.py in your current program use
- from calculator import add
Code:
#import all the functions from calculator.py from calculator import * print(add(3, 4)) print(mul(3, 4)) print(sub(3, 4)) print(div(3, 4))
Output:
7 12 -1 0.75
Code:
#import specific function from caluclator.py from calculator import add print(add(91, 909)) #We will get error if we will use any other function print(mul(91, 909))
Output:
1000
Traceback (most recent call last):
File "practise.py", line 7, in <module>
print(mul(91, 909))
NameError: name 'mul' is not defined
Using dot operator
- If you want to import all the functions from calculator.py in your current program use
- import calculator
Code:
#import all function from caluclator.py import calculator #We need to access function using the dot operator print(calculator.add(91, 909)) #We need to access function using the dot operator print(calculator.mul(91, 909))
Output:
1000 82719
Difference b/w Modules and Packages
Ideally, we access the function using a dot operator. The scenario which we discussed above makes you understand how to import a single module. In practical, we deal with a package and not an individual Python file. The package is a collection of Python module or Scripts (.py) whereas a module is a single Python Script (.py). A package is a directory of different Python modules/scripts containing an additional __init__.py file, which is needed to distinguish a package from a directory that only consists of Python scripts.
So, you must be excited to build your own Python package, which consists of different modules and an additional __init__.py file. We advise you to learn the concept of classes in the next section, after that we will learn how to build a package.
Python lesson: Class, Inheritance, Encapsulation, Composition
Working With Classes
Before proceeding to build Packages in Python, we would like to discuss classes and how to write classes in our Python Program.
What is a class?
We all have heard about Object-Oriented Programming. Implementation of a Class in any programming language helps us to achieve the concept of the OOPs. A class consists of functions and data, which works as a blueprint, whenever we need to use the associated function and data in a given class, we create an object, which contains its local copy of function and data. So, we are able to access the function and data using object_name and dot operator.
Why Class is needed when the concept of function is already there?
There are many important concepts we realize through the implementation of classes such as Data Abstraction, Data Hiding, Inheritance, Polymorphism. You need to study Object-oriented programming if you want to go in detail.
One important fundamental: Whenever we import a module, which does not contain any class i.e. a simple python script with function and data. We import the function itself, so any other python program that wants to execute this module at the same time can produce unexpected results. Because two python programs will simultaneously share the resources of the given module.
But in the case of Class, we are free to do so, because class gives access to its function and data only through an object. And each object has its own local copy of function and data. Though some data can be shared between classes if we want to, which is further implementation of the OOPs concept.
How to write a Class in Python and access it?
Before proceeding further: just remember these points.
Writing a class:
Simply imagine you are writing a single function or group of functions using data.
PseudoCode:
class class_name(object)
def __init__(self, arg1, arg2, arg3, .., .., argN):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
self.argN = argN
def function_name_1(self):
print("I AM {} Color".format(self.arg1))
def function_name_2(self):
print("I AM {} Color".format(self.arg2))
def function_name_3(self):
print("I AM {} Color".format(self.arg3))
def function_name_N(self):
print("I AM {} Color".format(self.argN))
Please note: In the above code class, object, self, def, __init__ are reserved keyword and you need to remember these keywords for writing a class.
class_name, function_name_1, function_name_2, function_name_3, function_name_4 can be named anything (based on your choice) in compliance with permitted namespace in Python.
What is the use of self keyword: In the above code you can see self keyword repeating a lot of times. We are creating an object that contains a local copy of data variables, thus we use the self keyword where each object refers to its own data and associated function.
How to access it:
We need to create an object for a given class. When creating an object we can pass arguments to initialize data. Then we will access all the data and function using:
PseudoCode:
#Creating an Object & initializing with N arguments first_object = class_name(arg1, arg2, arg3, .., .., argN) #Calling function_name_1 first_object.function_name_1() #Calling function_name_2 first_object.function_name_2() #Calling function_name_3 first_object.function_name_3() #Calling function_name_N first_object.function_name_N()
Implementation of Calculator Python Program using Class:
Initializing Parameters while creating an object
Code:
class Calculator(object):
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def sub(self):
return self.a - self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
calc_obj = Calculator(99, 3)
print("Addition result is {}".format(calc_obj.add()))
print("Multiplication result is {}".format(calc_obj.mul()))
print("Division result is {}".format(calc_obj.div()))
print("Subtraction result is {}".format(calc_obj.sub()))
Output:
Addition result is 102 Multiplication result is 297 Division result is 33.0 Subtraction result is 96
Encapsulation, IS-A (Inheritance), HAS-A (Composition)
Encapsulation
Encapsulation: When we want to hide some data from other objects or we want to restrict access to some methods and variables. The concept of Encapsulation helps us to prevent direct manipulation or modification of data. Only, the function has access to private data. We hide attributes by making them private. In Python, we hide it by placing underscore as the prefix for the attribute, i.e single “ _ “ or double “ __“
In the below code, we have demonstrated that private class data can only be manipulated using class functions and not using an object.
Code:
class Color:
def __init__(self):
self.__color_name = "Green"
def Color_Type(self):
print("Color Type is : {}".format(self.__color_name))
def Color_Type_1(self, price):
self.__color_name = "Red"
c = Color()
c.Color_Type()
# changing the Color
c.__color_name = "Blue"
c.Color_Type()
# Setting color using Function
c.Color_Type_1(1000)
c.Color_Type()
Output:
Color Type is : Green Color Type is : Green Color Type is : Red
IS-A Relationship (Inheritance)
IS-A Relationship: Salmon is a Fish. It means Salmon inherit properties from a Fish. When a child class inherits the property of a parent class. We refer to it as a Parent-Child relationship.
There are three ways in which parent and child class can interact:
- Actions on the child imply an action on the parent: Implicit behavior
- Actions on the child override the action on the parent: Override Explicitly
- Actions on the child alter the action on the parent: Alter Before or After
Actions on the child imply an action on the parent: Implicit behavior
Implicit actions that happen when you define a function in the parent but not in
the child.
Code:
class Parent(object):
def function_parent(self):
print("I am parent")
class Child(Parent):
pass
a = Parent()
b = Child()
a.function_parent()
b.function_parent()
Output:
I am parent I am parent
Actions on the child override the action on the parent: Override Explicitly
Code:
class Parent(object):
def function(self):
print("I am parent")
class Child(Parent):
def function(self):
print("I am Child")
a = Parent()
b = Child()
a.function()
b.function()
Output:
I am parent I am Child
Actions on the child alter the action on the parent: Alter Before or After
The third way to use inheritance is a special case of overriding where you want to alter the behavior before or after the Parent class’s version runs. You first override the function just like in the last example, but now we will use a Python built-in function named super to get the Parent version to call. Here’s the example of doing that so you can make sense of this description:
Code:
class Parent(object):
def function(self):
print("I am parent")
class Child(Parent):
def function(self):
print("I am CHILD, BEFORE PARENT is called")
super(Child, self).function()
print("I am CHILD, AFTER PARENT is called")
a = Parent()
b = Child()
a.function()
b.function()
Output:
I am parent I am CHILD, BEFORE PARENT is called I am parent I am CHILD, AFTER PARENT is called
Demonstration of super for initialization and function calling from Child class
Using super() with __init__
Code:
class Cube(object):
def __init__(self, arg):
self.arg = arg
def CubeFunction(self):
self.CubeResult = self.arg * self.arg * self.arg
class CubeAdd(Cube):
def __init__(self, arg, arg1):
super().__init__(arg)
self.arg1 = arg1
def CubeAddFunction(self):
super(CubeAdd, self).CubeFunction()
self.CubeAddResult = self.CubeResult + self.arg1
b = CubeAdd(2,1)
b.CubeAddFunction()
print(b.CubeAddResult)
b = CubeAdd(3,1)
b.CubeAddFunction()
print(b.CubeAddResult)
b = CubeAdd(4,1)
b.CubeAddFunction()
print(b.CubeAddResult)
Output:
9 28 65
HAS-A Relationship (Composition)
HAS-A Relationship: A dog is a mammal and Parrot is a Bird. Dog inherits features from Mammal parent class and Parrot inherits features from Bird parent class. Sometimes, one class does not inherit all the features from a class. But both dog and mammal have a mouth. It means they have some common properties but do not inherit all. So, we achieve this functionality through composition, we directly call a function from another class, without inheriting all the featured from a class.
The following code demonstrate the use of Composition.
Code:
class Cube(object):
def __init__(self, arg):
self.arg = arg
def CubeFunction(self):
self.CubeResult = self.arg * self.arg * self.arg
class CubeAdd(Cube):
def __init__(self, arg, arg1):
self.arg1 = arg1
self.cube = Cube(arg)
def CubeAddFunction(self):
self.cube.CubeFunction()
self.CubeAddResult = self.cube.CubeResult + self.arg1
b = CubeAdd(2,1)
b.CubeAddFunction()
print(b.CubeAddResult)
b = CubeAdd(3,1)
b.CubeAddFunction()
print(b.CubeAddResult)
b = CubeAdd(4,1)
b.CubeAddFunction()
print(b.CubeAddResult)
Output:
9 28 65
