1. Ethical Hacking
  2. Keep Coding
  3. python

Python For Beginners

Welcome! Are you completely new to programming? If not then we presume you will be looking for information about why and how to get started with Python. Fortunately an experienced programmer in any programming language (whatever it may be) can pick up Python very quickly. It’s also easy for beginners to use and learn, so jump in!

Installing

Installing Python is generally easy, and nowadays many Linux and UNIX distributions include a recent Python. Even some Windows computers (notably those from HP) now come with Python already installed. If you do need to install Python and aren’t confident about the task you can find a few notes on the BeginnersGuide/Download wiki page, but installation is unremarkable on most platforms.

Learning

Before getting started, you may want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books, or look at code samples that you might find helpful.

There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be useful if English is not your first language.

The online documentation is your first port of call for definitive information. There is a fairly brief tutorial that gives you basic information about the language and gets you started. You can follow this by looking at the library reference for a full description of Python’s many libraries and the language reference for a complete (though somewhat dry) explanation of Python’s syntax. If you are looking for common Python recipes and patterns, you can browse the ActiveState Python Cookbook

Looking for Something Specific?

If you want to know whether a particular application, or a library with particular functionality, is available in Python there are a number of possible sources of information. The Python web site provides a Python Package Index (also known as the Cheese Shop, a reference to the Monty Python script of that name). There is also a search page for a number of sources of Python-related information. Failing that, just Google for a phrase including the word ”python” and you may well get the result you need. If all else fails, ask on the python newsgroup and there’s a good chance someone will put you on the right track.

Introduction To Python 

Python in simple words is a High-Level Dynamic Programming Language which is interpreted. Guido Van Rossum, the father of Python had simple goals in mind when he was developing it, easy looking code, readable and open source. Python is ranked as the 3rd most prominent language followed by JavaScript and Java in a survey held in 2018 by Stack Overflow which serves proof to it being the most growing language.

What is Python?

Python is currently my favorite and most preferred language to work on because of its simplicity, powerful libraries, and readability. You may be an old school coder or may be completely new to programming, Python is the best way to get started!

Python provides features listed below :

  • Simplicity: Think less of the syntax of the language and more of the code.
  • Open Source: A powerful language and it is free for everyone to use and alter as needed.
  • Portability: Python code can be shared and it would work the same way it was intended to. Seamless and hassle-free.
  • Being Embeddable & Extensible: Python can have snippets of other languages inside it to perform certain functions.
  • Being Interpreted: The worries of large memory tasks and other heavy CPU tasks are taken care of by Python itself leaving you to worry only about coding.
  • Huge amount of libraries: Data Science? Python has you covered. Web Development? Python still has you covered. Always.
  • Object Orientation: Objects help breaking-down complex real-life problems into such that they can be coded and solved to obtain solutions.

To sum it up, Python has a simple syntax, is readable, and has great community support.

Python Interpreter

An interpreter is a computer program that directly executes, i.e. performs, instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program. So unlike Java, Python uses an interpreter.

The interpreter is a program that we need to run our python code or scripts. It basically provides an interface between the code and the computer hardware to get the results of the code.

No matter in which programming language the code is written, it goes through an interpreter when it comes to python. For example pypy is used to execute the code written in python.

Python Installation

I will be installing Python in Windows 10 OS. You can try installing Python in Linux, Mac etc. If you face any issue mention it in the comments section.

Following are the steps to install Python

  1. Go to www.python.org/downloads/
python installation - python tutorial - edureka

Python Installation For Windows

Python Installation For Windows

  1. Open a browser window and navigate to the Download page for Windows at python.org.
  2. Underneath the heading at the top that says Python Releases for Windows, click on the link for the Latest Python 3 Release – Python 3.x.x. (As of this writing, the latest version is Python 3.7.2.)
  3. Scroll to the bottom and select either Windows x86-64 executable installer for 64-bit or Windows x86 executable installer for 32-bit. 

But do we pick 32-bit or the 64-bit installer?

For Windows, you can choose either the 32-bit or 64-bit installer. Here’s what the difference between the two comes down to:

  • If your system has a 32-bit processor, then you should choose the 32-bit installer.
  • On a 64-bit system, either installer will actually work for most purposes. The 32-bit version will generally use less memory, but the 64-bit version performs better for applications with intensive computation.
  • If you’re unsure which version to pick, go with the 64-bit version.

Open the installer and click on “Run”.

Python Installation For Linux

Use the Graphical linux installation to install python on linux. Follow the steps below:

  • Open the Ubuntu Software Center folder. 
  • Select Developer Tools (or Development) from the All Software drop-down list box.
  • Double-click the Python 3.3.4 entry.
  • Click Install.
  • Close the Ubuntu Software Center folder.

Python is ready for use.

Python Installation For Mac

Before installing Python, you’ll need to install GCC. GCC can be obtained by downloading Xcode, the smaller Command Line Tools or the even smaller OSX-GCC-Installer package.

While OS X comes with a large number of Unix utilities, those familiar with Linux systems will notice one key component missing: a package manager. Homebrew fills this void.

Once you’ve installed Homebrew, insert the Homebrew directory at the top of your PATH environment variable. You can do this by adding the following line at the bottom of your ~/.profile file

1export PATH="/usr/local/opt/python/libexec/bin:$PATH"

Now, we can install Python 3:

1$brew install python

Python IDE

IDE typically provides code editor, compiler/ interpreter and debugger in one GUI (Graphical User Interface). It encapsulates the entire process of code creation, compilation and testing which increases the productivity of developers.

A developer working with an IDE starts with a model, which the IDE translates into suitable code. The IDE then debugs and tests the model-driven code, with a high level of automation. Once the build is successful and properly tested, it can be deployed for further testing through the IDE or other tools outside of the IDE.

Which Python IDE?

Always keep the following points in mind while choosing the best IDE for Python:

  • Level of expertise (beginner, professional) of the programmer
  • The type of industry or sector where Python is being used
  • Ability to buy commercial versions or stick to the free ones
  • Kind of software being developed
  • Need to integrate with other languages

Once these points are decided upon, the programmer can easily select among the IDEs based on the given features.

PyCharm

Developed by Czech company JetBrains, PyCharm is an IDE specific to Python. PyCharm is a cross-platform IDE. Therefore, users may download any of the Windows, Mac or Linux versions depending on their requirements. Honestly, PyCharm is considered to be one of the best IDE for Python and justifiably the most widely used.

In addition to the common features, PyCharm provides additional features like:

  • Specialized project views allowing quick switching between files
  • Facilitates Web Development along with Django, Flask, and web2py
  • PyCharm is equipped with more than 1000 plug-ins, so programmers can write their own plug-ins to extend its features

It provides two versions for download, the Community version which is free and the paid Professional version. Programmers can download the corresponding versions as per their requirements

PyCharm Download

Go to www.jetbrains.com/pycharm/download/#section=windows

pycharm - python tutorial - edureka

Here, the community version is free, but for the professional version, you need to buy the license. I will be working on the PyCharm community version.

PyCharm Community Edition

let us dive right into Pycharm now and I will walk you through the interface.

Let us begin by creating a new project. PyCharm greets you with the following image as soon as you open it:

pycharm - python tutorial - edureka

Here, on the left, you can check out all of the recent projects that I have been working with. But if this is your first time using PyCharm, then the column on the left will not contain anything.

Creating a new project is as easy as clicking on the Create New Project tab and going from there.

pycharm - python tutorial - edureka

This image basically helps us set up our Python Interpreter. However, this might be blank if you do not have Python installed on your system.

pycharm - python tutorial - edureka

Clicking on the little gear icon on the right will bring up the following page:

pycharm - python tutorial - edureka

Here, you can make use of the System Interpreter if you have not installed Python separately. Do check the version of the Python installation that is present so it meets your requirements.

Jupyter Notebook

Jupyter Notebooks are a powerful way to write and iterate on your Python code for data analysis. Jupyter Notebook is built off of IPython and the Kernel runs the computations and communicates with the Jupyter Notebook front-end interface.

Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. It is used for data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more.

Why Learn Python?

Python’s syntax is very easy to understand. The lines of code required for a task is less compared to other languages. Let me give you an example – If I have to print “Welcome To Edureka!”  all I have to type:

1print(“Welcome To Edureka!”)

Let’s look at some cool features of Python:

  1. Simple and easy to learn
  2. Free and Open Source
  3. Portable
  4. Supports different programming paradigm
  5. Extensible

If you are wondering where you can use Python (Python Application), let me tell you that is where Python stands out.

It is advantageous over other programming languages because it is a:

  • Syntax lite language
  • Easy to use & learn
  • Open-source language
  • Dynamic Memory Allocation
  • Extensive Support Libraries
  • Desktop GUI applications
  • Business applications
  • Database Access
  • Robust Web Application Development
  • Supports Math & AI

History of Python

Python was invented in 1991 by Guido van Rossum at CWI, Netherlands. The idea of the Python programming language is extracted from the ABC programming language or it can also be said that ABC is a predecessor of the Python programming language.

There is also a lesser known fact behind choosing the name Python. Guido was a fan of the comedy show, “Monty Python’s Flying Circus” which used to stream on BBC in those times. This is the reason he decided to select the name Python for his newly created programming language.
Python has a very large community across the world and releases its version within a short period of time.

Python version 2.0 was made public on 16th of October 2000, with many brand new features, including a cycle-detecting garbage collector and support for Unicode.

Python version 3.0 was made public on 3rd of December 2008. It was a crucial revision of the programming language that is not completely backward-compatible. Alot of its vital features were backported to Python 2.6. As well as the 2.7 version series. Further version releases of Python 3 series included the utility of 2 to 3, which automates (at least partially) the translation of Python 2 code to Python 3.

Python version 2.7 closing date was initially set in 2015 then was postponed to 2020 out of concern that a large body of existing code could not easily be forward-ported to Python 3. Now there won’t be anymore security patches or other improvements will be released for it. With Python 2 life outdation, only Python 3.6.x and later are supported.

Python 3.9.2 and 3.8.8 were accelerated as all of the versions of Python (including 2.7) had security issues, leading to possible remote code execution and web cache poisoning.

Python 2 Vs Python 3

Sl.noPython 2Python 3
1.It does the approximation i.e it rounds up to the closest whole number in the integer division (7 divided by 2 returns 3)It gives the accurate result (7 divided by 2 returns 3.5). Integer division in Python 3 becomes strikingly accurate, resulting in accurate values
2.It’s syntax is difficult to understandThe syntax when compared is simpler and can be easily understood.
3.The storage needs to define the Unicode string value with “u”.The default storage of strings is Unicode.
4.The value of the global variable will be changed whenever it will be used inside a for-loop.The value of variables doesn’t change.
5.Exceptions are enclosed in notations.Exceptions are enclosed in parenthesis.
6.The ordering comparison rules are comparatively complex.The ordering comparisons rules are quite simple.
7.In this version the xrange() is used for iterations.It provides a Range() function to perform iterations.

Applications of Python

  1. Data Science & Machine Learning
  2. Web Development
  3. Game Development
  4. Software Development
  5. Desktop GUI
  6. Enterprise Applications
  7. 3D CAD Applications
  8. Artificial Intelligence
  9. Desktop Application
  10. Automation
  11. Data Wrangling, Exploration And Visualization

Let us now start coding in Python.

Python Basics

The basic concepts in any programming language are the foundation of any programmer, We will start with the most basic concept in python.

Python Keywords

Keywords are nothing but special names that are already present in python. We can use these keywords for specific functionality while writing a python program.

Following is the list of all the keywords that we have in python:

keywords - python tutorial - edureka

Syntax and Usage

12345importkeywordkeyword.kwlist#this will get you the list of all keywords in python.keyword.iskeyword('try')#this will return true, if the mentioned name is a keyword.

Identifiers are user defined names that we use to represent variables, classes, functions, modules etc.

Syntax and Usage

12name ='edureka'my_identifier =name

Python Popular libraries:

  • Tensorflow: It is specially used for developing and training highly efficient Machine Learning and Deep Learning models, TensorFlow can also help you deploy these models to a host of platforms, such as a CPU, GPU(Graphic Processing unit), or a TPU(Tensor Processing Unit), with ease.
  • NumPy: This library is utilized in adding support for large, multi-dimensional arrays and matrices, accompanied with a large collection of high-level mathematical functions to operate on these arrays.
  • Pandas: It’s a software library specifically made for the Python programming language for the purpose of data analysis and manipulation.
  • Keras: It is a software library which is open-source & allows a Python interface for artificial neural networks.
  • Matplotlib: It is a library used for plotting in Python and its numerical mathematics extension NumPy.

Python Comments

programmer-coherent statements, that describe what a block of code means. They get very useful when you are writing large codes. It’s practically inhuman to remember the names of every variable when you have a hundred-page program or so. Therefore, making use of comments will make it very easy for you, or someone else to read as well as modify the code.

Syntax

1234567#this is a single line comment#this is a multi#line comment"""this is a docstring comment i hope it is clear"""

Python Block Comments

A block comment in python is written with the same indentation as the code, it is used to explain the code. A block comment looks something like the one written in the example below.

12# this is a print statementprint(“hello world”)

Python Variables

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

variables - python tutorial - edureka
Course Curriculum

Data Science with Python Certification Course

Explore Curriculum

In Python you don’t need to declare variables before using it, unlike other languages like Java, C etc.

Assigning values to a variable

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. Consider the below example:

Syntax

12S =10print(S)

This will assign value ‘10’ to the variable ‘S’ and will print it. Try it yourself.

Python Global Variable

In python, GLOBAL Keyword can be used to access/modify the variables out of the current scope.

Syntax

1234567A =10Def function():    globala    A +=10    print(A)print(A)function()

Data Types In Python

Python supports various data types, these data types defines the operations possible on the variables and the storage method. Below is the list of standard data types available in Python:

data types - python tutorial - edureka

Let’s discuss each of these in detail. In this Python tutorial, we’ll start with ‘STRINGS’ data type.

Python Strings

Strings are among the most popular data types in Python. We can create them simply by enclosing characters in quotes. Python treats single and double quotes in exactly the same fashion. Consider the example below:

Syntax

12S="Welcome To edureka!"D ='edureka!'

Python String Methods

Some of the string methods used in python are written below:

  1. strip()
  2. Count()
  3. split()
  4. translate()
  5. index()
  6. format()
  7. find()
  8. center()
  9. join()

Python String Operations

SyntaxOperation
print (len(String_Name))String Length
print (String_Name.index(“Char”))Locate a character in String
print (String_Name.count(“Char”))Count the number of times a character is repeated in a String
print (String_Name[Start:Stop])Slicing
print (String_Name[::-1])Reverse a String
print (String_Name.upper())Convert the letters in a String to upper-case
print (String_Name.lower())Convert the letters in a String to lower-case

Formatting A String In Python

Formatting a string means to allocate the string dynamically wherever you want.

Strings in Python can be formatted with the use of format() method which is very versatile and powerful tool for formatting of Strings. Format method in String contains curly braces {} as placeholders which can hold arguments according to position or keyword to specify the order.

Example

123String1 ="{1} {0} {2}".format('Hello', 'to', 'Batman')print("nPositional order: ")print(String1)

Output:

Positional order:
to Hello Batman

Python Numbers

Just as expected Numeric data types store numeric values. They are immutable data types, this means that you cannot change its value. Python supports three different Numeric data types:

Python Integer

It holds all the integer values i.e. all the positive and negative whole numbers, example – 10.

Python Float

It holds the real numbers and are represented by decimal and sometimes even scientific notations with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250), example – 10.24.

Python Complex 

These are of the form a + bj, where a and b are floats and J represents the square root of -1 (which is an imaginary number), example – 10+6j.

Python Boolean

These are the decisive data types, they only return categorical value, i.e true or false.

Now you can even perform type conversion. For example, you can convert the integer value to a float value and vice-versa. Consider the example below:

Syntax And Usage

1234A =10# Convert it into float typeB =float(A)print(B)

The code above will convert an integer value to a float type. Similarly you can convert a float value to integer type:

1234A =10.76# Convert it into float typeB =int(A)print(B)

Python Lists

You can consider the Lists as Arrays in C, but in List you can store elements of different types, but in Array all the elements should of the same type.

List is the most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Consider the example below:

Syntax

12subjects =['physics', 'chemistry','biology']print(subjects)

Output:['physics, 'chemistry','biology']

Notice that the Subjects List contains both words as well as numbers. Now, let’s perform some operations on our Subjects List.

Let’s look at few operations that you can perform with Lists:

SyntaxResultDescription
Subjects [0]PhysicsThis will give the index 0 value from the Subjects List.
Subjects [0:2]Physics, ChemistryThis will give the index values from 0 till 2, but it won’t include 2 the Subjects List.
Subjects [3] = ‘Biology’ [‘Physics’, ‘Chemistry’, ‘Maths’, ‘Biology’]It will update the List and add ‘Biology’ at index 3 and remove 2.
del Subjects [2][‘Physics’, ‘Chemistry’,  2]This will delete the index value 2 from Subjects List.
len (Subjects)[‘Physics, ‘Chemistry’, ‘Maths’, 2, 1, 2, 3]This will return the length of the list
Subjects * 2[‘Physics’, ‘Chemistry’, ‘Maths’, 2][‘Physics’, ‘Chemistry’, ‘Maths’, 2]This will repeat the Subjects List twice. 
Subjects [::-1][2, ‘Maths’, ‘Chemistry’, ‘Physics’]This will reverse the Subjects List

Python Lists Remove

1234a =[1,2,3,4,11,5] a.remove(11)#this will remove 11 from the list.

Python Lists Remove Duplicates

Follow the steps below to remove duplicates from a list

  1. Create a dictionary with the same values from the list
  2. Convert it into a list
  3. Print the converted list. You will get a list with duplicates removed.
123Mylist =[a,b,c,b,c,a,c,a]b =list(dict.fromkeys(Mylist))print(b)

Python Tuples

A Tuple is a sequence of immutable Python objects. Tuples are sequences, just like Lists. The differences between tuples and lists are:

  • Tuples cannot be changed unlike lists
  • Tuples use parentheses, whereas lists use square brackets. Consider the example below:

Syntax

1chelsea =('hazard', 'terry', 'lampard')

Now you must be thinking why Tuples when we have Lists?

So the simple answer would be, Tuples are faster than Lists. If you’re defining a constant set of values that you just want to iterate, then use Tuple instead of a List. 

Guys, all Tuple operations are similar to Lists, but you cannot update, delete or add an element to a Tuple. 

Now, stop being lazy and don’t expect me to show all those operations, try it yourself.

Python Sets

A Set is an unordered collection of items. Every element is unique.

A Set is created by placing all the items (elements) inside curly braces {}, separated by a comma. Consider the example below:

Syntax

1set_name ={1,2,3,4,5}

In Sets, every element has to be unique. Try printing the below code:

1set_2 ={1,2,3,3,4,5}

Here 3 is repeated twice, but it will print it only once.

Let’s look at some Set operations:

Union:

Union of A and B is a set of all the elements from both sets. Union is performed using | operator. Consider the below example:

123A ={1, 2, 3, 4}B ={3, 4, 5, 6}print( A | B)
Output = {1, 2, 3, 4, 5, 6}

Intersection:

Intersection of A and B is a set of elements that are common in both sets. Intersection is performed using & operator. Consider the example below:

123A ={1, 2, 3, 4}B ={3, 4, 5, 6}print( A & B )

Output: {3,4}

Difference:

Difference of A and B (A – B) is a set of elements that are only in A but not in B. Similarly, B – A is a set of element in B but not in A. Consider the example below:

123A ={1, 2, 3, 4, 5}B ={4, 5, 6, 7, 8}print(A -B)

Output: {1,2,3}

Python Dictionary

Now let me explain you Dictionaries with an example.

I am guessing you guys know about Aadhaar Card. For those of you who don’t know what it is, it is nothing but a unique ID which has been given to all Indian citizen. So for every Aadhaar number, there is a name and few other details attached.

Now you can consider the Aadhaar number as a ‘Key’ and the person’s detail as the ‘Value’ attached to that Key.

Dictionaries contains these ‘Key Value’ pairs enclosed within curly braces and Keys and values are separated with ‘:’. Consider the below example:

Syntax

1dictionary_name ={key: value, key2: value2}

You know the drill, now comes various Dictionary operations.

Access elements from a dictionary:

12Dict={'Name': 'Saurabh', 'Age': 23}print(Dict['Name'])

Output = Saurabh

Changing elements in a Dictionary:

123Dict={'Name': 'Saurabh', 'Age': 23}Dict['Age'] =32Dict['Address'] ='Starc Tower'

Output = {'Name' = 'Saurabh', 'Age' = 32, 'Address' = 'Starc Tower'}

Dictionary Methods

  • clear()
  • copy()
  • values()
  • update()
  • fromkeys()
  • get()
  • items()
  • keys()
  • pop()
  • popitem()
  • setdefault()

Operators in Python

Operators are the constructs which can manipulate the values of the operands. Consider the expression 2 + 3 = 5, here 2 and 3 are operands and + is called operator.

Python supports the following types of Operators:

operators - python tutorial - edureka

Let’s focus on each of these Operators one by one.

Arithmetic Operators:

These Operators are used to perform mathematical operations like addition, subtraction etc. Assume that A = 10 and B = 20 for the below table.

OperatorDescriptionExample
+ AdditionAdds values on either side of the operatorA + B = 30
– SubtractionSubtracts the right hand operator with left hand operator A – B = -10
* MultiplicationMultiplies values on either side of the operatorA * B = 200
/ DivisionDivides left hand operand with right hand operatorA / B = 0.5
% ModulusDivides left hand operand by right hand operand and returns remainderB % A = 0
** ExponentPerforms exponential (power) calculation on operatorsA ** B = 10 to the power 20

Consider the example below:

12345678910111213141516171819202122a =21b =10c =0c =a +bprint( c )c =a -bprint( c )c =a *bprint( c )c =a /bprint( c )c =a %bprint( c )a =2b =3c =a**bprint( c )
Output = 31, 11, 210, 2.1, 1, 8

Now let’s see comparison Operators.