Python is one of the most popular programming languages available today. It is widely used in various sectors of business, such as programming, web development, machine learning, and data science. Given its widespread use, it’s not surprising that Python has surpassed Java as the top programming language.

This Python tutorial covers all the basics of Python and some advanced topics of the Python language, such as variables, data types, arrays, functions, and OOPs concepts, all of which will help you prepare for a career as a professional Python programmer.

The examples used in this Python tutorial have been implemented using PyCharm IDE. You can download PyCharm here. PyCharm creates a virtual environment where you can change the version of Python you want to use. You can create a new Python file by clicking on the “file” menu and then selecting “New Scratch File.”

First, we’ll start with “Variables,” which are the fundamental building blocks for writing any part of Python code. Variables are entities of a program that hold a value. The image shown below is a box with a numerical value of 100. Here, a variable would be the name of the box, which is x

python-x-100

In this section of Python tutorial, let's see how can we assign a variable in Python

print(“Meet Jane”)

print(“Jane works as a software engineer”)

print(“Elise is Jane’s manager”)

The print function in Python prints out anything that is inside the parenthesis. There are multiple ways to run a file in PyCharm: you can either use “Alt+Shift+F10,” or click on the “run” menu and select the Python file you want to run. Alternatively, you can click on the run button. Here is the output of the code:

/code-output

You can add extra information to your code by adding comments using the hashtag “#.” 

Instead of typing “Jane” every time, you can store it in a variable, as shown in the example below:

name = “Jane”

print(“Meet,” name)

This will print out “Meet Jane” in the output console.

You can also use string formatting in a print statement to display the result:

print(“%s works as a software engineer”%name)

print(“Elise is %s’s manager”%name)

This prints out the following in the output console:

“Jane works as a software engineer”

“Elise is Jane’s manager”

In Python, all the variables are stored in a specific memory address. To find the address of variables used, print(id(name))

The variables that have the same values carry the same address. For example:

name=’Jane’

name2=’Jane’

print(id(name))

print(id(name2)) 

run-scratch

Variables with different values have a different address:

name=’Jane’

name2=’May’

print(id(name))

print(id(name2))

in-float

Python uses different types of program data. We’ll cover numeric data first. Numeric data comes in three different types: int, float, complex

The following is an example of an integer (int) data type in Python:

num = 5

To confirm what kind of data type it is, use type().

print(type(num))

Float is the second most commonly used data type.

num = 5.6

print(type(num))

Finally, we have the complex data type.

num = 5+6j

print(type(num))

casting

Python allows you to specify a variable type or convert one data type to another using Python casting. Casting is done using constructor functions - int(), float(), complex(), str().

num = 5

print(num, type(num))

print(float(num), type(float(num)))

print(complex(num), type(complex(num)))

above-new

From the above example, you can see that num is an integer variable. To convert this variable into float and complex type, we use float(num) and complex(num).

You can also convert a floating number into an integer.

num=5.6

print(int(num), type(int(num)))

If you have a lot of data, you cannot have it stored in multiple variables, as this would take up a lot of memory.  To overcome this problem, we have “Lists” in Python, which are collections of data that hold values of multiple data types. A list is declared within square brackets.

hey-1

You can also store various types of data using a Tuple, which is an immutable collection of heterogeneous data. You can change the values of a tuple, and tuples are differentiated with curly brackets.

hey-2

Data can also be stored in the form of Sets in Python. A set is an unordered collection of unique heterogeneous data.

hey-3.

Let’s declare a simple list and filter the values using indexing.

lst=[1,4,5,2,7,5]

print(lst)

print(lst[0])

print(lst[1])

Pythonlist1

In a Python list, the first index starts at 0, then 1, and so on. Therefore, lst[0] will return the first element in the list, and lst[1] will give the second element in the list.

To return the total number of elements in the list, use the length len() function.

print(len(lst)) # It will return 6 as there are six elements present in the list.

To extract the last element and the second last elements from the list, you can use

print(lst[-1])  # This will return 5

print(lst[-2])  # This will return 7 

To get the first four elements from the list, you can use

print(lst[0:4]) # It will return the values from the first four indexes and exclude the last index

Pythonlastindex

You can also slice the first four elements of the list using: 

print(lst[:4])

Likewise, you can slice all the elements starting from index 2 using: 

print(lst[2:])

The following print statement returns the first two elements in the list:

print(lst[:-4])

To display the last four elements from the list, you can use:

print(lst[-4:])

If you want to print every alternate value from the list:

print(lst[1::2]) # It will print the values starting from the first index, then the third index, and so on.

Pythonthirdindex

Note:  When slicing the values from a list, it can only accept integers. If you provide any other type of data, it will throw an error.

print(lst[1.0:4])

PythonError

A list can also contain floating and string literals.

lst=[1,4,”Python”,2,7.4,5]

print(lst)

Pythonprint(Ist)

Lists are mutable, meaning that you can change the values in the list.

lst[1] =”hello” # This will replace the value at first index from 4 to hello 

print(lst)

PythonHello

Python allows you to add new elements to the end of the list using an append() function.

lst.append(‘Simplilearn’)

print(lst)

PythonAppend

You can create a list inside another list. This is called a nested list. Here is an example:

nested=[1,2,[2,3,4]]

print(nested)

Another way to append the elements in a list is to use the extend() function.

nested.extend([[7,8,9]])

print(nested)

Pythonnested

Now that you have a good understanding of lists in Python, let's continue this Python tutorial with Tuples.

'tpl=(1,2,3)

print(tpl)

To extract the values of a tuple, you can slice it using its index.

print(tpl[1]) # This will return the value 2 from the tuple.

Pythontuple

To extract the first element from the list, you can use: print(tpl[:1])

To reverse the elements in a list, you can do that with

print(tpl[::-1])

python-print

Tuples are immutable, so you cannot change their values. It throws an error if you try to change them.

tpl=(1,2,3)

print(tp1)

tpl[1]=7

immutable

Tuples are used when you don’t want the data or information to change over time. You can also declare a tuple in the following way:

tpl=5,6,8

print(tpl)

Python allows you to pack and unpack a tuple.

a,b,c=tpl

print(a,b,c)

printabc

You can also create a list in Python in the following way:

a, *lst=tpl

print(a, lst)

print-st

The following is how to create a Set in Python:

s={1,3,3,3,4,5} # Sets only take unique values, so it will print 3 only once

print(s)

set-in-python.

You cannot change the values in a set. It will throw an error if you do so.

changing-list

Here is an example of changing a list into a set:

lst=[1,3,3,3,4,5]

print(lst)

print(set(lst))

changing-list-2

As you can see, the duplicate values in the list have now been removed after converting it to a set.

Now, let’s tackle the subject of Arithmetic operators in this Python tutorial. Python supports various types of arithmetic operators such, as addition(+), subtraction(-), multiplication(*), division(/), floor division(//), modulus(%), and exponentiation(**). 

a,b=10, 5

print(‘a+b’, a+b)

print(‘a-b’, a-b)

print(‘a*b’, a*b)

print(‘a/b’, a/b)

print(‘a//b’, a//b)

print(‘a%b’, a%b)

print(‘a**2’, a**2)

changing-list-3

You can store the value of any arithmetic operation in a variable.

a,b = 10,5

res = a*b

print(res)

Using Python, you can increment the value of a variable.

a,b = 10,5

count=0

count=count+1

count += 1 # Another way to increment the value of a variable using an assignment operator

print(count)

The output of the above code is two.

a//=3 # This returns 10//3 i.e. 3

Relational Operators

Relational operators are used for comparing two values. The relational operators return boolean values.

a,b=10, 5

print(a,b)

print(a>b) # Greater than operator

print(a<b) # Less than operator

print(a>=b) # Greater than or equal to operator

print(a<=b) # Less than or equal to operator

print(a==b) # Equal operator

print(a!=b) # Not equal operator

relational-operators

Logical Operators

Logical operators are used to combine conditional statements.

a1, b1, c1=10, 20, 30 

print(a1, b1, c1)

print(c1>a1 and c1>b1) # “and” operator returns True if both the statements are true

print(a1>b1 and c1>b1) # Returns “False” since a1 is not greater than b1

print(a1>b1 or c1>b1) # Gives “True” as or operator returns True if one of the statements is true

print(not a1>b1) # Reverses the results, returns True if the result is false

logical-operators

Bitwise Operators

Bitwise operators are used to compare binary numbers. The following are some examples of binary operators (&, |, ^, ~, <<, >>).

a,b = 10,5

print(bin(a), bin(b))

print(a & b) # Sets each bit to 1 if both bits are 1

print(bin(a & b))

print(a | b) # Sets each bit to 1 if one of 2 bits is 1

print(bin(a | b))

print(bin(a ^ b)) # Sets each bit to 1 if only one of two bits is 1 

print(bin(~a)) # Inverts all the bits

/bitwise

print(bin(a<<2)) # Shifts left by pushing zeros in from the right and let the leftmost bits fall off

print(bin(a>>2)) # Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

/bitwise-2.

Membership Operators

These operators are used to check if a sequence is present in an object (list, tuples, dictionaries, etc). Examples of such operators are in and not in.

list = [1,2,3,4,5]

x = 2

print(x in list) # Returns True since 2 is present in the list

print(x not in list) # Returns False as the value of x is present in the list

Identity Operators

These operators are used to compare the objects to see if they are the same object with the same memory location. Examples of such operators are “is” and “is not.”

x = 10

y = 10

print(x is y) # Returns True as the values of x and y are the same

print(x is not y) # Returns False

If you change y = 12, then print(x is not y) will return True.

Certain functions are not pre-built into Python, but these functions can be found inside Python Modules. Math is one such module that has a wide collection of mathematical functions. The following link has all the mathematical functions covered in detail: mathematical functions - Python

Some of the basic functions available are ceil(), floor(), factorial(), fabs(), isfinite(), exp(). There are other trigonometric and hyperbolic functions that you can use.

To use these functions, you need to import the math module.

import math

print(math.pi)

math-module

You can also import specific functions from the math module.

From math import pi

print(pi)

The following is how to use additional mathematical functions:

import math

X = 9.5

print(ceil(X)) # Returns the nearest integer greater than 9.5

print(math.tan(X))

y = 3

print(math.pow(X,y))

print(math.sqrt(x))

print(math.factorial(y))

print-math.

Let’s talk about how to accept inputs from the user in Python.

Python has a built-in input() function that has prompt as a parameter, which is a string representing a default message before the input.

name = input(“Enter your name”) # “” represents new line

print(“Hi”, name)

inline-input

The inline input function always accepts a string.

age = input(“Enter your age”)

print(type(age))

print(age + 5) # Throws an error because  age is a string and 5 is an integer

To add an integer to the age variable, you need to convert it into an integer.

print(int(age) + 5)

print(“%s is %d years old”%(name, int(age)))

print-years

Python has a feature that slices the characters from the user input function.

name = input(“Input a word”)[:4]

print(name) # Returns the first four letters of the word

four-letters

Since you know input() function accepts values as strings, you can explicitly pass inputs in the form of an integer.

a = int(input(“Enter a multiple of 5”))

print(type(a))

Next in this Python tutorial, you will learn the different decision-making statements and loops in Python.

If Statement

The if statement is used to test a specific condition. If the condition is true, a block of code is executed.

a = int(input(“Enter a multiple of 5”))

if a%5 != 0:

    print(a, ‘Not a multiple of 5’)

multiple

a = int(input(“Enter a multiple of 5”))

multiple-2

if a%5 != 0:

    print(a, ‘Not a multiple of 5’)

print(“this is what happens next”)

From the above output, you can see that the if statement runs only those lines of code that are indented. An indented line of code in Python has four spaces from the beginning of the line.

Else Statement

The else statement is executed when the expression in the if condition is false.

a = int(input(“Enter a number”))
if a%2 != 0:

    print(a, ‘is an odd number’)

else:

    print(a, ‘is an even number’)

print(“this is what happens next”)

happen

From the above output, since five is not directly divisible by two, we can see that the result is “5 is an odd number.” 

However, since four is divisible by two, the else statement is executed, and the result is “4 is an even number.”

Elif Statement

The elif statement in Python enables you to check multiple conditions and execute specific block of statements if the previous conditions were false.

a = int(input(“Enter a number a”))

b = int(input(“Enter a number b”))

c = int(input(“Enter a number c”))

if a>b and a>c:

    print(a, ‘is the greatest number’)

elif b>a and b>c:

    print(b, ‘is the greatest number’)

else:

    print(c, ‘is the greatest number’)

greatest-number

As you can see, since b>a and b>c, the elif statement is executed.

Nested if: There may be instances where you want to check for another condition after a condition ends up being true. In these cases, you can use nested if statements.

age = int(input(“Enter your age”))

if age >= 60:

    print(“You  are eligible for senior citizen discount”)

else:

    if age <=18:

        print(“You are eligible for minor discount”)

    else:

        print(“You are not eligible for any discount”)  

discount

The following is how a While Loop works in Python:

discount-2

While Loop: While loop is used to execute a set of statements as long as a condition is true.

word = “Python”

i = 0

while i<5:

    print(i, word)

    i+=1

The above code prints Python five times since the while condition is true until i<5.

You can also use a while loop to add elements to an empty list.

lst = []

c = input(“Enter any key to add elements to list and 0 to exit loop”)

while c != “0”:

    lst.append(c) # Add elements to the empty list until c is not equal to 0

    c = input(“Enter any key to add elements to list and 0 to exit loop”)

print(lst)

For Loop

A for loop in Python is used to iterate over a sequence (list, tuple, set, dictionary, and string).

word = “Python”

for w in range(3):

    print(w, word)

word

Using for loop, you can print all the elements present in a list in sequence.

lst = [1,2,”hello”,[1,2,3]]

for obj in list: # This will iterate through all the elements in the list and print it one by one

    print(obj)

print-obj

# Program to count the number of vowels in the input using a for loop:

word = input(“enter word ”)

count = 0

for i in word:

    if i in [‘a’,’e’,’i’,’o’,’u’,’A’,’E’,’I’,’O’,’U’]:

        count += 1

print(“number of vowels in %s is %d”%(word, count))

break

Break

The break statement terminates the loop before it has iterated through all the items.

fruits = [“apple”, “orange”, “grapes”]

for x in fruits:

    print(x)

    if x == “orange”: # This will break the loop when the element in the list is an orange

        break

break2

Continue

The continue statement will stop the current iteration of the loop, and continue with the next iteration.

fruits = [“apple”, “orange”, “grapes”]

for x in fruits:

    if x == “orange”:

        continue

    print(x)

continue.

Below is another example that illustrates how a “continue” statement works:

n = 20

for i in range(2, n//2+1):

    if n%i != 0:

        continue

    print(“%d is divisible by %d”%(n,i))

continue

One of the most useful features of Python is its built-in libraries that make programming easier. With that in mind, we will now be discussing how Array and NumPy works.

Learn data operations in Python, strings, conditional statements, error handling, and the commonly used Python web framework Django with the Python Training course.

Array

Python does not have built-in support for arrays. However, Python; ists can be used instead. An array is a special variable that can hold more than one value at a time.

Syntax: array(data type, value list)

The following example shows how to declare an array:

from array import * # Imports all the sub modules and functions from array module 

ar = array(‘i’, [1,2,3,4,5]) # Here ‘i’ represents an array of integer type

print(type(ar))

print(ar[2])

ar.append(-10) # Adds -10 to end of the array

print(ar)

ar.remove(3) # Removes element 3 from the array list

print(ar)

ar = ar*3 # Multiplies the array elements three times

print(ar)

print-ar

NumPy

NumPy is a Python library that is used for processing large multi-dimensional arrays and matrices.

If you are working in IDE, you need to use “pip install numpy” to install NumPy. If you are working with Jupyter notebook, you can use “conda install NumPy.

In PyCharm, you’ll go to File>>>Settings>>>Project>>>Project Interpreter>>>Click on the plus(+) sign on the top right corner and search for NumPy. Click on Install Package.

import numpy as np

ar1 = np.array([1,2,3])

np-array

As you can see from the output, this is a 1D array with no commas between the values. It is different from a list that has commas between the values. 

You can create a 2D array as follows:

ar1 = np.array([[1,2,3], [4,5,6]])

print(ar1)

print-ar1

The dimension, size, shape, and type of elements in an array can be checked using the following:

print(“Dimension:”,ar1.ndim)

print(“Size:”,ar1.size)

print(“Shape:”,ar1.shape)

print(“type of elements:”,ar1.dtype)

library

The following is a link to learn more on NumPy library 

Next, we’ll go over the functions available in NumPy.

To create an array filled with zeroes, you can do the following:

z = np.zeros((2,2),dtype=”int”) # Creates a 2x2 array filled with zeroes

print(z)

create-array

You can use the full() function to create an array of any dimension and elements.

z = np.full((2,3),1) # Creates a 2x3 array filled with ones

print(z)

full-array

Like lists, arrays in Python can be sliced using the index position.

ar3 = np.array([[1,2,3],[4,5,6],[10,11,12]])

print(ar3[1,2]) # Returns 6 as the output

print(ar3[1,::-1]) # Prints the elements of the second list of the array in reverse order

print(ar3[:2,::-1]) # Prints the elements of the first and second list in reverse order

reverse-order

You can perform arithmetic operations on the elements of an array.

ar3 = np.array([[1,2,3],[4,5,6],[10,11,12]])

print(ar3+10) # Add 10 to all the elements

print(ar3*10) #Multiplies 10 to each element in the array

multiples-10

The NumPy array has other functionalities as well. For instance, you can find the sum, mean, maximum and minimum of the elements in the array.

ar3 = np.array([[1,2,3],[4,5,6],[10,11,12]])

print(ar3.sum()) # Gives the total sum of all the elements

print(ar3[0].sum()) # Returns only the sum of the first list of elements in the array

print(ar3[0].min()) # Return the last element from the first list

last-10.

The elements in an array can be transposed as well.

ar3 = np.array([[1,2,3],[4,5,6]])

print(ar3)

print(ar3.T)

To return the array into normal form, use:

/return-the-array

ar3 = ar3.T

print(ar3.T)

Now let’s continue this Python tutorial by learning about functions in Python. A function is a block of code that only runs when it is called. You can pass data in the form of parameters to a function, and it can return data as a result.

Syntax: def function_name():

                 Block of code  

def fun(): # fun is the function name

    print(“Simplilearn”)

fun() # Calling the function

fun-function.

The following is another example of adding two numbers using a function.

def add(a,b): # Function add accepts two parameters, a and b

    print(a+b)

add(4,5) # It is mandatory to pass the required number of parameters while calling the function

calling-function

def add(a,b):

    s = a+b

    return s # This returns the value of a+b from the function

n = add(4,5)

print(n)

def add(a,b):

    s = a+b

    d = a-b

    return s, d # Returns two values for addition and subtraction from the function

n1, n2 = add(4,5)

print(n1, n2)

value

You can also assign values to the parameters while declaring a function.

def add(a=5, b=3):

    s = a+b

    d = a-b

    return s, d 

n1, n2 = add()

print(n1, n2)

/value-2

*args and **kwargs: These are mostly used in function definitions to pass a variable number of arguments to a function.

*args: In Python, a single asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions.

def args_kwargs(*myArgs):

    print(myArgs)

    print(myArgs[1])

args_kwargs(1,2,3,4)

def args_kwargs(*myArgs):

    a = myArgs[0] + myArgs[1]

    return a

a = args_kwargs(1,2,3,4)

kwargs

print(a) # This returns 3 since myArgs[0]=1 and myArgs[1]=2

**kwargs: The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function.

def args_kwargs(**myKwargs):

    print(myKwargs) # Prints the values in the form of a dictionary

    print(myKwargs[‘a’]+myKwargs[‘b’])

args_kwargs(a=10, b=20)

kwargs-2

def args_kwargs(**myKwargs):

    print(myKwargs)

    if ‘a’ in myKwargs and ‘b’ in myKwargs:

        print(myKwargs[‘a’]+myKwargs[‘b’]) # Won’t print, = as ‘a’ in not present in the function call

args_kwargs(c=10, b=20)

kwargs-3

Python allows you to assign the function name to a variable. 

def args_kwargs(**myKwargs):

    print(myKwargs)

    if ‘a’ in myKwargs and ‘b’ in myKwargs:

        print(myKwargs[‘a’]+myKwargs[‘b’]) 

args_kwargs(c=10, b=20)

d=args_kwargs

d(a=1, b=2)

kwargs-4

The final Python function that you will learn in this Python basics tutorial is known as Recursive. Recursion is a method of programming in which a function calls itself one or more times in its body.

def rec(n):

    if n==1:

        print(n)

        return

    print(n)

    return rec(n-1)

rec(3)

recursion

Recursion can be used to write a function that returns the factorial of a number.

The following code is considered a general way to write a function to return the factorial.

def fact(n):

    f = 1

    for i in range(1, n+1):

        f *= i

    return f

print(fact(3))

Using recursive function to return the factorial of a number:

def fact(n):

    if n==1:

        return 1

    return n * fact(n-1)

print(fact(3))

lambda

Learn the essentials of object-oriented programming, web development with Django, and more with the Python Training Course. Enroll now!

Lambda Function

Lambda can take any number of arguments, but can only have one expression.

Syntax: lambda arguments: expression

Here, you will see how a Lambda function works and why it is important.

The following is a Lambda function used to add two numbers passed as an argument, and print the result:

l = lambda a,b : a+b

print(l(10,20))

Next, we’ll go over how to implement filter, map, and reduce a list using the Lambda function.

Filter Function

A filter() function in Python takes in a function and list as arguments. It filters out all the elements of a sequence, for which the function returns True.

list = [‘a’, ‘b’, ‘e’, ‘f’, ‘o’, ‘a’]

l = list(filter(lambda x:x in [‘a’, ‘e’, ‘i’, ‘o’, ‘u’],lst))

print(l)

filter-function

Map Function

The map() function also takes in a function and list as an argument. A new list is returned, which contains all the Lambda modified items that each item for that function returned. 

The following example is a function that changes every character to the preceding character based on its ASCII value:

lst = [‘a’, ‘b’, ‘e’, ‘f’, ‘o’, ‘a’]

result = map(lambda x:chr(ord(x)+1),lst) # It maps all the letters to its ascii values using ord()

print(list(result))

map-function

Reduce Function

Reduce() function accepts a function and a sequence, and returns a single value. This function is defined in the “functools” module.

lst = [‘a’, ‘b’, ‘e’, ‘f’, ‘o’, ‘a’]

result = map(lambda x:chr(ord(x)+1),lst) 

print(list(result))

from functools import reduce

result = reduce(lambda x,y:x+y,lst)

print(result)

So far, we have looked at functions, and the different ways to write them. Now, let’s focus on Modules under the basics of Python.

A module can be considered the same thing as a code library. It is a file containing a set of functions that you want to include in your application.

Suppose there is a file called mod1.py in the same location as the scratch file and it has a prime function, and an even function.

def prime(a):

    for i in range(2,a):

        if a%i == 0:

            print(“Number is not prime”)

            return

    print(“Number is prime”)

def even(a):

    if a%2 == 0:

        print(“Number is even”)

    else:

        print(“Number is odd”)

You can access mod1.py file from the scratch file by importing it.

from mod1 import *

n = int(input(“Enter a number”))

prime(n) # Calling the prime function

even(n) # Calling the even function

even-function

Using modules makes your code compact and more readable; you don’t have to read through a hundred lines of code. Furthermore, you can share this module with other people who can utilize it in their projects.

Now that you know the basics of Python programming, it is time to learn about Object Oriented Programming (OOP) and its different features. 

Everything, including every instance, is an object in Python. OOP is a programming paradigm that focuses on objects. An object has Attributes and Behaviour.

An attribute contains the data that describes the object, such as lists, tuples, arrays, variables.

The behavior has methods applied to the attributes.

Here is an example of a car that has the following attributes and behaviors:

attribute

Class

A class in OOP is a collection of similar objects.

class

Inheritance

The inheritance mechanism in Python is one of the most important features of OOP. It allows a new class to inherit the features of another class. 

Example: There can be a “vehicles” class, and under vehicles, there is a class called “car.” Here, “vehicles” are called the parent class and “car” is the child class. A car can inherit all the functions and features of vehicles.

Encapsulation

This is the feature of preserving data from direct access.

Polymorphism

Polymorphism is a feature that lets you use the same function in multiple ways.

Suppose you have vehicles and bicycles. Bicycles accelerate very differently than a car does; a car runs on fuel and a bicycle has pedals. Both of them can accelerate but are used differently.

The following example explains the concept of Object-Oriented Programming:

class Car:

    carType = “manual” # global feature

    def __init__(self, year, speed): #__init()__ is executed when the function is being initiated

        self.year=year # creating an instance

        self.speed=speed

    @staticmethod

    def welcome():

        print(“Welcome to the car showroom”)

    @classmethod

    def type(cls):

        print(print(“These cars are”, cls.carType))

    def getSpeed(self):

        print(“Maximum speed is”, self. speed)

BMW = Car(2018, 155)

Ford = Car(2016, 140)

Car.welcome()

BMW.getSpeed()

Ford.getSpeed()

Car.type()

The following is an example of Inheritance:

inheritence

class Car:

    def __init__(self, year, speed): 

        self.year=year # creating an instance

        self.speed=speed

    def getSpeed(self):

        print(“Maximum speed:”, self.speed)

class Sedan(Car): # Sedan inherits the features of Car

    pass

BMW = Car(2018, 155)

Ford = Car(2016, 140)

BMW.getSpeed()

get-speed.

In the last section of this Python basics tutorial, let’s look at an example showing how to implement Polymorphism in Python.

class Car:

    def __init__(self,name):

        self.name=name

class Sedan(Car):

    def getSpeed(self):

        print(“Maximum speed 150”)

class SUV(Car):

    def getSpeed(self):

        print(“Maximum speed 120”)

carLst = [Sedan(“Camry”), SUV(“Scorpio”)]

for car in carLst:

    print(car.name + “:”,end= “”)

    car.getSpeed()

get-speed2

You can see we have polymorphed car class into Sedan and SUV and inherited the functionalities of car class.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Conclusion

This Python tutorial should give readers a better understanding of all basic Python concepts, including different conditional statements, handling data using NumPy, how to write a function, how to create a module, how to implement different features of Object Oriented Programming using classes and objects, and more.

For a more hands-on experience, go through this Simplilearn video on “Python Tutorial” delivered by our Data Science experts that covers the Python structure. 

How Simplilearn Can Help You

Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the increasingly popular Python development language and expose you to the essentials of Object-Oriented Programming, web development with Django, and game development. 

Learning Python also opens up even more career advancement opportunities, as it’s used widely in the field of software development, one of the most popular career options that professionals choose today. If this Python tutorial has piqued your interest, why not check out our other Software development courses, like Java Certification Training and Full Stack Developer course to learn more.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449

Get Free Certifications with free video courses

  • Programming Fundamentals

    Software Development

    Programming Fundamentals

    5 hours4.57.5K learners
  • Python for Beginners

    Software Development

    Python for Beginners

    11 hours4.5334K learners
prevNext

Learn from Industry Experts with free Masterclasses

  • Prepare for Digital Transformation with Purdue University

    Business and Leadership

    Prepare for Digital Transformation with Purdue University

    11th Jan, Wednesday9:00 PM IST
  • Program Preview: Post Graduate Program in Digital Transformation

    Career Fast-track

    Program Preview: Post Graduate Program in Digital Transformation

    20th Jul, Wednesday9:00 PM IST
  • Expert Masterclass: Design Thinking for Digital Transformation

    Career Fast-track

    Expert Masterclass: Design Thinking for Digital Transformation

    31st Mar, Thursday9:00 PM IST
prevNext