Special Offer - Enroll Now and Get 2 Course at ₹25000/- Only Explore Now!

All Courses
Python Tutorials

Python Tutorials

November 21st, 2018

Python Basics for Beginners

A Definite Tutorial Guide for Aspirants

Python is a high-level language that was released in the year 1991 and capable of writing any application from desktop to web application framework. For those who are already familiar with C, C++, and Java, Python is a pretty easy option to start or advanced their career. Before we actually start with Python basics for Beginners, let us first check the top reason to learn Python.

Python Basics for Beginners – A quick look at Python Fundamentals

1. Introduction to Python

Python is a high level Programming Language with the features of object oriented programming. As it offers dynamic binding and many more keywords thus has become extremely popular in the field of Application Development.

introduction to python
Python is the marvellous creature of Guido Van Rossum, a Dutch computer scientist and mathematician who decided to create a programming language which is unique on its own.

It is used for web development, software development, mathematical analysis, Data analysis and many more. Python is derived from many languages including C, C++, Java, Unix shell and many more.
Python program is typically 1/5 to 1/3 the size of equivalent Java or C++ code.

Python is used by many companies as well as in research centers. Google, YouTube, Dropbox, Yahoo, Zope Corporation,Walt Disney, Pixar, NASA, Red Hat, Nokia, IBM, Netflix, Yelp, Intel, Cisco, HP, Qualcomm, JPMorgan Chase, just to name a few.

2. What is Python?

Python is the high level object oriented programming language.
It follows some features,

  • Clear syntax and expressive
  • Supports both Object Oriented programming and Functional Programming
  • Highly Portable, runs almost anywhere like,highend server, workstations etc
  • Uses machine independent byte codes
  • Designed to be extensible allowing access to many external libraries of C and C++

Below are the common Python implementations ,

  • Cpython ( c ) (most common)
  • PyPy (python)
  • JyThon (Java)
  • IronPython(.Net)

python features


Important Features

python tutorials 3

  • Python is completely object-oriented and it is not typed statically.
  • There is no need for a variable declaration before you use them.
  • An object will define which type of operations are supported by any particular object or what operations can you perform on the data values.
  • With data type, you can also define the object attributes and either you can edit them or not.
  • There are eight popular data types in Python that include – Boolean, Strings, Numbers, Lists, Tuples, Bytes, Sets, and Dictionaries.
  • Programs are written as files ,and with the .py extension
  • Each module has their own namespaces
  • Name space within a module is always global
  • .py files are executed directly
  • .py files referenced by import statement are called as modules
  • Here Variables are not needed for introduction or type casting
  • Indentation plays a crucial role in here

3. Career Opportunities in Python

Apart from Ruby, after Swift, Python developers are more in demand and thus earns large packages. Python is also in use for cyber security.
The super intelligent coding structure provides different ways for supporting modern high-end technologies.

Web Development
Python framework Django, web2py, Flask are used for web development. Django is the popular one, but Flask is also in second highest in order of popularity as it is customizable.
web development
These are some sites who uses DJango.

Data Analysis
Python is preferred in research areas for its flexibility and speed. Data analysis is done by Python. It supported different frameworks and libraries to provide Artificial Intelligence and Machine Learning.

Image Processing
Image Processing and using it in graphical and analytical platforms have become easy with Python.

Desktop Application
Python is also used in software development to create different desktop applications.
desktop applications
Raspberry Pi
With it, python can also use in robotics, machines, cameras and even remote controlled toys.


Games like Battle Field 2, World of Tanks, Sims 4 are created by Python.

Games Applications

4. Advantages & Disadvantages of Python


Easy to Learn
Whether a programmer knows how to code or not it is understandable by both as it follows a simple coding syntax . Thus nowadays programmers loves Python over C++ or Java.

Lesser Coding
Python needs lesser coding and the source code can be used in other languages like C++. Thus provides a strong outcome for embedding different languages. In here a simple print statement does the display of data. It also does not need braces to create blocks, the indentation is responsible for it.

Python is portable to different Operating Systems. Anywhere a python source code can be taken for execution purpose. But you need to careful t ng

Python needs lesser coding and the source code can be used in other languages like C++. Thus provides a strong outcome for embedding different languages. In here a simple print statement does the display of data. It also does not need braces to create blocks, the indentation is responsible for it.


Python is portable to different Operating Systems. Anywhere a python source code can be taken for execution purpose. But you need to careful to  o not put any system dependent features.

Support for IoT
The IoT or Internet of Things has created huge opportunities in our life and technology and Python is the first choice for programmers when it comes to this topic. The Raspberry Pi is responsible for creating codes and communications between Bots and softwares.

Extensive Libraries
It provides large Libraries that include topics like String Operations, Internetworking, Web Services, OS Interfaces, Protocols, Regular Expressions, Documentations, Unit Testing, Databases Connectivity, Threading, Web browsers, CGI, GUI Programming and many more applications. Thus makes limited coding written in Python.

Free and Open Source
Building prototypes in Python is very easy. The Python code takes very less time to complete the circle from  its first Prototype to final Product. The Open Source nature gives it a huge advantage over design, scalability, portability and speed .

Enterprise Application
The Enterprise Application integration or EAI provides Python COM or COBRA components to develop web services. It has powerful coding capabilities by invoking C, C++ or Java via Jython. Also supports XML or other markup languages for web development.

Scientific and Numeric Applications
Python through its different libraries supports Scientific and Research applications in numerical, analysis, analytical fields.

Python Advantages and Disadvantages


As it is an Interpreted language thus sometimes speed is an issue. However some portions run faster than normal C or C++ codes. Still it is slower than C, C++ or newer like Go.

Not supported for Mobile or Browsers
As it is not yet supported for mobile development thus fewer apps had been built using Python. Even it has problems with browser as it is difficult to secure.

Design Limitations
As it is dynamically typed thus requires more testing with errors which only appears at runtime. Thus the design has its own issues.

Less developed Database Layers
Like C++ or Java which uses JDBC and ODBC technologies , the Python database access layer is less developed and primitive. However it cannot be in use where smooth interaction is needed for a complex huge database.

5. Python Implementation

Python is a language which can be implemented in different languages like CPython, PyPy, Jython, IronPython  etc. But before proceeding  further, you need to understand some important thngs.

Machine Language Coding
It is a set of instructions which directly executed by the CPU itself. Almost all of the high levellanguages converts the user written codes to machine language by using Compilers. The processors have their own machine language coding instruction sets.

Byte Code in OOP
It is converted to binary representations using virtual machines. The virtual machine is different for different languages and thus portable to different platforms.



The CPython is the defult implementation and is written in C. Almost supports all external libraries from C. It compiles Python codes into byte code by the CPython virtual machine. It is the default reference implementation for Python, thus supports maximum level  of compatibility with packages and different external libraries. All versions of Python programming language is based upon CPython.

Jython is the use of java classes in Python. Which compiles into byte code and thus can be run by JVM. It is the implementation of Python in Java platform. Provides java libraries in Python. Supports Python version 2.7 and above.

A Python implementation which is written using  .net coding language framework. Uses the .net virtual machine for compiling the codes. Supports .net libraries and Python libraries both. It performs better in programs like Thread. Supports Python version 2.7 and above.

It is the implementation of the Python programming language written in RPython. PyPY uses JIT which makes it more fast and efficient. PyPy supports version 2.7 and a new released beta version is there for Python 3.

Other implementations are PythonNet, Stackless Python, Brython, Wpython, MicroPython etc.

Implementations of Python


6. Python IDLE, Python Editors & Python IDEs

Python IDLE

IDLE stands for integrated development & learning environment.
The python IDLE is installed by default whenever you install Python. It supports Python Shell window, auto completion of codes, indentation, syntax highlighting and basic debugger.

Python General Editors

The general editors which are used for Python coding are as follows.
General Editors
Sublime Text
It is a popular code editor which is fast, has a huge community and highly customizable.
It has by default Python interpreter with it, though for specific purposes like scientific calculations, web framework etc., you have to install the respective packages.

The Vim or Vi editor is commonly found in MAC OS or LINUX OS. If you already know Vi editor then you can use it for Python coding otherwise you have to learn commands to use this editor. You have to install special packages for special purposes. 

Visual Studio Code
The VS code is very popular for Python development as it is a free and open source IDE founded by Microsoft. It is very lightweight and supported with many powerful features of Python.

GNU Emacs
Created as the “customizable, Extensible, real-time display and self documentation”, GNU Emacs has been there as long as UNIX OS. It is always free for every platform, uses an environment created by LISP.

Python Specific Editors

IDE and Editors
This editor supports Jupiter Notebook. Jupiter is an open source coding platform which supports a live platform for creating and sharing codes.

Created by GitHub, it is an open source like sublime Text. Highly customizable and uses packages for special purposes.

It comes with Python 3, mainly intended for beginners. Although it has some very good features which makes it popular in coders like highlighting, debugger, indentation, code completion etc.

It is a open source IDE for python development that is mainly for Data Scientists. It comes with ANACONDA package, so if you have ANACONDA already installed then you have Spyder in it. It supports data science libraries like NumPy, Matplotlib, SciP, etc.


The best full featured IDE for python is PyCharm. Available both in paid (Professional) and unpaid (Community) versions. Suitable for all type of platforms. It has very large supported Python libraries, though initially it takes time to load but is perfect for any type of Python coding.

7. Python Syntax, Indentation and Comments

Python Syntax

>>>print(“Hello “)

In Python 3 print is a function, and always invoked with parentheses.

Python Statements

Instuctions, which a python interpreter executes are known as statements.

Multiline Statement

Python supports multiline statements.




Here ‘\’ is known as a line continuation character.
Line continuation is also implied by parentheses(), brackets[] and braces{}.


Python uses indentation for creating blocks, in place of curly braces.

>>>x = 1

>>>if x == 1:

print(“x is 1”)

output: x is 1


In python the hash tag is used for creating a comment.

>>print(“hello”)    #display hello

Multiline Comments

Multiple line comments can be achieved by using either ‘ ‘ ‘ or

>>>print(“hello”)“””the codes are ok

Print is for display”””


The docstring in python means the first line in a module or function or class which indicates the definition of that block.

Always denoted using “”” .

8. Python Variables & Data Types

Python is completely object oriented programming language. You do not need to introduce variables before using them with their type. Based on the variable data type, the interpreter itself allocates memory and what data to be stored in that memory.

All data types in Python are given in the form of objects and each object has its particular data type as defined by the users.

Here we will learn about assigning values to variables and data types.

variables and data types

Assigning values


Rules for Assigning variable names

Should be start with alphabet (A-Z/a-z) or Underscore ( ­_ )






Syntax Error

There are some reserved words that you cannot use for variable names.
and, assert, exec, finally, def, del, elif, break, class, continue, from, global, if, import, in, is, else, except,  or, pass, print, raise, for, lambda, not, return, try, nonlocal, yield, while

>>>first = “string“

>>> second = 24

>>> third = 2.4






Multiple assignments
This method makes swapping of values is very easy.






Common Data types are

  • string
  • boolean
  • int
  • dict
  • float
  • list
  • long
  • set

9. Python Operators

Types of Operator
  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Assignment Operators
  4. Logical Operators
  5. Bitwise Operators
  6. Membership Operators
  7. Identity Operators

Python Arithmetic Operators

Assume variable A= 10 and variable B =20,

Operator Description Example
+ Addition Adds values A+B
– Subtraction Subtracts A-B
* Multiplication Multiplies values A*B
/ Division Divides A/B
% Modulus Remainder A%B
** Exponent Performs exponential (power) calculation A**B
// Floor Division A//B
Basic Operators
Operators with String
operators with list

Python Comparison Operators

Compares values between two operands

Operator Description Example
== For equal A==B
!= Not equal to A!=B
<> Same as not equal to A<>B
> Greater than A>B
< Less than A<B
>= Greater than equal to A>=B
<= Less than equal to A<=B

Python Assignment Operators

Operator Description Example
= Equal to A=B
+= Add and equal A=A+B or A+=B
-= Subtracts and equal A=A-B or A-=B
*= Muiltiply and equal A=A*B or A*=B
/= Division and equal A=A/B or A/=B
%= Modiulus and equal A=A%B or A%=B
**= Power and equal A**=B or A=A**B
//=  Floor and equal A=A//B or A//=B

Python Bitwise Operators

Uses bits and performs bit per bit operations.

Operator Description Example
& Binary AND (A& B)
| Binary OR (A | B)
^ Binary XOR (A ^ B)
~ Binary Ones Complement (~A )
<< Binary Left Shift A<< 2
>> Binary Right Shift A >> 2

Python Logical Operators

Operator Description Example
and Logical and A and B
or Logical or A or B
 not Logical not A not B
Logical operators

Python Membership Operators

Uses for strings, lists, or tuples.

Operator Description Example
in Checks whether it is there or not A in B
not in Checks whether it is not there A not in B

Python Identity Operators

In Operators
Not Operators

Operator Description Example
is True if finds same data A is B
is not True if finds other data A is not B

10. Python Numbers

Numbers here are directly assigned to the variable. No need for data type mention.


>>>myint = 7

Floating point numbers

>>> myfloat=7.2

Multiple Assignments

Here you can assign multiple variables concurrently using multiple values.

Here Python interpreter will take a=2 and b=3 directly.
The multiple assignments have made swap of values of variables easier and less complex. As you don’t need to use a third variable or a mathematical calculation to do the swap of values.




User input

The ‘input() ‘ function takes input from the user. But by default this function takes values as string. To take an input in integer format ‘int()’ is needed to typecast the input value into integer type.

It will ask for an input and will take the input in integer format.
Just write,



Type gives the exact data type of a particular variable.

11. Python Strings

Before starting String here are some basic argument specifiers you should know:

  • %s – String (or any object with a string representation, like numbers)representation
  • ​%d – Integers​ representation
  • %f – Floating point representation
  • %.<number of digits>f – Floating point numbers with a fixed amount of digits after the point.
  • ​%x/%X – Integers in hex representation

The string is written within double quotes and single quotes both.

Strings can be indexed with the first character starting with index 0.
>>>a[0]   # character in index number 0
Indexes if counted from the right , are started with negative numbers.
>>> a[-1]                            # last character
>>> a[-2]                            # second-last character
>>> a[-6]
You have to note that -0 is the same as 0.
Here are some String formats,

>>> “door is %s” % (‘closed’)o.p: ‘door is closed’

>>> “door is {0}”.format(“closed”)

Op: ‘door is closed’

>>> “The door is not {0} but remains {1}”.format(“closed”, “open”)

o.p: ‘The door is not closed but remains open‘

>>> “The door is {thing}”.format(thing=’closed’)

o.p: ‘The door is closed‘

>>> “The door is  {thing}, and the window is   {thing} also”.format(thing=’closed’)

o.p:’The door is closed , and the window is closed also’

>>>data = “Hello World!”


o.p:  4


o.p:  3


o.p:  lo  Wo

Built in functions for String

String has its own built in functions, by using which different operations can be performed. The following are,

Method Descriptions
capitalize() Makes the first letter in capital
center() Wrap’s string with specified character
casefold() Converts to casefold strings
count() Counts no. of letters in a string
endswith() Checks if ends with the specified data
startswith Checks if starts with the specified data
expandtabs() Replaces tab characters with spaces
encode() Returns encoded string
find() Returns index of first encounter of substring
format() Formats string as per view
index() Returns index number
isalnum() Returns alphanumeric character
isdecimal() Checks decimal characters
isdigit() Checks no of digits in a string
isidentifier() Checks for valid identifiers
islower() Converts to lowercase
isupper() Converts to uppercase
isnumeric() Checks numeric characters
isprintable() Checks printable characters
isspace() Checks white space characters
istitle() Checks for title
isjoin() Returns string in concatenated
lower() Returns lowercased string
upper() Returns upper case string
swapcase() Swaps upper to lower or vice versa
strip() Removes both leading and trailing characters
replace() Replaces a character with a given value
split() Splits a sentence with separators
len() For calculating the length

>>> a = “welcome back!“

o.p:welcome back!’

>>> a.upper()


>>> a.lower()

o.p:’welcome back!’

>>> a.split(” “)

o.p:[‘welcome’, ‘back!’]

>>> a.strip()

o.p.:’welcome back!’

>>> a.replace(‘!’,’?’)

o.p.: welcome back?’

>>> a.startswith(‘wel’)


>>> len(a)

o.p: 12

>>> b = ” hello”

>>> a + b

o.p: ‘welcome back hello ‘


o.p: Hello world


o.p: Hello world


o.p: 3


o.p: True



o.p:welcome   back


O.p: 2

12. Python Lists

Lists are same like arrays. They can contain different type of variables, but should be similar type and there is no limitation. Lists can also be used in different ways. In Python square brackets are used to create lists. Now let us see , how to build a list.

Create List


>>>List 2=[1,2,3,4,5,6,7]

Access an item 

We can print any element from the list

>>>print(List1[0])​      ​#prints   physics
Access the List 

we can call the total list

>>>print(List2​)         #prints       [1 ,2,3,4,5,6,7]
Change Item 
>>>List1[3]=25 >>>print(List1)​                ​#prints     [physics, chemistry, 25, 2018] D
delete an Item 
>>>del(List1[2]) >>>print(List1)​                 ​#prints      [physics,25,2018]
Add an item
>>>mylist = [] >>>mylist.append(10) >>>mylist.append(20) >>>mylist.append(30) >>>print(mylist[0]) ​# prints 10 >>>print(mylist[1]) ​# prints 20 >>>print(mylist[2]) # prints 30
Insert after an existing Item 


>>>List3.insert(1, ‘orange’)

>>>print(List3)  ​#prints    [2 ,orange, 5, 6]

remove an item 

The ​remove()​ method removes the specified item


>>>print(List3​)  ​#prints               [2,5,6]

The ​pop()​ method removes the specified index or the last item if index is not specified

>>>List5 = [“apple”, “banana”, “cherry”]


>>>print(List5) #prints     [apple, banana]

The ​del​ keyword removes the specified index.


>>>print(List5) #prints        [apple]

The ​del​ keyword can also delete the list.


>>>print(List5)   # it causes an error as the list does not exist

13. Python Tuples

A sequential data type, can consists of a number of values separated by commas, for instance:

>>> t1= 12345, 54321, ‘welcome’

>>> t1[0]


>>> t1=(12345, 54321, ‘hello!’)

>>> u1 = t1, (1, 2, 3, 4, 5)

# Tuples may be nested
>>> u1 ((1234, 51, ‘how!’), (1, 2, 3, 4, 5))
# Tuples are immutable

>>> t1[0]>>> t1[0] = 88888

>>> v1= ([1, 2, 3], [3, 2, 1])

# but they can contain mutable objects
>>> v1 ([1, 2, 3], [3, 2, 1])
#to create tuple

>>>tup1 = (‘Apple’, ‘Ball’, 1997, 2000)

>>>tup2 = (1, 2, 3, 4, 5 )

>>>tup1                  #run the tuple

>>>tup1 = ()           #empty tuple

>>>tup1 = (50)       #tuple containing a single value

#Accessing Values

>>>print ( tup1[0])

>>>print (tup2[1:5])

#Updating Tuples

>>>tup1 = (12, 34.56);

>>>tup2 = (‘abc’, ‘xyz’);

#Delete Tuple
>>>del tup1;
#Tuples respond to the + operator for concatenation and * operator for repetition same like strings but the result is a new tuple.

>>>(1, 2, 3) + (4, 5, 6)>>>(‘Hi!’,) * 4

Built in Functions

>>>len((1, 2, 3))   #length


>>>tuple1, tuple2 = (123, ‘xyz’, ‘zara’, ‘abc’), (456, 700, 200)>>>print( “Maximum value : “, max(tuple1))

>>>print( “Max value element : “, max(tuple2))


>>>print (“min value element : “, min(tuple1) )

>>>print( “min value element : “, min(tuple2))


>>>print cmp(tuple1, tuple2)

>>>print cmp(tuple2, tuple1)

# Following action is not valid for tuples
>>> tuple1[0] = 100;
# So let’s create a new tuple as follows

>>>tuple3 = tuple1 + tuple2;

>>>print( tuple3)

14. Python Dictionaries

Dictionary is a data type which works on a key-value pair. There are values for every keys and no two keys can be same.

>>> dictionary={‘name’:’charlie’,’id’:100,’dept’:’it’}

>>> dictionary

{‘dept’: ‘it’, ‘name’: ‘charlie’, ‘id’: 100}

>>> dictionary.keys()

[‘dept’, ‘name’, ‘id’]

>>> dictionary.values()

[‘it’, ‘charlie’, 100]

#using dictionaries in different ways

>>>dict = {‘name’:’Jack’, ‘age’:40}

>>>print(dict[‘name])   #corresponding value as output

>>>print(dict.get(‘age’)) #retrieves values of that key

>>>print(dict.values())    #all values

>>>print(dict.keys())      # all keys

#change or add elements

# update value

>>>dict[‘age’] = 27
# add item
>>>dict[‘address’] = ‘Downtown’
delete or remove elements

# remove a particular item

# remove an arbitrary item
# delete a particular item
>>>del dict [5]
# remove all items
# delete the dictionary itself
>>>del dict

15. Python Sets

An unordered datatype with no duplicate values.
They are mutable objects.
Based on data structure called Hash Table.
Frozen sets are immutable sets and used with methods or operators.

>>>set1 = set([“a”, “b”,”c”])
# Adding an element to normal set is fine

>>>Set1.add(“d”)>>>print(“Normal Set”)


# A frozen set

>>>frozen1 = frozenset([“e”, “f”, “g”])>>>print(“Frozen Set”)





#empty or clear
key in s
Containment checking
key not in s non-containment checking
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1is subset of s2 ,s1 < s2
s1 > s2 s1 is proper superset of s2
s1 | s2 the union of s1 and s2
s1 & s2 the intersection of s1 and s2
s1 – s2 the set of elements in s1 but not s2
s1 ˆ s2 the set of elements in either s1 or s2

16. Python Decision Making Statements

With Flow control, you could check or define the flow for any program execution. It is also suitable to represent the real-world problems as well. In this way, you could have full control over the execution of programs in Flow Controls.
python tutorials 5
Python decision making statement involves ,

  • if else
  • if elif else
The if Statement

The if statement is used to check a condition whether it is true, and run a block of statements ( if-block), otherwise process another block of statements (else-block). The if statement in Python lets you conditionally execute a block of statements.

>>>if a==20:print(‘Yes’)



If elif else statement
>>>number = 25

>>>guess = int(input(‘Enter an integer : ‘))

>>>if guess == number:

# New block starts here

print(‘Congratulations, you guessed it.’)

print(‘(but you do not win any prizes!)’)

# New block ends here

elif guess < number:

# Another block

print(‘No, it is a little higher than that’)

# You can do whatever you want in a block

print(‘No, it is a little lower than that’)

17. Python Loops

There are 2 types of loops in Python, for loop and while loop.

“for” loop

The ‘for loop’ supports the repeated execution of a block of statements that can be further controlled by the iterable expressions.

>>>primenumber = [2, 3, 5, 7]

>>for p in primenumber:


There are two built in functions that are used in for loop to iterate values, “range” and “xrange” .
The difference between these two functions is that the range function returns value with a specified range, Python 3 uses the range function, which is same like xrange. Note that the range function starts with zero.

# Prints out the numbers 0,1,2,3,4>>>for x in range(5):


# Prints out 3,4,5

>>>for x in range(3, 6):


# Prints out 3,5,7

>>>for x in range(3, 8, 2):


“while” loops

The while statement in Python supports the repeated execution of a block of statements that are further controlled by the conditional expressions. While loops repeat as long as the condition satisfied.

# Prints out 0,1,2,3,4>>>count = 0

>>>while count < 5:


count += 1

else with loop

While loop






print(‘count reached%d’%(count))

for loop

>>>for i in range(1,10):





print(“the loop has terminated”)

18. Python Control Statements- Break, Continue & Pass

Several times while writing the loop statement we need to finish the loop after some condition or need to skip execution of some code. This is often used to work on scenarios while writing the business logic.

Python contains break, continue, pass statements to control loop and the condition can be handled with the same. We will discuss here the break, continue and pass statements.

Sr.No. Control Statement & Description
break statement Terminates the loop statement
continue statement Causes the loop to continue after skipping the conditioned area.
pass statement The pass statement in Python is used to pass the conditioned statement.


The continue Statement – This also works as same like C/Java language. Continue statement ignore all the statement which come inside the scope of current iteration and return the control to beginning of the while/for loop. So it will not allow execution of the statements on the current iteration and move the control back to the top. This statement can be used with for/while loop.
The continue statement is used within a nested loop. Even if one loop ends, the execution will continue until the next iteration.

for letter in ‘Python Programming’:

if letter == ‘h’:


print (‘Current Letter :’, letter)

Continue Example-1

Continue Example-2


The break statement – This work as the same defined in C/Java language. This statement terminates the loop or come out from the loop and resume at the next statement execution.The break statement used to exit from a loop for some external and exceptional conditions. Somehow it works to save more iteration as well.The break statement works with the while/for loop.
The break statement can be added within a loop body only. When a loop is nested with other loop statements, the break statement will terminate the innermost nested loop.

for letter in ‘Python Programming’:

if letter == ‘h’:


print (‘Current Letter :’, letter)

Break Example-1

Break Example-2


The pass Statement – This statement in Python is performed nothing or nothing happens when it executed. It’s required when you don’t want any action or execution, it just works as syntactically This statement used to call as null operation and required for acknowledgment like where you reach till now. example like you are iterating a list and just want to acknowledge once reach to the specific object.

It does not perform any action but can be used as the placeholder when you have nothing specifically to do.

for letter in ‘Python Programming’:if letter == ‘h’:


print (‘Current Letter :’, letter)

Pass Example-1

Pass Example-2

19. Python Switch Case

Python does not have a keyword like ‘switch case’.
But we can do it using if else or using functions. Here is an example using functions,

# This function adds two numbers

def add(x, y):
return x + y

# This function subtracts two numbers

def subtract(x, y):
return x – y

# This function multiplies two numbers

def multiply(x, y):
return x * y

# This function divides two numbers

def divide(x, y):
return x / y

print(“Select operation.”)

# Take input from the user

choice = input(“Enter choice(1/2/3/4):”)

num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))

if choice == ‘1’:
print(num1,”+”,num2,”=”, add(num1,num2))

elif choice == ‘2’:
print(num1,”-“,num2,”=”, subtract(num1,num2))

elif choice == ‘3’:
print(num1,”*”,num2,”=”, multiply(num1,num2))

elif choice == ‘4’:
print(num1,”/”,num2,”=”, divide(num1,num2))
print(“Invalid input”)

20. Python Functions

Functions in Python are a group of related statements that are used to perform a specific task. It always makes your program more organized and increase the reusability, extensibility, and provides the abstraction. Functions are a way to create blocks to compose codes in more readable form.
Functions in python are declared using the keyword “def”, followed by the function name given by the user.

>>>def  my_function():print(“Hello From My Function!”)


Here are different ways to call a function,

>>>def   my_function_with_args(uname,msg=” “):

print(“Hello, %s , From My Function!, I wish you %s”%(uname, msg))

>>>my_function_with_args(“Python”,”good programming”)

>>>def sum_two_numbers(a, b):

return a + b


Optimal parameters

>>>def add(x,y=5):return x+y


Keyword parameters

Another approach is keyword parameter.

>>>def    sum(a,b,c=2,d=6):return a+b-c+d


Arbitrary Arguments

An arbitrary parameter number declared in Python with so-called tuple references. An asterisk “*” is used with  the last parameter to denote it as a tuple reference.

>>>def arbitrary(x,y,*m):print(x,y)


>>>arbitrary(2,3)   #x=2 and y=3

>>>arbitrary(2,3,”Python”,6,5)   #x=2,y=3 and m=”Python”,3,4

Pass by reference vs value

# Function definition is here

>>>def change( mylist ):mylist.append([1,2,3,4]);

print (“Values inside the function: “, mylist)


# Now you can call change function

>>>mylist = [10,20,30];

>>>change( mylist );

>>>print( “Values outside the function: “, mylist)

# Function definition is here

>>>def change( mylist ):

“This changes a passed list into this function”

mylist = [1,2,3,4];

print( “Values inside the function: “, mylist)


# Now you can call change function

>>>mylist = [10,20,30];

>>>change( mylist );

>>>print( “Values outside the function: “, mylist)

Scope of Variables

  • Global variables
  • Local variables

The variables which are defined inside function body are called with local scope and defined outside are called global.

>>>s=10      #global variable

>>>def fun():

f=22           #local variable


21. Python Built in Functions

Python abs ()

absolute value of a number.

>>> abs(-7)

>>> abs(7)

Python all ()

Returns true if all values are peresent in the list

>>> all({‘*’,”,”})
Python any ()

it takes one argument and returns True, if even one value in the list has a value true.

>>> any((1,0,0))
Python ascii ()

returns a printable representation of a python object

>>> ascii(‘?’)

>>> ascii([‘s’,’?’])

Python bin ()

Python bin() converts an integer to a binary string.

>>> bin(7)
Python bool ()

Python bool() converts a value to its equivalent boolean.

>>> bool(0.5)

>>> bool(True)

>>> bool(”)

Python chr ()

returns the character in python for an ASCII value

>>> chr(65)

>>> chr(9)

Python complex ()

Python complex() function creates a complex number

>>> complex(3)

>>> complex(3.5)

Python dict ()

Python dict(), as we have seen it, creates a python dictionary.

>>> dict()

>>> dict([(1,2),(3,4)])

Python dir ()

Python dir() returns an object’s attributes.

Python enumerate ()

it adds a sequence to the iterable.

>>> for i in enumerate([‘a’,’b’,’c’]):


Python eval ()

takes a string as an argument, which is executed as an expression

>>> x=7

>>> eval(‘x+7’)

Python filter ()

filters out the items for which the condition is True.

>>> list(filter(lambda x:x%2==0,[1,2,0,False]))
Python hash ()

returns the hash value of an object.

>>> hash(orange)
Python max ()

highest value of all.

>>> max(2,3,4)
Python min ()

lowest value in a sequence.

>>> min(3,5,1)

Python oct ()

converts an integer to its octal representation.

>>> oct(7)

>>> oct(True)

Python pow(x,y)

Takes y as power of x

>>> pow(3,4)
Python round ()

rounds off a float number to the given number of digits.

>>> round(3.777,2)

22. Python Lambda

It is an anonymous function, that is without a name.

Will be dreated like this,

Lambda arguments : expression

Can have multiple arguments but only one expression to execute them

Used whenever function objects are required.

>>> def cube(y):

return y*y*y;

>>>a = lambda x: x*x*x


Another use is to pass a function as an argument to dictionary,

>>> p = [(1, ‘o’), (2, ‘t’), (3, ‘th’), (4, ‘f’)]

>>> p.sort(key=lambda pair: pair[p])

>>> p

23. Objects in Python

Python is an object-oriented programming language, and everything is defined in the form of objects in Python. To create an object in Python, you should write “ob=mynewclass”. In this way, you can always create an object from an existing class.

With this discussion, we come to an end of this blog, “Python basics for beginners”. I hope you enjoyed reading this blog and find it informative. By far, you must have a basic understanding of Python programming basics for beginners and why you should learn Python to future-proof your career.

24. File handling in Python

File handling operations in Python are used to read or write data to a file. The basic operations of a File include – Open File, Read/Write File, Close a File. To open a file in Python, use the open () method, it will return the file object and used to write or modify data accordingly.

To read the file, we must open the file in the readable format. To append the data to a file, write w and start making changes to the file. Be careful with w operation otherwise, it may overwrite the existing data too.

25. Python Inheritance

Inheritance is a way in which we create a new class by taking the details of exisiting class without modifying it. The new class formed is a class derived (or child class) Same as that, the existing class is a base class (or  say parent class) Syntax: class Baseclass: Body of base class class DerivedClass(Baseclass): Body of derived class

In [24]:

class Father:
title = ‘Gurusamy’
wealth = ‘1c’
diabetic = ‘no’
color =’brown’
height = ‘5.9 feet’
def Father_details(self):
print(“Father detail are:  \nTitle:  ” +self.title +’\nwealth:  ‘ +self.wealth+’\ndiabetic:  ‘+self.diabetic+’\ncolor:   ‘+self.color+’\nheight:  ‘+self.height)

In [25]:

father = Father()

In [18]:

father.Father_details()Father detail are:
Title:  Gurusamy
wealth:  1c
diabetic:  no
color:   brown
height:  5.9 feet

In [26]:

class Son(Father):
def __init__(self,name1,age1, salary1, job1,married1):
self.name1 = name
self.salary1 = salary
self.job1 = job
self.married1 = married
def Son_details(self):
print(“Son detail are:  \nName: “+self.name+’\nAge:  ‘ +self.age+’\nSalary:  ‘+self.salary+’\nJob:  ‘+self.job+’\nMarried:  ‘+self.married+’\nTitle: ‘ +self.title +’\nwealth:  ‘ +self.wealth+’\ndiabetic:  ‘+self.diabetic+’\ncolor:   ‘+self.color+’\nheight:  ‘+self.height)

In [27]:

son = Son(‘Ramkumar’,’28’,’50k’,’salaried’,’yes’)

In [21]:

Son detail are:
Name: Ramkumar
Age:  28
Salary:  50k
Job:  salaried
Married:  yes
Title: Gurusamy
wealth:  1c
diabetic:  no
color:   brown
height:  5.9 feet

26. Python Collections Module

There are 6 Module in Python Collections:

  • Counter
  • defaultdict
  • OrderedDict
  • deque
  • ChainMap
  • namedtuple()

The Counter
Counter is a subclass of word reference object. The Counter() work in collections module takes an iterable or a mapping as the contention and returns a Dictionary. In this word reference, a key is a component in the iterable or the mapping and worth is the occasions that component exists in the iterable or the mapping.

Example :
Counter Output
The defaultdict

The defaultdict works precisely like a python lexicon, aside from it doesn’t toss KeyError when you attempt to get to a non-existent key. Rather it introduces the key with the component of the information type that you go as a contention at the production of defaultdict. The information type is called default_factory.

DefaultDict Output-2
The OrderedDict

OrderedDict is a word reference where keys keep up the request in which they are embedded, which means on the off chance that you change the estimation of a key later it won’t change the situation of the key.

OrderedDict Output-1
OrderedDict Output-2
The deque

The deque is a rundown advanced for embeddings and evacuating things. Import the deque You need to import deque class from the collections module before utilizing it.

Example Code:
Deque Output
The ChainMap

ChainMap is utilized to consolidate a few word references or mappings. It restores a rundown of word references.

Example Code
ChainMap Output
The namedtuple()

The namedtuple() restores a tuple with names for each position in the tuple. Probably the most serious issue with conventional tuples is that you need to recollect the list of each field of a tuple object. This is clearly troublesome.

The namedtuple was acquainted with tackle this issue.

Example Code:

namedtuple() output

Why you should Learn Python?

Here are the top ten reasons why someone should learn Python and why it is taken as one of the most optimum career choices in 2019.

  1. High Salaries and Career Opportunities
  2. AI or Artificial Intelligence
  3. Data Science
  4. Computer Graphics
  5. Scripting and automation
  6. Easy and highly readable syntax
  7. Dynamic Typing
  8. Web application Services
  9. Testing Frameworks
  10. Extensibility and Portability

Python Tutorial Guide – Start with the Python Installation

1. Browse the link – https://www.python.org/downloads/ and download the latest version as highlighted in yellow below.

python tutorials 1

2. In the next step, download the PyCharm IDE and install it on your system. PyCharm is an Integrated Development Environment (IDE) that is frequently used for computer programming, especially for the Python. Here, is one code analyzer, graphics debugger, integrated tester to check your code and available in different versions for your convenience. It supports web development with Django as well.
python tutorials 2
3. Now launch the IDE and you are ready to code in Python.