Python is a powerful, yet very simple, multi-purpose, high level programming language which is used in various aspect of technology. To cite but a few examples, Python is used in web developemnt, software development, and Data Science and Machine learning. This tutorial, which by the way,is beginner friendly, will explain all the fundamental concepts of python [programming.
Introduction to Python Programming language
Python is developed by Guido van Rossum. He named it Python after the comedy television show Monty Python’s Flying Circus. Guido van Rossum started implementing Python in 1989 and officially released in 1991.
Features of Python programming language
Readability: Python is a very readable language.
Easy to Learn: Learning python is easy as this is a expressive and high level programming language, which means it is easy to understand the language and thus easy to learn.
Cross platform: Python is available and can run on various operating systems such as Mac, Windows, Linux, Unix etc. This makes it a cross platform and portable language.
Open Source: Python is a open source programming language.
Large standard library: Python comes with a large standard library that has some handy codes and functions which we can use while writing code in Python.
Free: Python is free to download and use. This means you can download it for free and use it in your application. It is also open source which means you can freely distribute copies of this software, read its source code and modify it.
Supports exception handling: If you are new, you may wonder what is an exception? An exception is an event that can occur during program exception and can disrupt the normal flow of program. Python supports exception handling which means we can write less error prone code and can test various scenarios that can cause an exception later on.
Advanced features: Supports generators and list comprehensions. We will cover these features later.
Automatic memory management: Python supports automatic memory management which means the memory is cleared and freed automatically. You do not have to bother clearing the memory.
What we can do with Python
You may be wondering what all are the applications of Python. There are so many applications of Python, here are some of the them.
- Web development – Web framework like Django and Flask are based on Python. They help you write server side code which helps you manage database, write backend programming logic, mapping urls etc.
- Machine learning – There are many machine learning applications written in Python. Machine learning is a way to write a logic so that a machine can learn and solve a particular problem on its own. For example, products recommendation in websites like Amazon, Flipkart, eBay etc. is a machine learning algorithm that recognises user’s interest. Face recognition and Voice recognition in your phone is another example of machine learning.
- Data Analysis – Data analysis and data visualisation in form of charts can also be developed using Python.
- Scripting – Scripting is writing small programs to automate simple tasks such as sending automated response emails etc. Such type of applications can also be written in Python programming language.
- Game development – You can develop games using Python.
- Development Embedded applications.
- Desktop applications – You can develop desktop application in Python using library like TKinter or QT.
How to install Python
Python installation is pretty simple, you can install it on any operating system such as Windows, Mac OS X, Ubuntu etc.
To install the Python on your operating system, go to this link: which is the official Python website and it will detect the operating system and based on that it would recommend you to download Python. Always rememeber to download the latest version of Python (Python 3.8 or higher).
Installation steps are pretty simple. You just have to accept the agreement and finish the installation.
It must be noted, however, that most operating systems come with Python already installed. To check if you have python installed, go toyour terminal and type:
$ python --version
*Install an IDE *
In order to run Python code, you will need an IDE. Popular once include: VSCode, PyCharm, Atom, etc,. You can go ahead and install an IDE of your choice.
For newbies, IDE stands for Integrated Development Environment. It is a software that consolidates the basic tools that are required to write and test programs in a given language.
Typically, an IDE contains a code editor, a compiler or interpreter and a debugger. You can access all these at the same place through the IDE GUI.
Comments in Python Programming
Comments are an essential part of, not just Python, but any programming language. Although they do not change the outcome of a program.
A comment is text that doesn’t affect the outcome of a code, it is just a piece of text to let someone know what you have done in a program or what is being done in a block of code. This is especially helpful when someone else has written a code and you are analysing it for bug fixing or making a change in logic, by reading a comment you can understand the purpose of code much faster then by just going through the actual code.
To write a comment in Python, simply use a hashtag before the comment as shown below:
*# This is just a text, it won't be executed.*
print("Python comment example")
Output:
Python comment example*
Types of Comments in Python
There are two types of comments in Python.
- Single line comment
- Multiple line comment
Single line comment
In python we use # special character to start the comment as in shown below:
#This is just a comment. Anything written here is ignored by Python
Multi-line comment:
To have a multi-line comment in Python, we use triple single quotes at the beginning and at the end of the comment, as shown below.
*'''
This is a
multi-line
comment
*'''
Python Comments Example
In this Python program we are seeing three types of comments. Single line comment, multi-line comment and the comment that is starting in the same line after the code.
*'''
We are writing a simple program here
First print statement.
This is a multiple line comment.
'''
print("Hello World!")
# Second print statement
print("I’m learning python programming")
print("Welcome to the world of coding.") # Third print statement*
Output:
Hello World!
I’m learning python programming
Welcome to the world of coding.
NOTE: When # character is encountered inside quotes, it is not considered as comment. For example:
print("#this is not a comment")
**Output:*
#this is not a comment
Python Variables with examples
Variables are used to store data, they take memory space based on the type of value we assigning to them. Creating variables in Python is simple, you just have write the variable name on the left side of = and the value on the right side, as shown below. You do not have to explicitly mention the type of the variable, python infer the type based on the value we are assigning.
*number = 100 #number is of type int
str = "Mukumbuta" #str is of type string*
Identifiers in Python
There are some basic rules that one have to follow when naming variables (also known as Identifiers) in Python.
- The name of the variable must always start with either a letter or an underscore (_). For example: _str, str, num, _num are all valid name for the variables.
- The name of the variable cannot start with a number. For example: 9num is not a valid variable name.
- The name of the variable cannot have special characters such as %, $, # etc, they can only have alphanumeric characters and underscore (A to Z, a to z, 0-9 or _ ).
- Variable name is case sensitive in Python. this means number is different from NUM.
Python Variable Example
num = 100
str = "The Ultimate Guide"
print(num)
print(str)
Output:
100
The ultimate Guide
We can also assign multiple variables in a single statement in Python like so:
x = y = z = 99
print(x)
print(y)
print(z)
Output:
99
99
99
Concatination in python
*x = 10
y = 20
print(x + y)
p = "Hello"
q = "World"
print(p + " " + q)*
Output:
30
Hellow World
NOTE: If you attempt to use the + operator with variable x and p, the program will throw and error on your face that gose somethinglike:
unsupported operand type(s) for +: 'int' and 'str'
Data Types
A data type defines the type of data, for example 100 is an integer data while “Hello” is a String type of data. The data types in Python are divided in two categories:
- Immutable data types – Values cannot be changed.
- Mutable data types – Values can be changedImmutable data types in Python are:
- Strings
- Tuple
- Numbers Mutable data types in Python are:
- Dictionaries
- Lists
- Sets
Python Keywords and Identifiers with examples
In this article, we will discuss Keywords and Identifiers in Python with the help of examples.
A python keyword is a reserved word which you can’t use as a name of your variable, class, function etc. These keywords have a special meaning and they are used for special purposes in Python programming language. For example – Python keyword “while” is used for while loop thus you can’t name a variable with the name “while” else it may cause compilation error.
To get the list of keywords on your system, open command prompt (terminal on Mac OS) and type trhe following:
*$ Python 3.6
...
>>> help()
Welcome to Python 3.6's help utility!
...
help> keywords*
Output:
*Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass*
Example of Python keyword
In the following example we are using while keyword to create a loop for displaying the values of variables num as long as they are greater than 5.
num = 10
while num>5:
print(num)
num -= 1
Output:
10
9
8
7
6
Numeric Data Type in Python
Integers
In Python 3, there is no upper bound on the integer number which means we can have the value as large as our system memory allows.
# Integer number
num = 100
print(num)
print("Data Type of variable num is", type(num))
Output:
Long Data Type
Long data type is deprecated in Python 3 because there is no need for it, since the integer has no upper limit, there is no point in having a data type that allows larger upper limit than integers.
Float Data type
Values with decimal points are the float values, there is no need to specify the data type in Python. It is automatically inferred based on the value we are assigning to a variable. For example here fnum is a float data type.
# float number
fnum = 34.45
print(fnum)
print("Data Type of variable fnum is", type(fnum))
Output:
34.45
Data Type of variable fnum is, float
Complex Numbers
Numbers with real and imaginary parts are known as complex numbers. Unlike other programming language such as Java, Python is able to identify these complex numbers with the values. In the following example when we print the type of the variable cnum, it prints as complex number.
complex number
cnum = 3 + 4j
print(cnum)
print("Data Type of variable cnum is", type(cnum))
Output:
Python Data Type – String
String is a sequence of characters in Python. The data type of String in Python is called “str”.
Strings in Python are either enclosed with single quotes or double quotes.
_# Python program to print strings and type
f_word = "First String"
s_word = 'Second String'
# displaying string s and its type
print(f_word)
print(type(f_word))
# displaying string s_word and its type
print(s_word)
print(type(s_word))_
Output:
Python Data Type – Tuple
Tuple is immutable data type in Python which means it cannot be changed. It is an ordered collection of elements enclosed in round brackets and separated by commas.
_# tuple of integers
f_tuple = (1, 2, 3, 4, 5)
#prints entire tuple
print(f_tuple)
#tuple of strings
t2 = ("hi", "hello", "bye")
#loop through tuple elements
for s in t2:
print (s)
#tuple of mixed type elements
t3 = (2, "Lucy", 45, "Steve")
'''
Print a specific element
indexes start with zero
'''
print(t3[2])_
Output:
Python Data Type – List
List is similar to tuple, it is also an ordered collection of elements, however list is a mutable data type which means it can be changed unlike tuple which is an immutable data type.
A list is enclosed with square brackets and elements are separated by commas.
_# list of integers
f_list = [1, 2, 3, 4, 5]
#prints entire list
print(f_list)
#list of strings
s_list = ["Apple", "Orange", "Banana"]
# loop through list elements
for x in s_list:
print (x)
# List of mixed type elements
c_list = [20, "Mukumbuta", 15, "The Ultimate Guide"]
'''
Print a specific element in list
indexes start with zero
'''
print("Element at index 3 is:",c_list[3])_
Output:
Python Data Type – Dictionary
Dictionary is a collection of key and value pairs. A dictionary doesn’t allow duplicate keys but the values can be duplicate. It is an ordered, indexed and mutable collection of elements.
The keys in a dictionary doesn’t necessarily to be a single data type, as you can see in the following example that we have 1 integer key and two string keys.
_# Dictionary example
dict = {1:"Mukumbuta","lastname":"Singh", "age":31}
# prints the value where key value is 1
print(dict[1])
# prints the value where key value is "lastname"
print(dict["lastname"])
# prints the value where key value is "age"
print(dict["age"])_
Output:
Python Data Type – Set
A set is an unordered and unindexed collection of items. This means when we print the elements of a set they will appear in the random order and we cannot access the elements of set based on indexes because it is unindexed.
Elements of set are separated by commas and enclosed in curly braces.
*# Set Example
myset = {"hi", 2, "bye", "Hello World"}
# loop through set
for a in myset:
print(a)
# checking whether 2 exists in myset
print(2 in myset)
# adding new element
myset.add(99)
print(myset)_
Output:
Python conditionals
The If statement
If statements are control flow statements which helps us to run a particular code only when a certain condition is satisfied. For example, you want to print a message on the screen only when a condition is true then you can use if statement to accomplish this in programming. In this section, we will learn about the IF statement.
There are other control flow statements available in Python such as *if..else, if..elif..else,
nested if_ etc. However in this guide, we will only cover the if statements, other control statements are covered in separate tutorials.
Syntax of If statement in Python
The syntax of if statement in Python is pretty simple.
if condition:
block_of_code
Python – If statement Example
flag = True
if flag==True:
print("Welcome")
print("To")
print("TheUltimateGuide.com")
Output:
Welcome
To
TheUltimateGuide.com
In the above example we are checking the value of flag variable and if the value is True then we are executing few print statements. The important point to note here is that even if we do not compare the value of flag with the ‘True’ and simply put ‘flag’ in place of condition, the code would run just fine so the better way to write the above code would be:
flag = True
if flag:
print("Welcome")
print("To")
Now we understand better how if statement works. The output of the condition would either be true or false. If the outcome of condition is true then the statements inside body of ‘if’ executes, however if the outcome of condition is false then the statements inside ‘if’ are skipped. Lets take another example to understand this:
flag = False
if flag:
print("You Guys")
print("are")
print("Awesome")
The output of this code is none, it does not print anything because the outcome of condition is ‘false’.
Python if example without boolean variables
In the above examples, we have used the boolean variables in place of conditions. However we can use any variables in our conditions. For example:
num = 100
if num < 200:
print("num is less than 200")
Output:**
_num is less than 200
Python If else Statement Example
In this guide, we will learn another control statement ‘if..else’.
We use if statements when we need to execute a certain block of Python code when a particular condition is true. If..else statements are like extension of ‘if’ statements, with the help of if..else we can execute certain statements if condition is true and a different set of statements if condition is false. For example, you want to print ‘even number’ if the number is even and ‘odd number’ if the number is not even, we can accomplish this with the help of if..else statement.
Syntax
if condition:
block_of_code_1print("TheUltimateGuide.com)
else:
block_of_code_2
block_of_code_1: This would execute if the given condition is true
block_of_code_2: This would execute if the given condition is false
If-else example in Python
num = 22
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output:
Even Number
Syntax of if elif else statement in Python
This way we are checking multiple conditions.
if condition:
block_of_code_1
elif condition_2:
block_of_code_2
elif condition_3:
block_of_code_3
...
...
else:
block_of_code_n
Example
In this example, we are checking multiple conditions using if..elif..else statement.
num = 1122
if 9 < num < 99:
print("Two digit number")
elif 99 < num < 999:
print("Three digit number")
elif 999 < num < 9999:
print("Four digit number")
else:
print("number is <= 9 or >= 9999")
Output:
Python Nested If else statement
In this part of the tutorial, we will learn the nesting of the control statements we covered above.
When there an if statement (or if..else or if..elif..else) is present inside another if statement (or if..else or if..elif..else) then we call this nested control statements.
Nested if..else statement example
Here we have a if statement inside another if..else statement block. Nesting control statements makes us to check multiple conditions:
num = -99
if num > 0:
print("Positive Number")
else:
print("Negative Number")
#nested if
if -99<=num:
print("Two digit Negative Number")
Output:
Negative Number
Two digit Negative Number
Python for Loop explained with examples
A loop is a used for iterating over a set of statements repeatedly. In Python we have three types of loops for, while and do-while. In this guide, we will learn for loop and the other two loops are covered in the separate tutorials.
Syntax of For loop in Python
for in :
# body_of_loop that has set of statements
# which requires repeated execution
Here is a variable that is used for iterating over a . On every iteration it takes the next value from until the end of sequence is reached.
Lets take few examples of for loop to understand the usage.
Python – For loop example
The following example shows the use of for loop to iterate over a list of numbers. In the body of for loop we are calculating the square of each number present in list and displaying the same.
Program to print squares of all numbers present in a list
List of integer numbers
_numbers = [1, 2, 4, 6, 11, 20]_
variable to store the square of each num temporary
_sq = 0_
iterating over the given list
_for val in numbers:_
calculating square of each number
_sq = val * val_
displaying the squares
_print(sq)_
Output:
1
4
16
36
121
400
Function range()
In the above example, we have iterated over a list using for loop. However we can also use a range() function in for loop to iterate over numbers defined by range().
range(n): generates a set of whole numbers starting from 0 to (n-1).
For example: range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example: range(5, 9) is equivalent to [5, 6, 7, 8]
range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify the step_size, the numbers generated are having difference of 1. However by specifying step_size we can generate numbers having the difference of step_size.
For example: range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
Lets use the range() function in for loop:
Python for loop example using range() function
Here we are using range() function to calculate and display the sum of first 5 natural numbers.
Program to print the sum of first 5 natural numbers
variable to store the sum
_sum = 0
iterating over natural numbers using range()
for val in range(1, 6):
calculating sum
sum = sum + val
displaying sum of first 5 natural numbers
print(sum)_
Output:
15
For loop with else block
In Python we can have an optional ‘else’ block associated with the loop. The ‘else’ block executes only when the loop has completed all the iterations. Lets take an example:
for val in range(5):
print(val)
else:
print("The loop has completed execution")
Output:
0
1
2
3
4
The loop has completed execution
Note: The else block only executes when the loop is finished.
Nested For loop in Python
When a for loop is present inside another for loop then it is called a nested for loop. Lets take an example of nested for loop.
for num1 in range(3):
for num2 in range(10, 14):
print(num1, ",", num2)
Output:
0 , 10
0 , 11
0 , 12
...
Python While Loop
While loop is used to iterate over a block of code repeatedly until a given condition returns false. The main difference between a for loop and a while loop is that we use while loop when we are not certain of the number of times the loop requires execution, on the other hand when we exactly know how many times we need to run the loop, we use for loop.
Syntax of while loop
while condition:
#body_of_while
The body_of_while is set of Python statements which requires repeated execution. These set of statements execute repeatedly until the given condition returns false.
Flow of while loop
- First the given condition is checked, if the condition returns false, the loop is terminated and the control jumps to the next statement in the program after the loop.
- If the condition returns true, the set of statements inside loop are executed and then the control jumps to the beginning of the loop for next iteration. These two steps happen repeatedly as long as the condition specified in while loop remains true.
Python – While loop example
Here is an example of while loop. In this example, we have a variable num and we are displaying the value of num in a loop, the loop has a increment operation where we are increasing the value of num. This is very important step, the while loop must have a increment or decrement operation, else the loop will run indefinitely, we will cover this later in infinite while loop.
num = 1
# loop will repeat itself as long as
# num < 10 remains true
while num < 10:
print(num)
#incrementing the value of num
num = num + 3
Output:
1
4
7
Python – while loop with else block
We can have a ‘else’ block associated with while loop. The ‘else’ block is optional. It executes only after the loop finished execution.
num = 10
while num > 6:
print(num)
num = num-1
else:
print("loop is finished")_
Output:
10
9
8
7
loop is finished
Python Functions
In this guide, we will learn about functions in Python. A function is a block of code that contains one or more Python statements and used for performing a specific task.
Why use function in Python?
Like we've already established, a function is a block of code that performs a specific task. Lets discuss what we can achieve in Python by using functions in our code:
- Code re-usability: Lets say we are writing an application in Python where we need to perform a specific task in several places of our code, assume that we need to write 10 lines of code to do that specific task. It would be better to write those 10 lines of code in a function and just call the function wherever needed, because writing those 10 lines every time you perform that task is tedious, it would make your code lengthy, less-readable and increase the chances of human errors.
- Improves Readability: By using functions for frequent tasks you make your code structured and readable. It would be easier for anyone to look at the code and be able to understand the flow and purpose of the code.
- Avoid redundancy: When you no longer repeat the same lines of code throughout the code and use functions in places of those, you actually avoiding the redundancy that you may have created by not using functions.
Syntax of functions in Python
Function declaration:
def function_name(function_parameters):
function_body # Set of Python statements
return # optional return statement
Calling the function:
when function doesn't return anything
function_name(parameters)
OR
when function returns something
variable is to store the returned value
variable = function_name(parameters)
Python Function example
Here we have a function add() that adds two numbers passed to it as parameters. Later after function declaration we are calling the function twice in our program to perform the addition.
_def add(num1, num2):
return num1 + num2
sum1 = add(100, 200)
sum2 = add(8, 9)
print(sum1)
print(sum2)_
Output:
300
17
Default arguments in Function
Now that we know how to declare and call a function, lets see how can we use the default arguments. By using default arguments we can avoid the errors that may arise while calling a function without passing all the parameters. Lets take an example to understand this:
In this example we have provided the default argument for the second parameter, this default argument would be used when we do not provide the second parameter while calling this function.
*# default argument for second parameter
def add(num1, num2=1):
return num1 + num2
sum1 = add(100, 200)
sum2 = add(8) # used default argument for second param
sum3 = add(100) # used default argument for second param
print(sum1)
print(sum2)
print(sum3)*
Output:
300
9
101
Types of functions
There are two types of functions in Python:
- Built-in functions: These functions are predefined in Python and we need not to declare these functions before calling them. We can freely invoke them as and when needed.
- User defined functions: The functions which we create in our code are user-defined functions. The add() function that we have created in above examples is a user-defined function.
Python Numbers
In this guide, we will see how to work with numbers in Python. Python supports integers, floats and complex numbers.
An integer is a number without decimal point for example 5, 6, 10 etc.
A float is a number with decimal point for example 6.7, 6.0, 10.99 etc.
A complex number has a real and imaginary part for example 7+8j, 8+11j etc.
Example: Numbers in Python
Python program to display numbers of
different data types
*# int
num1 = 10
num2 = 100
print(num1+num2)
# float
a = 10.5
b = 8.9
print(a-b)
# complex numbers
x = 3 + 4j
y = 9 + 8j8
print(y-x)*
Output:
110
1.5999999999999996
(6+4j)
Python List with examples
In this guide, we will discuss lists in Python. A list is a data type that allows you to store various types data in it. List is a compound data type which means you can have different-2 data types under a list, for example we can have integer, float and string items in a same list.
Create a List in Python
Lets see how to create a list in Python. To create a list all you have to do is to place the items inside a square bracket [] separated by comma,.
#list of floats
num_list = [11.22, 9.9, 78.34, 12.0]
# list of int, float and strings
mix_list = [1.13, 2, 5, "TheUltimateGuide", 100, "hi"]
# an empty list
nodata_list = []
As we have seen above, a list can have data items of same type or different types. This is the reason list comes under compound data type.
Syntax to access the list items:
list_name[index]
Example:
*# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# prints 11
print(numbers[0])
# prints 300
print(numbers[5])
# prints 22
print(numbers[1])*
Output:
11
300
22
Python Strings
A string is usually a bit of text (sequence of characters). In Python we use ” (double quotes) or ‘ (single quotes) to represent a string. In this guide we will see how to create, access, use and manipulate strings in Python programming language.
How to create a String in Python
There are several ways to create strings in Python.
- We can use ‘ (single quotes), see the string str in the following code.
- We can use ” (double quotes), see the string str2 in the source code below.
-
Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line strings in Python. See the strings str3 and str4 in the following example.
lets see the ways to create strings in Python
str = 'TheUltimateGuide' print(str) str2 = "Mukumbuta" print(str2)
multi-line string
str3 = """Welcome to
TheUltimateGuide.com
"""
print(str3)
str4 = '''This is a tech
blog
'''
print(str4)*
Output:
*TheUltimateGuide
Mukumbuta
Welcome to
TheUltimateGuide.com
This is a tech
blog*
How to access strings in Python
A string is nothing but an array of characters so we can use the indexes to access the characters of a it. Just like arrays, the indexes start from 0 to the length-1.
You will get IndexError if you try to access the character which is not in the range. For example,
if a string is of length 6 and you try to access the 8th char of it then you will get this error.
You will get TypeError if you do not use integers as indexes, for example if you use a float as an index then you will get this error.
*str = "Timothy"
displaying whole string
print(str)
displaying first character of string
print(str[0])
displaying third character of string
print(str[2])
displaying the last character of the string
print(str[-1])*
Python String Operations
Lets see the operations that can be performed on the strings.
Concatenation of strings in Python
The + operator is used for string concatenation in Python. Lets take an example to understand this:
*str1 = "One"
str2 = "Two"
str3 = "Three"
# Concatenation of three strings
print(str1 + str2 + str3)*
Output:
OneTwoThree
Python Membership Operators in Strings
in: This checks whether a string is present in another string or not. It returns true if the entire string is found else it returns false.
not in: It works just opposite to what “in” operator does. It returns true if the string is not found in the specified string else it returns false.
*str = "Welcome to TheUltimateGuide.com"
str2 = "Welcome"
str3 = "Mukumbuta"
str4 = "XYZ"
# str2 is in str? True
print(str2 in str)
# str3 is in str? False
print(str3 in str)*
# str4 not in str? True
print(str4 not in str)*
Output:
True
False
True
Python Tuple with example
In Python, a tuple is similar to Lists except that the objects in tuple are immutable which means we cannot change the elements of a tuple once assigned. On the other hand, we can change the elements of a list.
How to create a tuple in Python
To create a tuple in Python, place all the elements in a () parenthesis, separated by commas. A tuple can have heterogeneous data items, a tuple can have string and list as data items as well.
Example – Creating tuple
In this example, we are creating few tuples. We can have tuple of same type of data items as well as mixed type of data items. This example also shows nested tuple (tuples as data items in another tuple).
*# tuple of strings
my_data = ("hi", "hello", "bye")
print(my_data)
# tuple of int, float, string
my_data2 = (1, 2.8, "Hello World")
print(my_data2)
# tuple of string and list
my_data3 = ("Book", [1, 2, 3])
print(my_data3)
# tuples inside another tuple
# nested tuple
my_data4 = ((2, 3, 4), (1, 2, "hi"))
print(my_data4)*
Output:
('hi', 'hello', 'bye')
(1, 2.8, 'Hello World')
('Book', [1, 2, 3])
((2, 3, 4), (1, 2, 'hi'))
Empty tuple:
# empty tuple
my_data = ()
Tuple with only single element:
Note: When a tuple has only one element, we must put a comma after the element, otherwise Python will not treat it as a tuple.
a tuple with single data item
my_data = (99,)
If we do not put comma after 99 in the above example then python will treat my_data as an int variable rather than a tuple.
How to access tuple elements
We use indexes to access the elements of a tuple. Lets take few example to understand the working.
Accessing tuple elements using positive indexes
We can also have negative indexes in tuple, we have discussed that in the next section. Indexes starts with 0 that is why we use 0 to access the first element of tuple, 1 to access second element and so on.
*# tuple of strings
my_data = ("hi", "hello", "bye")
# displaying all elements
print(my_data)
# accessing first element
# prints "hi"
print(my_data[0])
# accessing third element
# prints "bye"
print(my_data[2])*
Output:
('hi', 'hello', 'bye')
hi
bye
Note:
- TypeError: If you do not use integer indexes in the tuple. For example my_data[2.0] will raise this error. The index must always be an integer.
- IndexError: Index out of range. This error occurs when we mention the index which is not in the range. For example, if a tuple has 5 elements and we try to access the 7th element then this error would occurr.
Python Dictionary with examples
Dictionary is a mutable data type in Python. A python dictionary is a collection of key and value pairs separated by a colon (:), enclosed in curly braces {}.
Python Dictionary
Here we have a dictionary. Left side of the colon(:) is the key and right side of the : is the value.
mydict = {'StuName': 'Peter', 'StuAge': 30, 'StuCity': 'Agra'}
Accessing dictionary values using keys in Python
To access a value we can can use the corresponding key in the square brackets as shown in the following example. Dictionary name followed by square brackets and in the brackets we specify the key for which we want the value.
mydict = {'StuName': 'Ajeet', 'StuAge': 30, 'StuCity': 'Agra'}
print("Student Age is:", mydict['StuAge'])
print("Student City is:", mydict['StuCity'])
Output:
Loop through a dictionary
We can loop through a dictionary as shown in the following example. Here we are using for loop.
mydict = {'StuName': 'Steve', 'StuAge': 4, 'StuCity': 'Agra'}
for e in mydict:
print("Key:",e,"Value:",mydict[e])
Output:
Python OOPs Concepts
Python is an object-oriented programming language. What this means is we can solve a problem in Python by creating objects in our programs. In this guide, we will discuss OOPs terms such as class, objects, methods etc. along with the Object oriented programming features such as inheritance, polymorphism, abstraction, encapsulation.
Objects in Python
An object is an entity that has attributes and behaviour. For example, Ram is an object who has attributes such as height, weight, color etc. and has certain behaviours such as walking, talking, eating etc.
Classes in Python
A class is a blueprint for the objects. For example, Ram, Shyam, Steve, Rick are all objects so we can define a template (blueprint) class Human for these objects. The class can define the common attributes and behaviours of all the objects.
Methods
As we discussed above, an object has attributes and behaviours. These behaviours are called methods in programming.
Example of Class and Objects
In this example, we have two objects; Ram and Steve that belong to the class Human
Object attributes: name, height, weight
Object behaviour: eating()
Code:
*class Human:
# instance attributes
def init(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
# instance methods (behaviours)
def eating(self, food):
return "{} is eating {}".format(self.name, food)
creating objects of class Human
ram = Human("Ram", 6, 60)
steve = Human("Steve", 5.9, 56)
accessing object information
print("Height of {} is {}".format(ram.name, ram.height))
print("Weight of {} is {}".format(ram.name, ram.weight))
print(ram.eating("Pizza"))
print("Weight of {} is {}".format(steve.name, steve.height))
print("Weight of {} is {}".format(steve.name, steve.weight))
print(steve.eating("Big Kahuna Burger"))*
Output:
Height of Ram is 6
Weight of Ram is 60
Ram is eating Pizza
Weight of Steve is 5.9
Weight of Steve is 56
Steve is eating Big Kahuna Burger
How to create Class and Objects in Python
In this tutorial, we will see how to create classes and objects in Python.
Class definition in Python
A class is defined using the keyword class.
Example
In this example, we are creating an empty class DemoClass. This class has no attributes and methods.
The string that we mention in the triple quotes is a docstring which is an optional string that briefly explains the purpose of the class.
*class DemoClass:
"""This is my docstring, this explains brief about the class"""
this prints the docstring of the class
print(DemoClass.doc)*
Output:
This is my docstring, this explains brief about the class
Creating Objects of class
In this example, we have a class MyNewClass that has an attribute num and a function hello(). We are creating an object obj of the class and accessing the attribute value of object and calling the method hello() using the object.
*class MyNewClass:
"""This class demonstrates the creation of objects"""
creating object of MyNewClass
obj = MyNewClass()
prints attribute value
print(obj.num)
calling method hello()
obj.hello()
prints docstring
print(MyNewClass.doc)*
Output:
100
Hello World!
This class demonstrates the creation of objects
Python Constructors – default and parameterized
A constructor is a special kind of method which is used for initializing the instance variables during object creation. In this guide, we will see what is a constructor, types of it and how to use them in the python programming with examples.
Constructors in Python
Constructor is used for initializing the instance members when we create the object of a class.
For example: We have an instance variable num which we are initializing in the constructor. The constructor is being invoked when we create the object of the class (obj in the following example).
*class DemoClass:
# constructor
def init(self):
# initializing instance variable
self.num=100
# a method
def read_number(self):
print(self.num)
creating object of the class. This invokes constructor
obj = DemoClass()
calling the instance method using the object obj
obj.read_number()*
Output:
100
Syntax of constructor declaration
As we have seen in the above example that a constructor always has a name init and the name init is prefixed and suffixed with a double underscore(). We declare a constructor using def keyword, just like methods.
_def __init(self):
# body of the constructor_
Types of constructors in Python
We have two types of constructors in Python.
1. Default constructor – this is the one, which we have seen in the above example. This constructor doesn’t accept any arguments
2. Parameterized constructor – constructor with parameters is known as parameterized constructor.
Python – default constructor example
Note: An object cannot be created if we don’t have a constructor in our program. This is why when we do not declare a constructor in our program, python does it for us. Lets have a look at the example below.
Example: When we do not declare a constructor
In this example, we do not have a constructor but still we are able to create an object for the class. This is because there is a default constructor implicitly injected by python during program compilation, this is an empty default constructor that looks like this:
*def init(self):
# no body, does nothing.
Code:
class DemoClass:
num = 101
# a method
def read_number(self):
print(self.num)
creating object of the class
obj = DemoClass()
calling the instance method using the object obj
obj.read_number()*
Output:
101
Declaring a constructor example
In this case, python does not create a constructor in our program.
*class DemoClass:
num = 101
# non-parameterized constructor
def init(self):
self.num = 999
a method
def read_number(self):
print(self.num)
creating object of the class
obj = DemoClass()
calling the instance method using the object obj
obj.read_number()*
Output:
999
Python – Parameterized constructor example
When we declare a constructor in such a way that it accepts the arguments during object creation then such type of constructors are known as Parameterized constructors. As you can see that with such type of constructors we can pass the values (data) during object creation, which is used by the constructor to initialize the instance members of that object.
*class DemoClass:
num = 101
# parameterized constructor
def init(self, data):
self.num = data
a method
def read_number(self):
print(self.num)
creating object of the class
this will invoke parameterized constructor
obj = DemoClass(55)
calling the instance method using the object obj
obj.read_number()
creating another object of the class
obj2 = DemoClass(66)
calling the instance method using the object obj
obj2.read_number()*
Output:
55
66
With that, we've covered most of the basics to get us started programming in Python. What now...?! Simple.
Learn... Practice... Repeat...
OK, that looks like an infinite loop.
Top comments (0)