Browse by Domains

Python Tutorial For Beginners – A Complete Guide | Learn Python Easily

What is Python ?

Contributed by – python.learning

Python is a high-level, object-oriented programming language. Most beginners in the development field prefer Python as one of the first languages to learn because of its simplicity and versatility. It is also well supported by the community and keeps up with its increasing popularity. In this Python Tutorial for beginners, we will learn the basics of Python as a programming language, and understand how to get started with it. We will see how to download and install Python and use the popular IDEs to begin coding. We will also discuss jupyter functionality in detail.

What is Python used for?

Next time you are browsing through Google, indulging in your daily dose of Instagram, spending hours watching videos on Youtube, or listening to your favourite music on Spotify, remember that all of them use Python for their programming needs. Python has various uses across applications, platforms, and services. Let us talk about a few here.

Web Development

top Python web frameworks - python tutorial for beginners

The large selection of pre-built Python libraries makes web development a much simpler task. Writing a Python code is less time-consuming due to its clean and simple syntax. This helps with quick prototyping accelerating the ROI of commercial products. The built-in testing frameworks help in shipping bug-free codes. A large selection of well-supported frameworks help in facilitating speedy implementation without compromising on the performance of the solution.

Internet of Things

For the sake of simplicity, let us consider the Internet of Things to be the ‘physical objects connecting an embedded system to the internet’. It plays a vital role in projects that involve big data, machine learning, data analytics, wireless data networks, and cyber-physical systems. IoT projects also deal with real-time analytics.

A programming language should be a bold choice keeping in mind the aforementioned fields of application. This is where Python ticks off all the check-boxes. Additionally, Python is also scalable, expandable, portable, and embeddable. This makes Python system-independent and allows it to accommodate multiple single board computers, irrespective of the operating system or architecture.

Python tools for IoT under python tutorial for beginners


Also, Python is excellent for managing and organising complex data. It is particularly useful for IoT systems that are data-heavy. Another reason for Python to be the ideal programming language for IoT applications is its close relation with scientific computing.

Everything Python

Let’s help you explore Python more!

Are you looking for career guiding articles in Python? 👇

OR

Are you looking for Knowledge articles in Python?

Machine Learning

Machine Learning has offered a whole new approach to problem-solving. Python is at the forefront of Machine Learning and Data Science due to the following reasons:

  • Extensive open-source library support
  • Efficient and precise syntax
  • Easy integration with other programming languages
  • Python has a low entry-point
  • Scalable to different operating systems and architectures

Here is a Python Tutorial video for you by Great Learning.

How to Install Python?

If you are a Windows user and if you have installed Python using Anaconda distribution package which is available at Anaconda.org, you need to go to “Download Anaconda” and then download the latest version for Python 3.6.

Once you download this, it is a pretty simple and straightforward process to follow, and you will have Python installed for you. The next step is to power up an IDE to start coding in Python.

So once you install Python, you can have multiple IDEs or text editors on top of your Python installation.

For text editors, you can use something like Sublime or Notepad++. If you are comfortable using an Integrated Development Environment, then you can use Jupyter. Also, there are other options like Wingware, Komodo, Pycharm, and Spyder.

There are multiple packages available in Python. Some of the instrumental libraries are numpy, pandas, seaborn for visualisation and scipy for calculations and statistics. Others are xlrb, openpyxl, matplotlib, and io.

Why to Choose Python?

You Should Choose this because Python has become the most preferred programming language for enabling data science and machine learning applications. Of course, Python has its advantages; it is swift as compared to other programming languages, even R for that matter.

We can easily say that Python is a swift compiler. Since it is a Java-based programming language, you will be able to extend its applications beyond analytical research, analytical modelling, and statistical modelling. You will be able to create web applications using Python and integrate these web applications directly to your analytical models in the background.
Python is also very easy to integrate with other platforms and other programming languages. It has a common object-oriented programming architecture wherein existing IT developers, IT analysts, and IT programmers find it very easy to transition to the analytics domain.
Because the structure of coding in Python is object-oriented programing architecture, it has excellent documentation support.

7 Reasons Why You Should Use Python

  1. Readable and Maintainable Code
  2. Multiple Programming Paradigms
  3. Compatible with Major Platforms and Systems
  4. Robust Standard Library
  5. Open Source Frameworks and Tools
  6. Simplified Software Development
  7. Test-Driven Development
7 reasons why you should use Python - python tutorial for beginners

R vs Python?

R was developed for statistical analysis applications; on the other hand; Python was developed as a general-purpose programming language. Both of these are essential for those who work with large data-sets, solve machine learning problems, and create complex data visualizations.
Let us have a look at the differences between R and Python

Read more about the difference between R and Python, and which is a better alternative.

Best Way to Learn Python?

The ease of learning is the main attribute behind Python’s popularity. It is a simple and type free programming language and hence easy to learn. The time taken to learn the language depends on the level you want to achieve with Python. Also, the learning curve could be shorter or longer depending on individual ability.

One would require 6-8 weeks to learn the basics of Python. This will include learning the syntax, key-words, functions and classes, data types, basic coding, and exception handling.
Advanced Python skills are not necessary for all Python professionals. Depending on the nature of your work, you can learn skills such as database programming, socket programming, multithreading, synchronisation techniques etc.

The highly sophisticated Python skills include concepts of Data Analytics, hands-on experience of the required libraries, image processing etc. Each of the specialised skill would need around one week to master.

Read our blog on top 50 interview questions for Python to test your knowledge. It will give you an idea about how much you know about Python and what else is there to learn.

What are the top Python IDEs?

There are 7 top IDE’s for Python

  1. Spyder
  2. PyCharm
  3. Thonny
  4. Atom
  5. Jupyter
  6. Komodo
  7. Wingware


Top 7 Python IDEs - python tutorial for beginners

Which is the best IDE for Python?

Jupyter is the best IDE for Python and one of the most widely used IDE for Python. Let us have a look at how to set-up the Jupyter Notebook. Also, let us see what the functionalities of a Jupyter Notebook.

How to Power Jupyter Notebook

Below are the guided steps to power up a Jupyter notebook:

  1. Open the Anaconda prompt. This is available to you if you have done the installation through the Anaconda installer. 
  2. Once you open the Anaconda Command Prompt, you will see a default path assigned to you. This is the username for the computer that you are using.
  3. Add the folder paths to this default path (e.g., cd Desktop → cd Python), where you want to open the notebook
  4. Once you set the path, add the Jupyter notebook using the command jupyter notebook
  5. Hit enter. This will open the notebook in your local host, i.e., your system
  6. The path described in the Anaconda prompt will now come on your jupyter notebook home page
  7. Next step is to open a new Python Notebook. This is your environment to carry out all the coding. You can rename the new notebook (untitled) to what you want and hit ‘rename’.
creating new python notebook - python tutorial for beginners


Keep the anaconda prompt active, the one which you used to power up your Jupyter notebook, while you are working with your Jupyter in your local. If the anaconda prompt is closed, the python is no longer running on your system, and the kernel gets disconnected.

Functionalities in a Python Notebook (Jupyter)

File options in Jupyter notebook - python tutorial for beginners
downloading a Jupyter notebook - python tutorial for beginners

There are multiple options on the toolbar, i.e., File, Edit, View, Insert, Cell, Kernel, Widgets and Help. Let us have a look at some of the features and functionalities one by one.

File Options

Save and Checkpoint – Setting a Checkpoint is a fascinating concept. The file is Autosaved at regular intervals, and by setting a check-point, you can skip back a few auto-saves to the set checkpoint. This helps in case you made a mistake in the past couple of minutes or hours. You can always revert to a more stable checkpoint and proceed with your code from there, rather than starting from scratch. 

Download as – There are different ways in which you can download a Jupyter Notebook. First is the Classic Notebook, which is the ipynb extension. Before being called a jupyter notebook, it was an Ipython notebook. That is why this extension.
Then you have your .py extension. Save the file with .py extension, and you can import the same to a different IDE for easier use. 

Close and Halt – This command closes whatever kernel is running at this particular point in time and halts all the processes.

run cells in Jupyter notebook - python tutorial for beginners
keyboard shortcuts in Jupyter - python tutorial for beginners

Edit Options

It includes Cut Cells, Copy Cells, Paste, Delete, Splitting a Cell, Moving up, down, so on and so forth.

So, What is a cell?
Cells are nothing but the code that you type in the dialogue box present on the window. This is a cell, where you type in your code — each cell when run will give you an output.

To run this particular piece of code, you can either click the specific option which says, Run cell or the shortcut key for the same is Shift + Enter

If you want to explore the other available shortcut options, you can get under Help in Keyboard Shortcuts. 

You can cut these cells, paste them later on. You can merge, split, so on and so forth. These are simple items.

View Options

You can Toggle your Headers, Toolbars, and Line numbers as well. 

Insert Options

These are basic insert operations. You can insert a cell above or below as per the requirement of your code. 

cell types in Jupyter - Python tutorial for beginners
what is markdown - python tutorial for beginners

Cell Options

If you hit Run All, it runs all the cells that are present in this entire workbook. When you click ‘Run All Above’, it runs all the cells above the selected cell. Similarly, if you click ‘Run All Below’, it runs all the cells that are below the selected cell.

The different types of cells, i.e., Code, Markdown and Raw Convert Files.
One exciting feature that we will be using much in our code files is something called Markdown file. A markdown is nothing but converting whatever you have typed in a cell into a text message.

The cells that you have converted as a Markdown will not be run or considered as a line of code. When you run this cell, it is taken as a text field, and the output is text too. No computation is carried out on this cell.

help options in Jupyter - python tutorial for beginners

Help Options

Here you can see the usual libraries and packages that are available.

You can click on these options, and it will open a guidebook or the reference book, where you can have a look at the various methods that are available within the selected package.
There are various other options you can experiment with when you are working with Jupyter.

Comments

Comments are useful to describe the program logic and purpose of various modules.  People other than the coder can understand the code by looking into the meaningful comments.

While testing the program, comments can be used to disable portions of code and are excluded from execution.

Python comment starts with the # symbol.  The comment may be its own or the comment may start after a code in the same line.  Both cases are explained in the below image.

# comment in separate line  
x = x * 5  
  
  
x = x * 5   # multiply by 5; comment in same line  
  
  
# this function is going to divide two variables  
# the second value should not be zero  
# if it is zero, error is thrown  
def divide(first, second):  

There is no different way to mention multiline comments.  # can be added to different lines.

When # is placed inside quotes, then it is part of the string and not a comment.

For example,

str = "# hello world" 

Variables

Python variables are containers to hold data.  These assigned data value to a variable can be changed at a later stage.

The first assignment of value to a variable creates the variable.  There is no explicit declaration of variable.

numOfBoxes = 7  
ownerName = "Karthik"  
print("numOfBoxes= ", numOfBoxes)  
print("ownerName= ", ownerName)  

In the above example, two variables with numeric and string data are created.  Print statements are used to display those variables.

Variable names follow these conventions.

  • Variable name begins with letter or underscore character
  • Alpha-numeric and underscores are allowed in the rest of name
  • Variable names are case-sensitive
# valid names  
numOfBoxes = 7  
_num_of_boxes = 10           # this is a different variable than numOfBoxes  
_NUM_OF_BOXES = 15   # a different variable as names are case sensitive  
  
ownerName = "Karthik"  
ownerName2 = "Charan" # different, valid variable  
  
  
  
# invalid names  
2ownerName = "David"    # cannot start with number.    
                                          # Only letter or underscore in the beginning  
owner-name = "Ram"       # no hypen  
owner name = "Krish"      # no space allowed  
                                          # only alpha numeric and underscore  

Here we have listed out some of the possible variable names and few invalid names.

In python, you can assign multiple values to many variables.  Also assign the same value to multiple variables. Please see this example.

# different values assigned to many variables  
length, width, depth = 5, 8, 7  
print(length)  
print(width)  
print(depth)  
  
# same value assigned to many variables  
length = width = depth = 5  
print(length)  
print(width)  
print(depth)  

Operators

Contributed by – papaprogrammer

Operators help in processing variables and values.  For example, if we can two numeric variables, they can be added or subtracted, multiplied or divided.  These operations change the value and give out new values.

Python supports the following categories of operators.

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

 Arithmetic operators

Mathematical operations like addition, subtraction are performed using arithmetic operators.  Let us go through them.

a = 10  
b = 6  
  
print (a + b)    # addition  
print (a - b)     # subtraction  
print (a * b)     # multiplication  
print (a / b)      # division  
print (a % b)    # modulus  
print (a ** b)   # exponentiation  
print (a // b)    # floor division  

All the operations are easy to understand.  Modulus operation returns the remainder of dividing two numbers (in our example, 4 is the reminder).  Similarly, floor division is integer division, which returns the result of division as whole integer (10 // 6 = 1).

Assignment operators

Values or variable content can be assigned to another variable using assignment operators.  The right-hand side can also be an expression (assignment to c in the following example). Here are a few examples.

a = 7  # assign value to a  
b = a  # assign value of a into b  
c = a + b -2  # calculate an expression and place result into c  
  
b += 2   # equivalent to b = b + 2  
b -= 2    # equivalent to b = b - 2  
b *= 2   # equivalent to b = b * 2  
b /= 2    # equivalent to b = b / 2  
b %= 2   # equivalent to b = b % 2  
b //= 2   # equivalent to b = b // 2  
b **= 2  # equivalent to b = b ** 2  
b &= 2   # equivalent to b = b & 2  
b |= 2    # equivalent to b = b | 2  
b ^= 2    # equivalent to b = b ^ 2  
b >>= 2  # equivalent to b = b >> 2  
b <<= 2  # equivalent to b = b << 2  

The last five operators will be explained in the later section below.

Comparison operators

Two values are compared and the result is a Boolean value True or False.  Used in if and loop statements to make decisions.

a = 3  
b = 7  
  
print(a == b)  # true if a and b are equal  
print(a != b)  # true if a and b are not equal  
print(a > b)  # true if a is greater than b  
print(a < b)  # true if a is less than b  
print(a >= b)  # true if a is greater than or equal to b  
print(a <= b)  # true if a is less than or equal to b  

Let us see an example of comparison in action.  Here we check if a is less than b. IF this condition is true, execute a statement.  Otherwise execute a different statement.

a = 3  
b = 7  
  
if(a < b):  
    print("first number is less than second one");  
else:  
    print("first number is greater than or equal to second one")  
  

Logical operators

Two or more comparison operations can be combined using logical operators.  These logical operators return Boolean value.

a = 5  
b = 8  
  
# True if both conditions are true  
print(a > 3 and a < 7)  
  
# True if one condition is true  
print(a > 6 or b < 7)  
  
# True if given condition is false (inverse of given condition)  
print(not(a > 3))  

Identity operators

Identity operators compare if two objects are the same.  They need to point to the same location.

a = ["hello", "world"]  
b = ["hello", "world"]  
c = a  
  
  
# prints true as both are same element  
print(a is c)  
  
# prints false as they are two diffent values  
# content may be same, but value locations are different  
print(a is b)  
  
# comparing the values gives true  
print(a == b)  
  
# not negates the comparison result  
# if two variables are not same, then result is true  
print(a is not c)  
print(a is not b)  

Membership operators

Checks if an element is present in a given list.

a = ["hello", "world"]  
  
# checks if given element is present in the a list  
print("world" in a)  
  
# checks if given element is not present in the a list  
print("world" not in a)  

Bitwise operators

While dealing with binary numbers, we need bitwise operators to manipulate them.  Binary numbers are zeros and ones, which are named as bits.

a = 1   # binary equivalent of 1 is  1  
b = 2   # binary equivalent of 2 is 10  
  
# In case of AND(&) operation, if both bits are 1, set result to one  
# in our case, two corresponding bits are not 1  
# so, corresponding result is 0  
print(a & b)  
  
# OR operation (|), gives 1 if either operands are 1  
# The reult of 0 and 1 is 1, 1 and 0 is 1  
# hence, a | b gives binary 11 or decimal equivalent of 3  
print(a | b)  
  
  
# XOR (^) returns 1 if only one of the operands is 1  
# 1 ^ 1 = 0, 0 ^ 0 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1  
# considering a and b, they have only ones in each bit position  
print(a ^ b)  
  
# NOT operation negates the bit value  
# NOT 0 = 1, NOT 1 = 0  
# while negating b, all preceeding zeros are turned to one  
# this leads to a negative number  
print(~ b)  
  
  
# zero fill left shift (<<)  
# zeros are filled from right, bits are shifted to left  
# left most bits fall off  
# in this example, we shift the bits of b twice  
# 10 (b) shifted twice is 1000 (which is decimal 8)  
print(b << 2)  
  
  
# signed right shift (>>)  
# shift the bits to the right, copy leftmost bits to the right  
# right most bits fall off  
# when we shift b (10) once to the right, it becomes 1  
print(b >> 1)  

Ternary Operator

Introduction Python Ternary Operator

We all know the different operators in python, i.e., Unary operators and Binary operators.

An operator that can be used to negate a positive value with one operand is called the unary operator; for example, x = -4, here we are negating a value 4 with operator –, so operator — acts as a unary operator.

An operator who works with two operands is called a binary operator; for example, x =, 3+7, the operator + acts as a binary operator.

The operator +,- acts as both Unary and Binary operators.

Now we know what the Unary and Binary operator is, so what is this ternary operator? Guess what? Yes, you are correct; an operator that works with three operands (components) is called a ternary operator.

The dictionary meaning of ternary is “composed of three items”, the operator evaluates something based on a condition, and the result is the true_value if the condition evaluates to TRUE else the result is the false_value.

The three components are (1) A condition (2) True value (3) False value.

Let’s write a simple if condition that evaluates a person’s age and tells whether the person is major or minor.

Age = 21
if (Age > 18):
    print("Major")
else:
    print("Minor")

We declared Age variable equal to 21; we then have an if/else statement that evaluates the Age value if age is greater than 18 then prints ”Major” else “Minor”.

To evaluate a simple condition, we have written 5 lines of code. Can we write the same code in a lesser number of lines? 

Yes, with the help of a ternary operator we can achieve this. This operator is available from Python version 2.4.

Syntax of Python Ternary Operator

As I said above, the ternary operator requires 3 components and the structure of these components as below:

So, the following code shows how can we transform the above lengthy code into a lesser number of lines using the ternary operator:

Age = 21
"Major" if (Age > 18) else "Minor"
#'Major'
Age = 15
"Major" if(Age > 18) else "Minor"
#'Minor'

That’s it! Component 2 is our condition ( if (Age > 18) ), which is evaluated first. If it evaluates to True, then “Major” is the output; otherwise, “Minor” is the output. In this case, Age > 18 evaluates to TRUE, so the output is “Major”.

Let’s decompose our improved code to match the structure of the ternary operator:

(1) A condition →if (Age > 18)

(2) True value →“Major”

(3) False value → “Minor”

Python Ternary operator in the return statement

We can use ternary operators in the function’s return statement. For example, writing a function that expects a person’s Age as input and returns the person is either “Major” or “Minor”.

def is_major(Age):
       return 'Major' if Age > 18 else 'Minor'
is_major(21)
# 'Major'
is_major(15)
'Minor'

The above code shows how we can use the ternary operator in a return statement; we have used the ternary operator structure directly in the return statement.

ShortHand Ternary operator

We also have a shorthand form of the ternary operator that we discussed above, which will quickly test a function’s output. This type of syntax introduced in Python 2.5 and can be used in python 2.5 or greater.

True or NULL
# True
False or 1
# 1

The first statement (True or “NULL”) will return True, and the second statement (False or “1”) will return 1.

You can use this syntax to test a variable value:

known_number = None
msg = known_number or "Unknown number"
print(msg)
#Unknown number
known_number = 5634
msg = known_number or "Unknown number"
print(msg)
# 5634

This will be useful when you quickly test a user input in a function:

def choice_name(person_name, person_nick_name):
display_name = person_name or person_nick_name
print(display_name)
# function call with name and nick name as none
choice_name(person_name ="Jospeh",person_nick_name =None)
#Jospeh
# function call with name as none and nick name
choice_name(person_name = None,person_nick_name ='Joe')
# Joe

The above function takes the person name and nickname as arguments and use the shorthand ternary operator syntax and results in displaying the person’s name; this will become handier to test the two variables and results in the only TRUE values.

Ternary operator with if-else-if statement

Let’s write a function that evaluates multiple if conditions and return the result.

floors = 12
if (floors <= 3):
	print('Low rise building')
elif(floors >3 and floors <=7):
	print('Mid-rise building')
else:
	print('High rise building')
#High rise building

The above If…elif code evaluates a number of floors value and result is the category of building, i.e., if the floors are greater less than or equal to three floors, then it is categorized a “Low rise building” else if the floors are greater than three but less than or equal to 7 then its is categorized as “Mid-rise building ” else it is categorized as “High rise building”.

With the help of a ternary operator, we can write this code in a small number of lines, But how? The ternary operator structure says only 3 components, but here we have multiple conditions, don’t worry, we also nest the ternary operator just like nested if. 

floors = 12
'Low rise building' if (floors <= 3) else 'Mid-rise building' if(floors >3 and floors <=7) else 'High rise building'
#'High rise building'

floors = 7
'Low rise building' if (floors <= 3) else 'Mid-rise building' if(floors >3 and floors <=7) else 'High rise building'
#'Mid-rise building'

floors = 2
'Low rise building' if (floors <= 3) else 'Mid-rise building' if(floors >3 and floors <=7) else 'High rise building'
# Low rise building

Lambda

Earlier we saw function definition and function calls. Lambdas are anonymous, small functions.  The body of the lambda can have only one expression. Lambda can take any number of arguments.

# a lambda function with the name growth is created  
# it takes one argument and increase it by 2  
growth = lambda givenLength : givenLength + 2  
print(growth(25))  # prints 27  
Let us take another example with many parameters:
# lambda with the name area is created  
# two parameters are passed, who area is calculated  
area = lambda length, breadth: length * breadth
print(area(4, 7))  # prints 28  

The lambdas are useful when nested within another function.  The function becomes a template to create a function.

# the growth lambda we wrote earlier  
def growth(n):  
    return lambda a : a + n  
  
# create a function that would increase by 2  
strechTwo = growth(2)  
  
# create a function that would increase by 3  
strechThree = growth(3)  
  
print(strechTwo(7))  
print(strechThree(7))  

In the above example, using the same function growth, we spawn different functions strechTwo and strechThree.  This is possible with the lambda function declared inside the growth function. We get the output 9 and 10 by running this code.

Arrays

Arrays are used to store a list of values in a variable.  Here is the syntax to create an array. Square brackets are used to define a list.

fruits = ["mango", "apple", "grapes"]  
print (fruits)  

Arrays allow us to access the array elements using index.  The index are zero based, they start from zero.

fruits = ["mango", "apple", "grapes"]  
firstFruit = fruits[0]  
print (firstFruit)  

Similar to accessing the element, we can modify the element using index.

fruits = ["mango", "apple", "grapes"]  
fruits[0] = "melon"  
print (fruits)  

The number of elements in an array can be known by using the len() method.

fruits = ["mango", "apple", "grapes"]  
print (len(fruits))  # prints 3  

for statement is used to loop through the array elements.  We can process individual elements inside the loop.

fruits = ["mango", "apple", "grapes"]  
  
for fruit in fruits:  
    print(fruit)  
      

append() method adds a new element to the end of the array.

fruits = ["mango", "apple", "grapes"]  
  
fruits.append("guava")  
print(fruits)  

Two methods are useful to remove elements from the array.  pop() method takes the array index and removes the element in the particular position (remember the elements are zero based).  remove() accepts the value of the element and removes it. Let us see these two methods in action.

fruits = ["mango", "apple", "grapes"]  
  
fruits.pop(1)  
print(fruits)  
  
fruits.remove("grapes")  
print(fruits)  

Classes

Objects are entities that possess properties and methods.  These objects can be created by declaring classes. Classes are blueprints of objects.

In this example, we see how to define a class, create objects out of the class and access the property of the object.

# create a class with "class" keyword  
class Fruit:  
    # a property, "name" is created  
    # the property is assigned with the value "mango"  
    name="mango"  
  
# let us create an object, "oneFruit" using the above class  
oneFruit = Fruit()  
  
# the property of the object "oneFruit" is accessed like this  
print(oneFruit.name)  

All classes have an inbuilt function, __init__()
This function is called when a new object is created from the class.  This function is called automatically when the object is created.

We can write useful initialization code in this function, so that variables are set at the time of object instantiation. 

# create a class with "class" keyword  
class Fruit:  
    # define the init function  
    def __init__(self, name, color):  
        self.name = name  
        self.color = color  
  
# let us create an object, "oneFruit" using the above class  
# values are passed to the class  
oneFruit = Fruit("mango", "yellow")  
  
# the property of the object "oneFruit" is accessed like this  
print(oneFruit.name)  
print(oneFruit.color)  

In the above example, we used a parameter “self”.  There are three parameters defined in the init function, however we passed only two arguments in the class invocation.  The self-parameter is automatically passed to the class’s method. The name “self” is not fixed, you may use any name. It has to be the first parameter. 

Apart from the inbuilt methods, the class can have other user defined methods.  Let us create a makeJuice() method inside the class.

# create a class with "class" keyword  
class Fruit:  
    # define the init function  
    def __init__(self, name, color):  
        self.name = name  
        self.color = color  
  
    def makeJuice(self):  
        print("Made " + self.name + " juice. It will be in " +   
            self.color + " color.")  
  
# let us create an object, "oneFruit" using the above class  
# values are passed to the class  
oneFruit = Fruit("mango", "yellow")  
  
# invode object's method  
oneFruit.makeJuice()  

The property of the object can be modified like this:
oneFruit.color = "red"  

Inheritance

Inheritance is a concept where we extend the functionality of a class to create new classes.  There are many benefits of doing this. Foremost is to reuse existing code.

The existing class has generic code that can be reused.  This class is called parent or base class.

We create a child class that would receive the definition from the parent class.

Let us consider a parent class, Vehicle.  This has properties and methods suitable to describe any vehicle.

class Vehicle:  
    def __init__(self, make, color):  
        self.make = make  
        self.color = color  
  
    def display(self):  
        print("make= " + self.make + " color= " + self.color)  
  
v = Vehicle("2015", "green")  
v.display()  

Two properties, make and color, are defined in the Vehicle property.

Let us extend a child class, Car, from the Vehicle class.

class Vehicle:  
    def __init__(self, make, color):  
        self.make = make  
        self.color = color  
  
    def display(self):  
        print("make= " + self.make + " color= " + self.color)  
  
# v = Vehicle("2015", "green")  
# v.display()  
  
class Car(Vehicle):  
    def __init__(self, make, color, numOfSeats):  
        super().__init__(make, color)  
        self.numOfSeats = numOfSeats  
  
    def display(self):  
        super().display()  
        print("number of seats= " + str(self.numOfSeats))  
  
    def wipeWindshield(self):  
        print("turned on wiper")  
  
newCar = Car("2019", "orange", 5)  
newCar.display()  
newCar.wipeWindshield()  

There are many points to be noted in this code.

Line 12 defines a class, Car.  This is an extended Vehicle (mentioned in the paranthesis).

Line 13 is the constructor of Car.  Three parameters are accepted.

Line 14 invokes the constructor of the parent, Vehicle class.  Two parameters are passed to the parent’s constructor.

Line 15 initializes an object property, numOfSeats.  This property belongs to Car and does not exist in Vehicle class.

Line 17 redefines the method display().  In the method’s code, parent method is called, as well as code is there to express functionality of the Car object.

Line 21 defines a method that belongs to the Car class.

Line 24 to 26 creates a Car object, handles Car properties and invokes various methods.

Iterators

Iterator is a container of values, with which we can traverse through all the values.

In Python, an iterator is an object that implements __iter__() and __next__().

Lists, tuples, dictionaries, and sets are iterable and implement an iterator protocol.  These containers have iter() method that are used to traverse the values.

Here is an example.

fruitTuple = ("mango", "apple", "grapes")  
  
fruitIter = iter(fruitTuple)  
  
print(next(fruitIter))  
print(next(fruitIter))  
print(next(fruitIter))  

A string can be iterated using iter() method.

fruitStr = "mango"  
  
fruitIter = iter(fruitStr)  
  
print(next(fruitIter))  
print(next(fruitIter))  
print(next(fruitIter))  
print(next(fruitIter))  
print(next(fruitIter))  
print(next(fruitIter)) # last call throws error  

Note that the first five next () call print each character of “mango”.  The final next () throws an error saying the iteration has stopped.

The iterable object can be iterated with the for in loop.

fruitTuple = ("mango", "apple", "grapes")  
  
fruitIter = iter(fruitTuple)  
  
for fruit in fruitTuple:  
    print(fruit)  

We can create our own iterator class.  We need to implement __iter__() and __next__() methods.

Remember __init__() we saw in class definition?  The iterator method and protocols are similar to init of the class.

Let us consider an example that would create an iterator.  The iterator is a Fibonacci series starting from 1, 2.

class Fibonacci:  
    def __iter__(self):  
        # define first two numbers  
        self.first = 1  
        self.second = 2  
        return self  
  
    def __next__(self):  
        curr = self.first + self.second # find new number  
        self.first = self.second # shift the previous two numbers  
        self.second = curr  
        return curr  
  
fibo = Fibonacci ()  
fiboIter = iter(fibo)  
  
print(next(fiboIter))  
print(next(fiboIter))  
print(next(fiboIter))  
print(next(fiboIter))  
print(next(fiboIter))  

when line 15 iter(fibo) is called, __iter__() is invoked internally.  When next(iter) is called, __next__() method is invoked to find the next element in the series.

This iterator is never ending as there is no termination control.

To prevent the endless series, we can add a StopIteration statement.  In the __next__, we can add a condition and use StopIteration.

class Fibonacci:  
    def __iter__(self):  
        # define first two numbers  
        self.first = 1  
        self.second = 2  
        return self  
  
    def __next__(self):  
        curr = self.first + self.second # find new number  
        if (curr <= 50):  
            self.first = self.second # shift the previous two numbers  
            self.second = curr  
            return curr  
        else:  
            raise StopIteration  
  
fibo = Fibonacci ()  
fiboIter = iter(fibo)  
  
for f in fiboIter:  
    print(f)  

In this sample, we check if the Fibonacci series has reached 50.  Any value beyond or equal to 50 would raise an error. That would stop the for loop.

Scope

The variable is available only in the region that it is declared.  The limitation of such variable declaration is scope. The scope of variable or method defines where those elements are accessible.

def func1():  
    a = 5  
    print(a)  
  
func1()  
print(a)  

The last print statement throws error as a is not accessible at the main part of the code.

One way to have access to the variable at all places is to declare the variable at global scope.  Variable created at the main level is global and can be accessed inside the function definition.

a = 5  
  
def func1():  
    print(a)  
  
func1()  
print(a)  

Now both the print statements have access to the variable.

When the same name is used for variables inside and outside a function, then python treats them as two separate variables.

a = 5  
  
def func1():  
    a = 7  
    print(a)  
  
func1()  
print(a)  

If we change the value of a inside the function, that change won’t affect the variable outside the function.

While a variable is defined inside a function, the variable can be declared as global using the “global” keyword.

def func1():  
    global a  
    a = 10  
    print(a)  
  
func1()  
print(a)  

Modules

Module is about using library files.  You create a python library file with general functions and variable declarations. These definitions can be referred to by another python file.

Following functions and values are defined in inventory.py

fruits = ["mango", "apple", "grapes"]  
  
def countStock():  
    return len(fruits)  

In order to use this function and array, we will have to import this library in our main code file.

import inventory  
  
print(inventory.countStock())  
print(inventory.fruits)  

Line 1 imports the inventory library.  Line 3 and 4 refers to the function and variables declared in the library.

The library name can be changed to a suitable name.  In the following code, we change the library name to inv.  This change is local to our code.

import inventory as inv  
  
print(inv.countStock())  
print(inv.fruits)  

We don’t have to import all the elements from the library.  We can be choosy in importing. The from clause is used to import part of the module.

from  inventory import  countStock  
  
print(countStock())  
print(fruits)  

In the above code, function countStock returns expected results.  However, fruits are undefined and throw errors.

There are many built-in modules in python, that can be used in the above styles of import.

Dates

By importing the module, datetime, we can work with dates in python.

import datetime  
  
today = datetime.datetime.now()  
print(today)  

We get to print the current date and timestamp.

We can also create a date object with specific date value.   The datetime object’s constructor accepts year, month and day to create a date.

import datetime  
  
pastDate = datetime.datetime(2020, 2, 29)  
print(pastDate)  

In the above constructor call, hours, minutes, seconds, milliseconds are optional.  Zero is their default value.

Datetime has a way to format the date value.  The datetime object exposes the strftime() method that formats the object’s date value.  Strftime() accepts a format string as input and returns formatted output.

import datetime  
  
pastDate = datetime.datetime(2020, 2, 29)  
print(pastDate.strftime("%B"))  

%B returns a full month’s name.

Other format details are as mentioned in this table.

DirectiveDescriptionExample
%aWeekday, short versionFri
%AWeekday, full versionFriday
%wWeekday as a number 0-6, 0 is Sunday2
%dDay of month 01-3122
%bMonth name, short versionMar
%BMonth name, full versionMarch
%mMonth as a number 01-1210
%yYear, short version, without century19
%YYear, full version2020
%HHour 00-2315
%IHour 00-125
%pAM/PMPM
%MMinute 00-5937
%SSecond 00-5923
%fMicrosecond 000000-99999942875
%zUTC offset50
%ZTimezoneCST
%jDay number of year 001-366365
%UWeek number of year, Sunday as the first day of week, 00-5352
%WWeek number of year, Monday as the first day of week, 00-5352
%cLocal version of date and timeSat Feb 29 18:23:00 2020
%xLocal version of date02/29/20
%XLocal version of time13:57:00
%%A % character%

Random Number Generator in Python

WHAT ARE RANDOM NUMBER GENERATOR:

                               Generators are functions that produce items whenever they’re called. Random Number Generator in Python is an inbuilt function that assists you to generate random numbers whenever required. These all functions are built-in within the random module of python.

GENERATING INTEGERS:-

                        If we talk about the random integers, they can be generated using randrange() and randint(). Let’s see how these two functions works,

                  RANDINT()RANDARANGE()
DEFINITIONThis function generates integers that are in between a given limit. It takes two parameters in which the first parameter specifies the lower limit of the range and the second specifies the upper limit of the given range. randint(a,b) starts generating values from a to b such that:a <= x <= b   (includes a and b)As mentioned earlier, the randrange() function, allows the user to generate values by stepping over the interval count.
EXAMPLE Import randomRandom.randint(1,8)Import randomFor x in range(4):   Print(random.randarange(2,40,2)
OUTPUT6814263
EXPLANATIONThe above code generates any number between the range 1 and 8.The above code generates 4 numbers (given in range) within 40 as specified and gives only even number as specified as 2,x,2.

GENERATING FLOATING POINT VALUES:-

                       You can make use of the random() and the uniform() functions to generate floating-point numbers.

                  RANDOM()UNIFORM()
DEFINITIONThe random() function produces floating-point values between 0.0 to 1.0 and takes no parameters. The upper limit is excluded; therefore, the maximum value will be 9.999.Unlike random() function, the uniform() function takes two parameters that determines the lower and the upper limits respectively.
EXAMPLE Import randomFor x in range(3): Print(random.random())Import randomFor x in range(3):   Print(random.uniform(5)
OUTPUT0.2983393871094
0.9649267263738
0.980860867699
3.9659759597658
2.760760876876
1.8758567596609
EXPLANATIONThe above code generates decimal numbers with any number of digits by keeping the whole number as 0, and it gives only 3 numbers because the number 3 is specified in the code.The above code generates decimal numbers with any number of digits after the dot. It gives only 3 numbers as specified and the uniform operator gives the whole numbers within as specified in the code.

GENERATING VALUES FROM A GIVEN SEQUENCE:-

  1. CHOICE():

This function takes a sequence as a parameter and returns random values from it. In this, function is the python programming language that will return the items from the strings, list, tuple.

EXAMPLE:

for x in range (2):
       print(random.choice(([1,2,3,4,5,6,7,8,9]));

OUTPUT:-

3

6

EXPLANATION:-

 The above code generates a random number given in the list and gives only 2 numbers as specified in the code.

  1. SAMPLE():-

This function picks up a random sequence from the sequence provided and returns it as the output. It takes two parameters where the first parameter is a sequence and the second is an integer value specifying how many values need to be returned in the output.

EXAMPLE:-

print(random.sample([2, 3, 4, 5, 6, 7, 8], 3));

OUTPUT:-

 2, 5, 8

EXPLANATION:-

The above code generates random 3 numbers given in the list and those give only 3 random numbers because 3 is specified above in the code.

  1. SEED():-

This is used to save the state of the random functions and is greater than some random numbers and the multiple executions of the same or different machines and for a specific seed value.

EXAMPLE:-

Import random
Random.seed(2)
Print(random.random())
Random.seed(2)
Print(random.random())

OUTPUT:-

0.9560342718892494

0.9560342718892494

EXPLANATION:-

As the above code generates seed(2), the output of the code remains the same for each time. This might be useful if we want to pass the random numbers in various test cases.

  1. SHUFFLE():-

It is used the sequence like shuffling means and changing the positions of the elements.           

EXAMPLE:-

import random
list = [1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(list)
print(list)

OUTPUT:-

[4, 5, 2, 1, 6, 8, 7, 3]

EXPLANATION:-

In the above code, the input list has been shuffled, and a new list has been formed in the output. 

JSON

JSON stands for Javascript object notation.  It is a text format useful to exchange data and store information.  

Python has a built-in module, called json, to handle json data.

The json string can be parsed into json data using json.loads() method.  json.loads method returns the json data a dictionary.

import json  
  
jsonStr = '{ "name" : "mango", "price" : 100, "color" : "yellow" }'  
  
jsonData = json.loads(jsonStr)  
print(jsonData["color"])  
print(jsonData)  

json.dumps() is used to convert python objects into json strings.

import json  
  
fruitsDictionary = { "name" : "mango", "price" : 100, "color" : "yellow" }  
  
jsonStr = json.dumps(fruitsDictionary)  
  
print(jsonStr)  

We can give indentation to improve the readability of the generated output string.

import json  
  
fruitsDictionary = { "name" : "mango", "price" : 100, "color" : "yellow" }  
  
jsonStr = json.dumps(fruitsDictionary, indent=5)  
  
print(jsonStr)  

We can sort the order of the keys in the dumps method.

import json  
  
fruitsDictionary = { "name" : "mango", "price" : 100, "color" : "yellow" }  
  
jsonStr = json.dumps(fruitsDictionary, indent=5, sort_keys=True)  
  
print(jsonStr)  

Regular expression

Regular expression is a powerful search mechanism, where we have a string pattern and look for matching substring in a given full string.

re module is imported to use regEx library functions.

import re  
  
givenStr = "Hello world, good morning"  
outRegex = re.search("^Hello", givenStr)  
print(outRegex)  

outRegex is an object generated by the search method. The search looks for a string Hello at the beginning of the string.

PIP

In the module section, we saw how to import modules into our code and use the elements from those libraries.

PIP is a package manager that helps in installing required modules.

pip install <package-name>

This is the syntax to install a package.  This need to be run in a command prompt window.

If pip is not installed in your machine, please download from https://pypi.org/project/pip/

Sample install is:

pip install HTMLParser

pip uninstall <package-name>

This command will uninstall the installed package

pip list

will display all packages installed in this machine.

Try, Except

Try block watch for any error thrown in the block.

Except block handles any error thrown.

When we don’t use try and except, python will throw error and halt the program.  By using try, except, we handle the errors in our code and avoid code termination.

try:  
    print(a)  
except:  
    print("error occured, please check if a is defined")  

Here a is undefined.  Error is thrown, which is handled by the except block.

finally is a block that gets executed after try and except are executed.  This gets the control irrespective of if error occurred or not. We can write cleaning operations like closing file handles in this finally block.

try:  
    print(a)  
except:  
    print("error occured, please check if a is defined")  
finally:  
    print("We are here after try and except")  

We can write code to raise custom errors.  The error thrown can be handled by our try, except or the python engine can receive the error.

a = 0  
  
if a == 0:  
    raise Exception("cannot divide by zero")  

User Input

Most of the programs need to get input from users and generate output.  In python, input() method is used to accept input from user.

city = input("Where do you live? ")  
print("city you live is : " + city)  

String Formatting

string variables can be formatted with format() method.  The template string is created first and values are attached at the formatting stage.

tStr = "The fruit {} is {} color."  
print(tStr.format("mango", "yellow"))  
print(tStr.format("apple", "red"))  

You may refer to the values using index.  The index is zero based.

tStr = "The fruit {0} is {1} color. {0} is good for health"  
print(tStr.format("mango", "yellow"))  
print(tStr.format("apple", "red"))  

Similar to indexed reference, we can use names of the parameters.

tStr = "The fruit {name} is {color} color. {name} is good for health"  
print(tStr.format(name = "mango", color = "yellow"))  
print(tStr.format(name = "apple", color = "red"))  

Python Data Types

Python supports five standard data types which further might have sub-types. The data types that are used to define the operations possible on them and the storage method for each of them.

Here are the five data types

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary

Let us have a look at all these data structures and understand how to use them with examples:

Numbers

This data type stores numeric values where Python creates a number object and a number is assigned to a variable.

Example:

a=4
b=6

Here, a and b are number objects.

Python supports four types of numeric data; they are-

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers with imaginary number represented with ‘j’)

Lower case L can be used in case of long integers, however, upper-case L should always be used to avoid confusion.

String

A sequence of characters which are represented in quotation marks are known as a string. A single, double or triple quotes can be used to define a string in Python. If string handling needs to take place, there are inbuilt operators provided. This makes it straightforward and easy to use.

Example: “hello” +” python” will return “hello python”

The operator * is called a repetition operator. The operation “Python ” *2 will return “Python Python “

Let us take a look at another example-

str1 = 'hello javatpoint' #string str1   
str2 = 'how are you' #string str2   
print (str1[0:2]) #printing first two character using slice operator    
print (str1[4]) #printing 4th character of the string  
print (str1*2) #printing the string twice 
print (str1 + str2) #printing the concatenation of str1 and str2    

Output:

he  
o 
hello javatpoint hello javatpoint
hello javatpoint how are you

List

A list can contain data of different types, it is similar to arrays in C. Items which are stored in the list are separated with a comma and should be enclosed within square brackets [].

To access data from a list, slice [:] operators should be used. Repetition operator (*) and concatenation operator (+) work the same way in strings as well as list.

Take a look at the following example-

l  = [1, "hi", "python", 2]
print (l[3:])
print (l[0:2]) 
print (l)
print (l + l)  
print (l * 3)      

Output:

[2]  
[1, 'hi'] 
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

Tuple

There are many similarities between tuple and list. Tuple contains the collection of items of different data types, these items are separated with a comma (,) and need to be enclosed within parentheses ().

The size and value of items in a tuple cannot be modified since it is a read-only data structure.

Let us take a look at one example-

t  = ("hi", "python", 2)  
print (t[1:])  
print (t[0:1])  
print (t)  
print (t + t)  
print (t * 3)   
print (type(t))  
t[2] = "hi"  

Output:

('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment 

Dictionary

A dictionary is like an associative array where each key stores a specific value. It is an ordered set of key-value pair items. A key is capable of holding any primitive data type. Value is an arbitrary Python object. Each item in a dictionary is separated using a comma and is enclosed within curly brackets {}

Let us take a look at the following example-

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
print("1st name is "+d[1])
print("2nd name is "+ d[4])  
print (d)  
print (d.keys())  
print (d.values())  

Output:

1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']

Flow control statements

Conditional statements (if-else statements)

These commands help you make decisions based on conditions such as ‘if’ a specific condition occurs then you have to perform a set of operations, ‘else’ you have to perform another set of operations.

Let us see how it works:

First, we will define some variables and assign values to them. Next, we will perform some basic ‘if’ ‘else’ operations on these variables.

a=10
b=20
if (b>a):
    print (b is greater than a) 

Output

b is greater than a

In the above computation, the if condition is true hence we get the output. Now, let us try ‘if’ function with a false statement.

if (a>b):
    print (“a is greater than b”)

For this statement, we will not get an output because the if condition stands false.

Now, let’s include the else statement.

if (a>b):
    print (“a is greater than b”)
else:
    print (“b is greater than a”)

Output:

b is greater than a

Next, let us explore the ‘elif’ function for multiple conditions:

a=10
b=20
c=30
if (a>b) & (a>c):
    print (“a is the greatest”)
elif (b>a) & (b>c):
    print (“b is the greatest”)
else: 
    print (“c is the greatest”)

Output:

c is the greatest

You can also implement if and else functions on the different data structures such as tuple, list, string, etc. Let us look at an example with a list.

l1 = [10,20,30,40,50]
if l1[0]==10:
    l1[0]=100
l1

Output:

[100,20,30,40,50]

Looping (while and for statements)

Looping statements are used to repeat a task multiple times. Let us look at how it works.

First, we will define a variable and assign a value to it. Next, we will implement ‘while’ function to it.

i=1
while (i<=5):
    print(i)
    i=i+1

Output:

1
2
3
4
5

So, what is happening here? Since, i=1, which is less than or equal to 5, the while loop stands and the value of ‘i’, i.e., ‘1’ is printed. As per the next command, the value of ‘i’ will be updated to ‘2’.

Again, as ‘2’ is less than or equal to ‘5’, we will again enter the while loop and print the value of ‘i’, which is now ‘2’. This goes on until the value of ‘i’ becomes ‘5’. After that, when the value of ‘i=6’, i.e., it is not less than or equal to ‘5’, the while statement stands false and hence the computation stops there. 

Let us take another example where we have to print the table of ‘2’ to ten values. Let us have a look at how to use while loop for the same.

i=1
n=2
while(i<=10):
    print (n, “ * ”, i, “ = ”, n*i)
    i=i+1

Output:

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Just like conditional statements, you can also implement while functions on the different data structures such as tuple, list, string, etc. Let us look at an example with a list.

li=[1,2,3,4,5]
i=0
while i<len(l1);
    l1[1]=l1[i]+100
    i=i+1
l1

Output:

[101,102,103,104,105]

Next, let us take a look at where and how to use a for loop. For loop is used to iterate over a sequence, let us head to the code to understand the functionality of the for loop.

l1 = [“blue”,“green”,”red”]
for i in l1
    print(i)

Output:

blue 
green 
red

Now, let us see how to create nested for loops, i.e., a for loop inside a for loop.

color = [“green”,“yellow”,“pink”]
item = [“chair”,“book”,“phone”]
for i in color:
    for j in item:
        print(i,j) 

Output:

green chair
green book
green phone
yellow chair
yellow  book
yellow  phone
pink chair
pink book
pink phone

So this is all about the flow control statements. You can apply these functions and loops in many ways as required for the type of data you are working with and the type of problem you are trying to solve. 

File handling

Python supports many functions to create, read, write and delete files.  These operations are crucial in most of the applications.

open () function opens the function for further processing.  open () takes two parameters, one is the file name we want to operate and other is a mode.

mode deals with the operation we want to perform.  It could be read (r) or append (a) or write (w) or create (x)

Further, we can specify if the file is binary (b) or text (t) file.

Create a text file with some content in the name fruits.txt.  Place this file in the same directory as the python code we are writing.

Consider this example.

f = open("fruits.txt") 

Here the default mode is assumed.  By default, text file is opened in read mode.  The above statement can be written as :

f = open("fruits.txt", "rt")  

The open returns a file object.  This file object is used to read or write into the file.

f = open("fruits.txt")  
print(f.read())  

The read method of file object loads the content of the text file and returns as a string.

Instead of reading the whole line, we can read lines at a time.  readline() method returns one line of text. We can call readline any number of times, until the file has text content.

f = open("fruits.txt")  
print(f.readline())  
print(f.readline())  

The first two lines are displayed in this code.

All the lines can be read within a for loop.

f = open("fruits.txt")  
  
for line in f:  
    print(line)  

When the file usage is over, it is better to close the file.   This releases the handle and other resources associated with the file and file open command.

f = open("fruits.txt")  
  
for line in f:  
    print(line)  
  
f.close()  

Writing into a file is possible by-passing appropriate modes.  append (a) mode will add new strings to the end of the file. write (w) mode will remove existing content of the file and write the new string alone into the file.

f = open("fruits.txt", "a")  
f.write("guava is green")  
f.close()  
  
f = open("fruits.txt")  
  
for line in f:  
    print(line)  
  
f.close()  

By running this code, we add the new string to the existing file and display the whole content.

If we replace mode “a” with “w”, the whole text file (existing content) will be erased and only the new string will be available in the file.

mode x is used to create a new file.  If the file already exists, x will throw an error saying file already exists.

f = open(“fruits.txt”, “x”)  

Also, mode x and w will create new file if the file does not exist.

The os library is used to delete folders and check if files exist.

import os  
  
os.remove("fruits.txt")  

Here we have deleted the file. Error is thrown if the file doesn’t exist.

You may check if the file exists or not by using the exists() method of os.path object.

import os  
  
filename = "fruits.txt"  
  
if os.path.exists(filename):  
    os.remove()  
else:  
    print(filename + " does not exist")  

A folder can be deleted with rmdir() method of os module.

import os  
  
os.rmdir("unwantedFolder")  

Creating Functions in Python 

A function is a block of code that is reusable. It is used to perform a single, related action and one can directly call the function when they need to perform that action, often as a part of a bigger code. Just call the function and input required values to the variables and hence eliminate the need for writing lengthy codes every time you need to perform the same action.

To create functions in Python, we will use the ‘def’ method. Any input parameter or arguments need to be placed inside the parenthesis with the functions name while defining it. The code block within every function starts with a colon (:) and is indented. Finally, return [expression] exits a function. Look at the example below.

 def add_10(x):
     return (10+x)

Let us see what output we get when we invoke this function.

add_10(5)

Output:

15

Let us have a look at another example of defining a function using if and else.

Learn Simple Commands by Using Python as a Calculator

To insert a comment in Python, start the sentence with the hash character, i.e., #. A comment may appear at the start of a line. It might also follow a code or a white space. Comments are explained below with the help of some examples.

 # This is a comment
counter = 100     # This is a comment which follows a code
                  # This is a comment which follows a white space
text = "# This is not a comment as the hash character is inside the quotes."

Let us run some simple commands. Start the interpreter and wait for the primary prompt, i.e., >>>. Let us now see some simple commands and their results. Here are the basic mathematical operations such as sum, difference, multiplication, and division.

>>> 2 + 2
4
>>> 50 - 5*4
30
>>> (50 - 5*4) / 6
5
>>> 8 / 5
1.6

The division always provides a floating value as an output. If you want to display the integer result and remainder separately, the command would include “//” to display integer value after division, and % will display the remainder.

>>> 16 / 3
5.333333333333334
>>> 16 // 3
5
>>> 16 % 3
1

In Python, you can use ** to calculate powers.

>>> 5 ** 2
25
>>> 3 ** 4
81

Next, the symbol (=) is used to assign values to a variable.

>>> height = 20
>>> width = 9 * 5

When working in the interactive mode, the last printed value is assigned to the variable (_), i.e., underscore. Hence, one can recall the last printed value by calling the variable _. Let us have a look at the example below where we calculate tax levied on the price of a product.

>>> tax = 12.5 / 100
>>> price = 110.50
>>> price * tax
13.8125    # this is the last printed value, hence assigned to _
>>> price + _
124.3125   # now this becomes the last printed value, hence assigned to _
>>> round(_, 2)  # this is the command to round off the value to two decimal places
124.31 

Data Manipulation with Pandas

Pandas stands for Panel Data. It is the core library for data manipulation and data analysis. 

NumPy provides us with a multidimensional array, similarly, Pandas provides us with a multi-dimensional data structure to perform various data manipulation operations. 

Pandas provides us with both single-dimensional and multidimensional data structures. 

The single-dimensional data structure is called a series object; the multidimensional data structure is known as data-frame.

In Python, we’ll mainly be working with data-frames. This is because, Machine Learning algorithms such as linear regression, logistic regression and so on, are all applicable on data-frames. All the data sets available to us can be converted into a data-frame in Python and all manipulations can be done on this. 

In Pandas, the series object is a one-dimensional labelled array. When we consider NumPy array, it is not labelled. 

Pandas Series object

Let us take a look at how to create a series object using Pandas. Pandas are pre-installed in Anaconda, hence, we will not have to install it manually. 

First, we would have to invoke the Pandas library. To do this, type in-

import pandas as pd

Here, ‘pd’ is an alias for Pandas. 

Once Pandas has been imported, we can create the first series object. Let us name it as s1.

s1= pd.Series ([1,2,3,4,5]) 

We must keep in mind that S should always be a capital letter. A series object has now been created. 

Take a look at the image for reference. 

This is how a series object is created. As you can see, the values 10,20,30,40,50 are int64 type. And 0,1,2,3,4 are the labels associated with each of these values. These values can either be known as labels associated or index values. 

If you wish to change the index in a panda series, you can do it by adding an index attribute as shown in the following image. 

This allows us to choose the value associated or the index value corresponding to the series list.

Series object from Dictionary 

Now that we have seen how to create a series object with the help of lists, we can take a look at how it is done with the help of a dictionary. 

In case of a dictionary, the key automatically becomes the index and the values will stay as the actual values of the index. 

Here, the index is k1, k2 and k3 and the values are 10,20 and 30 respectively. 

Pandas Data-frames

A data-frame is a two dimensional labelled data structure and it comprises rows and columns. Normally, in a data-frame, all the elements in a particular column are of the same type. 

For example- If we consider a column which contains the names of people, all of them would be a string type value. If we consider a column containing the marks of these individuals, they would be of an integer type. 

Let us create a data-frame named ‘student’. We’ll list the names of the students inside the data-frame and also the marks which each student obtained, this creates a dictionary. 

To create the data-frame using the dictionary we created, we need to type pd.DataFrame(student) 

Refer the image below for reference and to see the output for the same.

The key becomes the column name and the list of values for a particular key becomes the row values for that column. In simpler words, the key here is student_name and the row values are Bob, Sam, Julia and Charles. 

This is basically how a data-frame is created in Pandas. 

There are a few inbuilt functions which can be performed on any data frame. They are – head(), shape(), tail() and describe(). If we want to separate individual rows and columns from a data frame, we can use any of these two methods. They are .iloc[] and .loc[] method. 

These are some of the data manipulation methods which can be done with Pandas. 

Python Tutorial FAQs

1. How do I start python for beginners?

As a beginner, it is quite confusing to decide where to begin your learning journey. There are a number of resources available online through which one can learn Python for Beginners. Depending on what learning method suits you, you can learn through video content, blogs, free online courses, and more. Great Learning Academy offers a Python for Machine Learning Free Online Course that you can take up as a beginner. This course will help you enter the field of Python.

2. What are the steps to learn Python?

Start with the basic concepts in Python. Learn what Python means, where it is used, and how to install Python. Post this, start learning the basic Syntax involved in Python. If you want a guided step-by-step process of learning Python, you can take up free online courses to learn. Check out this free python course with certificate and get started with Python.

3. How can I learn Python fast?

Beginners in the field of Python prefer to learn the programming language due to its simplicity and versatility. To learn Python fast, start with the basics. Learning the fundamentals will give you a clear idea of the language. Practicing programming and working on various projects with also help you learn quickly and through practical exposure.

4. Can a beginner learn Python?

Yes. Python is an object-oriented programming language that is known for it’s simplicity. Most beginners in the field of development prefer to learn Python.

5. Can I learn Python without any programming experience?

Yes. You can learn Python without any prior programming experience or knowledge. Python is great for beginners due to its simple Syntax.

6. How much time does it take to learn Python?

The time taken to learn Python would depend on the individual and varies based on several factors. However, to learn the basics of Python, including the syntax, variables, datatypes, etc., would take anywhere between five to ten weeks at the latest.

7. What should I learn after Python basics?

After learning the basics of Python, you can learn more about Web Development Frameworks, you can learn Machine Learning, and you can also work on various Python Projects that are helpful in building your CV. Working on Python Projects and Internships can push you closer to landing your dream job.

8. How do I start python coding?

To start coding in Python, you first have to install Python with the help of the Anaconda distribution package available on Anaconda.org. Download Anaconda and then download the latest Python version. The process after this is straightforward. The next step is to power up an IDE and start coding in Python.

9. Is Python easier than Java?

There are certain differences between the two programming languages. Python is an interpreted language and is dynamically typed. Whereas Java is a complied language and is statically types. Although the runtime is faster in Java and it is easier to debug, Python is easier to learn and read.

Learn python from expert faculty under Great Learning’s PG program in Artificial Intelligence and Machine Learning. You do not need any prior technical background to pursue this course and understand python functioning.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

2 thoughts on “Python Tutorial For Beginners – A Complete Guide | Learn Python Easily”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top