Python-PyCharm Tutorial
Python-PyCharm Tutorial
In PyCharm (IDE)
https://www.edureka.co/blog/pycharm-tutorial
Last updated on Dec 18
Anirudh Rao
Research Analyst at Edureka who loves working on Neural Networks and Deep Learning!
Python is an extremely popular language and widely used. This makes Python
certification one of the most sought-after programming certifications.
In this PyCharm Tutorial blog, I will be walking you through the following topics:
• What is an IDE?
• Why do you need an IDE?
• Introduction to Python
• Python Development Environments
• Introduction to PyCharm
• Important Tools & Features of PyCharm
• How Do I Run Pycharm?
• PyCharm Tips and Tricks For Beginners
Let’s begin this PyCharm Tutorial blog by checking out what an IDE actually is.
What Is An IDE?
An Integrated Development Environment (IDE) is a software environment used to
write programs using tools like an editor and compiler. This can prove to be an
extremely useful tool when coding in various languages for many reasons.
It is a software application that combines all of the features and tools needed by
a software developer. It is graphical in nature, meaning that it uses windows and
controls like buttons to display information and accept input from the user. For
example, tools can include:
Next up on this PyCharm Tutorial blog, let us check out why we need to make use
of an IDE.
Another feature to IDE’s is the ability to debug your program. This is arguably one
of the most important tools for deploying a successful program. Testing is crucial
to make sure that your user does not experience an incident where the code does
not handle a specific error and crash the program. Debugging provides you with
the ability to run through the program, stopping the code at specified points to
check values of variables or other interests as needed, to verify that the code and
functions are running as intended.
Finally, a few more tools that IDE’s offer can be resource management and the
ability to compile your code. When writing a new program there are usually many
different files that have been referenced in specific path locations so it is very
important for the running of the program that these files are in the correct
locations. Using an IDE makes it easy to see a visual representation of the location
of these files and makes it more understandable for the user.
Advantages to IDEs
Next up in this PyCharm Tutorial blog, let us take a quick introduction to Python.
An Introduction To Python
Python is a very versatile language. It has thousands of libraries and modules to
work with.
Personally, I think Python is really fun to work with when compared to all the
other languages out there. It is very beginner friendly which is very important and
the syntax is very simple to figure out. As a beginner, think this is very vital when
starting out with a language.
Well since Python and most of its libraries are open source it has gained a lot of
traction among startups and the industry as well. And this definitely leads to
millions of happy learners across the globe.
So you might be wondering why you should consider learning Python right?
Guys, it has such a wide range of application, I couldn’t fit it all in one image!
Next up in this PyCharm Tutorial blog, let us check out all the development
environments you can use to code Python in.
Another good thing about Python is that there are many IDEs you can make use
of. Everything from Eclipse, Notepad++, Bluefish, Komodo and Vim.
In my opinion, having a liking towards an IDE is similar to liking an ice cream flavor.
You have to try it and only then you will realize if this is for you or not.
I personally lean towards Pycharm because I love every single feature it provides
and I feel like home when coding in it.
Next up on this PyCharm Tutorial blog, let us check out a brief introduction to
PyCharm.
Introduction To PyCharm
Many programmers nowadays opt for Python to build software applications with
the concise, clean, and readable code base. They can even accelerate custom
software application development by taking advantage of a number of integrated
development environments (IDEs) for Python.
The developers can even customize the PyCharm UI according to their specific
needs and preferences. Also, they can extend the IDE by choosing from over 50
plug-ins to meet complex project requirements.
PyCharm is one of the most widely used IDEs for Python programming
language. At present, the Python IDE is being used by large enterprises like
Twitter, Pinterest, HP, Symantec, and Groupon.
Installing PyCharm
Installing PyCharm is pretty simple and straightforward. Head to the official
website using this
link: www.jetbrains.com/pycharm/download/#section=windows
Data Science with Python Certification Course
Explore Curriculum
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 and for
beginners and intermediate programmers, it is more than sufficient. But if you are
a professional programmer and want to completely make use of the IDE then go
ahead with the Professional version.
On that note, next up in this PyCharm Tutorial blog, let us check out the important
tools and features of PyCharm.
Here are some of the major features which stand out in terms of competition and
ease of use:
• Code Editor
• Code Navigation
• Refactoring
• Popular Web Technologies
• Support for Popular Python Web Frameworks
• Python Scientific Libraries
Code Editor
At the same time, the programmers can also use the editor to expand a code block
to an expression or logical block, avail code snippets, format the code base,
identify errors and misspellings, detect duplicate code, and auto-generate code.
Also, the editor makes it easier for developers to analyze the code and identify the
errors while writing code.
Code Navigation
The user can even find an item in the source code, code snippet, UI element, or
user action almost immediately. They can further locate the usage of various
symbols and set bookmarks in the code. At the same time, the developers can
even take advantage of the code navigation feature to scrutinize the code
thoroughly in the lens mode.
Refactoring
PyCharm makes it easier for developers to implement both local and global
changes quickly and efficiently. The developers can even take advantage of the
refactoring options provided by the IDE while writing plain Python code and
working with Python frameworks. They can avail the rename and move to refactor
for files, classes, functions, methods, properties, parameters, and local/global
variables.
Likewise, they can improve code quality by extracting variables, fields, constants,
and parameters. Also, PyCharm allows programmers to break up longer classes
and methods through extract method.
Popular Web Technologies
At the same time, the live edit feature provided by the IDE enables programmers
to see the changes made to the code instantaneously on a web browser. PyCharm
further allows developers to avail a JavaScript debugger as well as CoffeeScript and
TypeScript editors. It even simplifies isomorphic web application development by
supporting both AngularJS and NodeJS.
The Python IDE even helps web developers to debug Django templates, format the
code, verify the code, and manage .py consoles. At the same time, PyCharm also
supports widely used Python web frameworks like Pyramid and Web2Py. It
provides code completion and navigation options specific to the Pyramid.
Likewise, it allows web developers to avail code completion and navigation options
while working with Web2Py.
PyCharm further helps programmers to use Python more efficiently in big data
and data science projects. It supports some of the widely used scientific libraries
for Python — NumPy, Anaconda, and Matplotlib. The developers can work
efficiently with these scientific libraries by availing the interactive graphs, deep
code insight, and array viewers provided by the IDE.
They can even run the REPL Python console provided by PyCharm to avail robust
features like on-the-fly syntax check and code inspection. At the same time, the
programmers can also integrate the IDE seamlessly with IPython Notebook to
create innovative solutions without putting extra time and effort.
Now let us talk about the different tools that give PyCharm the upper hand:
• Database Tools
• Visual Debugger
• Built-in Terminal
• Software Testing
• Remote Development Capabilities
Let us now walk through what each of these in a slight bit of detail. Let us begin
with the Database Tools:
Database Tools
PyCharm further supports SQLAlchemy library and inject SQL code into code
written in various programming languages. The professional edition of the IDE
further makes it easier for developers to handle large volumes of data efficiently
through data grids.
Visual Debugger
The visual debugger provided by the IDE helps programmers to debug Python,
JavaScript, and Django code. The developers can use the inline debugger to see
live debugging data directly on the editor. Likewise, they can debug multiple
Python processes simultaneously and step through the code bypassing libraries.
PyCharm further creates a reusable and customizable configuration for each test
script or debugger execution. The users even have the option to facilitate remote
debugging by integrating the visual debugger with remote interpreters.
Built-in Terminal
PyCharm comes with local terminals for Windows, Linux, and macOS. The built-in
terminal enables programmers to continue coding and testing without leaving the
IDE. Also, the programmers can use the IDE to run Python files and configure
custom Python environments according to precise project requirements.
At the same time, they can run interactive Python or Django consoled directly in
the IDE. The console provides useful features like code completion, automatic
braces matching, and dynamic syntax change. The programmers even have the
option to integrate the console with both local and remote interpreters.
Software Testing
Like other IDEs, PyCharm also comes with features and tools to simplify Python
application testing. It allows developers to perform unit testing through popular
Python testing frameworks like Nose, Attest and Doctests. The testers even have
the option to run individual or multiple test files and test classes. They can further
integrate the IDE with Coverage.py to measure code coverage while testing the
applications.
While testing multi-threaded applications, the testers can use the thread
concurrency visualization option provided by the IDE to control the application
fully and efficiently. At the same time, PyCharm enables users to deliver high-
quality software by implementing behavior-driven development (BDD).
PyCharm allows developers to connect with various machines and build software
applications remotely. The programmers can avail the built-in SSH console
provided by the IDE to connect to machines and perform various development
tasks remotely through SSH. They can even run, debug, and profile the Python
applications in a remote environment by replacing the local interpreter with a
remote interpreter.
Next up on this PyCharm Tutorial blog, let us check out how we can go about
making use of PyCharm practically.
Let us begin by creating a new project. PyCharm greets you with the following
image as soon as you open it:
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.
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.
To install Python, use the official documentation to install or follow the instructions
as shown below:
Next
Clicking on the little gear icon on the right will bring up the following page:
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.
I have multiple versions of Python installed but for this example, I have been using
Python 3.7 as you can see from the above picture.
After this step is to basically create a scratch file by opening – File -> Create ->
Scratch File -> Python File
As soon as you finish this process, PyCharm will welcome you with a blank screen
and a scratch file ready for you to code in.
But, if you need to execute this program you will have to add a valid configuration
to the program.
Take a look at the below image. This is a result of clicking Add Configuration from
the scratch file screen.
Here you are supposed to add a name to the configuration – In this case, it
is ConfigName but it can be anything as per your requirement.
The Script Path indicates the Path of the scratch file which simply means that the
file location under the same directory.
As discussed earlier, we can choose and set the Project Interpreter at this point
in time.
The last step would be to hit Apply and close the window and the configuration is
added and set. Pretty easy, right?
So after setting up the configuration, you are pretty much ready to execute the
code and go on from there.
Output:
As you can check out from the above screenshot, we got the correct output in
the Python Console.
PyCharm Debugger
Debugging with PyCharm is an easy affair. All you need to do to set up breakpoints
is to click on the left-hand side of the code and the rod dot gets placed.
It is as shown in the image below. You can place any number of breakpoints that
you desire and break the code up and execute them.
You can also make use of the Watch option to check what values get fed into what
variables. This is definitely a big plus and when used along with the inline debugger
it adds a huge advantage to any programmer.
On the whole, this helps increase readability and documentation along with
making the process of debugging and testing very easy.
Next up in this PyCharm Tutorial blog, let us look at some simple tips and tricks
that you can make use of while working with PyCharm.
Duplicating a single line or a set of lines is as easy as selecting the lines and then
pressing Ctrl + D. This ensures to duplicate the selected lines onto the new lines
right after the selection. Do note that the indentation will be the same as the
original line.
Before Ctrl + D:
After Ctrl + D:
You can track and traceback changes to the files and the entire project by using a
keyboard shortcut which is Alt + Shift + C. This ensures a certain amount of
readability as well as knowing the recent changes which help you get better clarity
of the project lifecycle.
Refactoring:
Let us say you have a variable called “x” and you have used it about 100 times in
the program and suddenly you decide ‘x’ has to become ‘y’. The regular way to go
about this to find every ‘x’ and change it with ‘y’, right? Actually, no!
PyCharm supports an intelligent refactoring technique where all you need to know
if select that variable and choose the refactor setting. If you change it at one
occurrence then all the occurrences of that variables changes with just one click.
The biggest advantage is that this works perfectly for a variable under a certain
scope as well.
Intelligent Typing:
Pressing Alt and scrolling to select a certain piece of code will select everything in
that particular column only. This may be used for faster indentation or changing
the indentations at a rapid pace. However, it is also used to edit multiple
statements in the same column, thereby reducing the time and effort of doing it
manually.
Check out the following image for better clarity about the selection:
Conclusion
The concepts discussed in this Pycharm Tutorial should help you use PyCharm to
build your Python code quickly and efficiently.
This will be very handy when you are trying to create a Python program using the
PyCharm IDE which gives you a good number of advantages. This upper hand will
ensure that you can concentrate more on the code overall. This could very well be
your first step towards mastering Python.
After reading this blog on PyCharm Tutorial, I am pretty sure you want to know
more about Python. To know more about Python you can refer the following blogs:
• Introduction To Python
o What is Python?
o Python Interpreter
o Python Installation
▪ Python Installation For Windows
▪ Python Installation For Linux
▪ Python Installation For Mac
o Python IDE
▪ Which Python IDE?
▪ PyCharm
▪ Jupyter Notebook
o Why Learn Python?
o History of Python
o Python Applications
• Python Basics
o Python Keywords
o Python Comments
▪ Python Comments Block
o Python Variables
▪ Global Variables In Python
o Data Types In Python
▪ Python Strings
▪ Python Strings Format
▪ Python Strings Methods
▪ Python Strings Operations
▪ Numbers
▪ Python Integers
▪ Python Float
▪ Python Boolean
▪ Python Lists
▪ Python Lists Remove
▪ Python List Remove Duplicates
▪ Python Tuples
▪ Python Sets
▪ Python Dictionary
▪ Dictionary Methods
o Operators In Python
o Conditional Statements
▪ If,Else,Elif Statement In Python
▪ Conditional Statement Example
o Loops In Python
▪ For Loop In Python
▪ While Loop In Python
▪ Nested Loops In Python
o Python Functions
• File I/O In Python
• Python Modules
o Built-in Modules In Python
o OS
o Math
o Random
o Datetime
• Python OOPs
o Python Classes
o Inheritance In Python
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.
To get in-depth knowledge on Python Programming language along with its various
applications, you can enroll now for Python course Certification training with 24/7
support and lifetime access.
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!
• 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
Python is an interpreted language, meaning the interpreter reads the code and
executes it line by line. The interpreter can execute Python code from the
command line or within an IDE (Integrated Development Environment).
The Python interpreter can execute Python code from the command line or within
an IDE (Integrated Development Environment).
Python Installation
In this Python tutorial blog, we’ll show you how to install python no matter which
operating system you use. You can follow the steps given below and if you have
any queries during the process, feel free to leave a comment.
1. Go to www.python.org/downloads/
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.
Use the Graphical linux installation to install python on linux. Follow the steps
below:
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
1 export PATH="/usr/local/opt/python/libexec/bin:$PATH"
Now, we can install Python 3:
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.
Always keep the following points in mind while choosing the best IDE for Python:
Once these points are decided upon, the programmer can easily select among the
IDEs based on the given features.
PyCharm
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
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.
In this Python tutorial, we’ll also see how to use Pycharm, 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:
Creating a new project is as easy as clicking on the Create New Project tab and
going from there.
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.
Clicking on the little gear icon on the right will bring up the following page:
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.
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:
1 print('Welcome To Edureka!')
Let’s look at some cool features of Python:
History of Python
Python is a programming language created by Guido van Rossum in the late 1980s.
It is a high-level, general-purpose programming language that can be used for
many applications. The language is easily extensible and has a large and vibrant
open-source community.
• Python 2 and
• Python 3
Python version 2.0 was made public on the 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 the 3rd of December 2008. It was a crucial
revision of the programming language that is not completely backward-
compatible. A lot of its vital features were backported to Python 2.6. As well as the
2.7 version series. Further version releases of the 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 any more 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
The language has an extensive standard library and many third-party modules.
These libraries and modules can be used to develop desktop applications, web
applications, and games. These applications have been explained briefly below:
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.
1 import keyword
2 keyword.kwlist
3 #this will get you the list of all keywords in python.
4 keyword.iskeyword('try')
#this will return true, if the mentioned name is a keyword.
5
Identifiers are user defined names that we use to represent variables, classes,
functions, modules etc.
Syntax and Usage
1 name = 'edureka'
2 my_identifier = name
Python Popular libraries:
This Python tutorial will also explain some of the most popular python libraries
Python Comments
Syntax
Explore Curriculum
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.
Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
In Python you don’t need to declare variables before using it, unlike other
languages like Java, C etc.
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
1 S = 10
2 print(S)
This will assign value ‘10’ to the variable ‘S’ and will print it. Try it yourself.
Syntax
1 A = 10
2 Def function():
3 global a
4 A += 10
5 print(A)
print(A)
6 function()
7
Data Types In Python
Python supports various data types, these data types define the operations
possible on the variables and the storage method. In this section of the Python
tutorial, we’ll go through some of the commonly used data types in Python.
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
1 S= "Welcome To edureka!"
2 D = 'edureka!'
Python String Methods
1. strip()
2. Count()
3. split()
4. translate()
5. index()
6. format()
7. find()
8. center()
9. join()
Syntax Operation
print (len(String_Name)) String Length
print (String_Name.index(“Char”)) Locate a character in String
Count the number of times a character is repeated in a
print (String_Name.count(“Char”))
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
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:
1 A = 10
2 # Convert it into float type
3 B = float(A)
print(B)
4
The code above will convert an integer value to a float type. Similarly you can
convert a float value to integer type:
1 A = 10.76
2 # Convert it into float type
3 B = int(A)
print(B)
4
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
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:
Subjects [0] Physics This will give the index 0 value from the S
len (Subjects) [‘Physics, ‘Chemistry’, ‘Maths’, 2, 1, 2, 3] This will return the length of the list
[‘Physics’, ‘Chemistry’, ‘Maths’, 2]
Subjects * 2 This will repeat the Subjects List twice.
[‘Physics’, ‘Chemistry’, ‘Maths’, 2]
Subjects [::-1] [2, ‘Maths’, ‘Chemistry’, ‘Physics’] This will reverse the Subjects List
Python Lists Remove
1 a = [1,2,3,4,11,5]
2
3 a.remove(11)
4 #this will remove 11 from the list.
Python Lists Remove Duplicates
1 Mylist = [a,b,c,b,c,a,c,a]
2 b = list(dict.fromkeys(Mylist))
3 print(b)
Python Tuples
A Tuple is a sequence of immutable Python objects. Tuples are sequences, just like
Lists. We will see the differences between tuples and lists in this python tutorial.
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 created by placing all the items (elements) inside curly braces {}, separated
by a comma. Consider the example below:
Syntax
1 set_name = {1,2,3,4,5}
In Sets, every element has to be unique. Try printing the below code:
1 set_2 = {1,2,3,3,4,5}
Here 3 is repeated twice, but it will print it only once.
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:
1 A = {1, 2, 3, 4}
2 B = {3, 4, 5, 6}
3 print ( A | B)
Output = {1, 2, 3, 4, 5, 6}
Intersection:
A = {1, 2, 3, 4}
1 B = {3, 4, 5, 6}
2 print ( A ^ B )
3
Output: {3,4}
Difference:
1 A = {1, 2, 3, 4, 5}
2 B = {4, 5, 6, 7, 8}
3 print(A - B)
Output: {1,2,3}
Python Dictionary
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
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.
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.
1
2 a = 21
3 b = 10
4 c =0
5
6 c =a +b
print ( c )
7
8 c =a -b
9 print ( c )
10
11 c =a *b
12 print ( c )
13
14 c =a /b
print ( c )
15
16 c =a %b
17 print ( c )
18 a =2
19 b =3
c = a**b
20
print ( c )
21
22
Output = 31, 11, 210, 2.1, 1, 8
Now let’s see comparison Operators.
Comparison Operators:
These Operators compare the values on either sides of them and decide the
relation among them. Assume A = 10 and B = 20.
1
2
3 a = 21
b = 10
4 c =0
5
6 if ( a == b ):
7 print ("a is equal to b")
8 else:
print ("a is not equal to b")
9
10 if ( a != b ):
11 print ("a is not equal to b")
12 else:
13 print ("a is equal to b")
14
15 if ( a < b ): print ("a is less than b") else: print ("a is not less than b") if (
print ("a is greater than b")
16 else:
17 print ("a is not greater than b")
18
19 a =5
20 b = 20
if ( a<= b ): print ("a is either less than or equal to b") else: print ("a is nei
21
print ("a is either greater than or equal to b")
22 else:
23 print ("a is neither greater than nor equal to b")
24
25
Output = a is not equal to b
a is not equal to b
a is not less than b
a is greater than b
a is either less than or equal to b
b is either greater than or equal to b
Now in the above example, I have used conditional statements (if, else). It basically
means if the condition is true then execute the print statement, if not then execute
the print statement inside else. We will understand these statements later in this
Python Tutorial blog.
Assignment Operators:
1
2 a = 21
3 b = 10
4 c =0
5
6 c =a +b
print ( c )
7
8 c += a
9 print ( c )
10
11 c *= a
12 print ( c )
13
c /= a
14 print ( c )
15
16 c =2
17 c %= a
18 print ( c )
19
20 c **= a
print ( c )
21
22
Output = 31, 52, 1092, 52.0, 2, 2097152, 99864
Bitwise Operators:
Logical Operators:
x = True
1
y = False
2
3 print('x and y is',x and y)
4
5 print('x or y is',x or y)
6
7 print('not x is',not x)
8
Now in Python Tutorial, we’ll learn about Membership Operators.
Membership Operators:
1 X = [1, 2, 3, 4]
2 A =3
3 print(A in X)
print(A not in X)
4
Output = True
False
Next in Python Tutorial, it’s time we understand the last Operator i.e. Identity
Operator.
Identity Operators:
These Operators are used to check if two values (or variables) are located on the
same part of the memory. Two variables that are equal does not imply that they
are identical.
1 X1 = 'Welcome To edureka!'
2
X2 = 1234
3
4 Y1 = 'Welcome To edureka!'
5
6 Y2 = 1234
7
8 print(X1 is Y1)
9
10 print(X1 is not Y1)
11
12 print(X1 is not Y2)
13
print(X1 is X2)
14
15
Output: True
False
True
False
• First the control will check the ‘If’ condition. If it is true, then the control will
execute the statements after If condition.
• When ‘If’ condition is false, then the control will check the ‘Elif’ condition. If
Elif condition is true then the control will execute the statements after
Elif condition.
• If ‘Elif’ Condition is also false then the control will execute the Else
statements.
Syntax
if condition1:
1 statements
2
3 elif condition2:
4 statements
5
6 else:
statements
7
8
Consider the example below:
1 X = 10
2 Y = 12
3
4 if X <Y: print('X is less than Y') elif X >Y:
5 print('X is greater than Y')
else:
6 print('X and Y are equal')
7
Output: X is less than Y
Loops
This python tutorial will also explain loops. In general, statements are executed
sequentially. The first statement in a function is executed first, followed by the
second, and so on
There may be a situation when you need to execute a block of code several
number of times
• Pre-test: In this type of loops the condition is first checked and then only the
control moves inside the loop
• Post-test: Here first the statements inside the loops are executed, and then
the condition is checked
Loops in Python
• While
• For
• Nested
While Loop
Here, first the condition is checked and if it’s true, control will move inside the loop
and execute the statements inside the loop until the condition becomes false. We
use this loop when we are not sure how many times we need to execute a group
of statements or you can say that when we are unsure about the number of
iterations.
1 count = 0
while (count <10):
2 print ( count )
3 count = count + 1
4
5 print ("Good bye!")
6
Output = 0
1
2
3
4
5
6
7
8
9
Good bye!
For Loop
Like the While loop, the For loop also allows a code block to be repeated certain
number of times. The difference is, in For loop we know the amount of iterations
required unlike While loop, where iterations depends on the condition. You will
get a better idea about the difference between the two by looking at the syntax:
Syntax
It basically means a loop inside a loop. It can be a For loop inside a While loop and
vice-versa. Even a For loop can be inside a For loop or a While loop inside a While
loop.
1 count = 1
2 for i in range(10):
3 print (str(i) * i)
4
5 for j in range(0, i):
count = count +1
6
Output
1
22
333
4444
55555
666666
7777777
88888888
999999999
Django
Unlike other frameworks, Django is a python based open-source & free to use web
framework that includes a large number of built-in features rather than offering
them as separate libraries. Django uses its ORM for mapping objects to database
tables. Though Django has commendable support for MySQL, SQLite, PostgreSQL,
and Oracle Database, it can also support other databases via third-party drivers.
Flask
Flask allows the developers to build up a web application foundation from which
it is possible to use any extensions required, as it is a microweb framework written
in Python. Flask is compatible with Google App Engine.
AIOHTTP
Bottle
The bottle is a microframework that produces a single source file for each
application developed. It is one of the best python web frameworks, designed to
be fast, simple & lightweight. This microframework for Python was initially created
for building APIs.
CherryPy
web2py
Web2py is an open-source web application framework written in the Python
programming language. Web2py allows web developers to program dynamic web
content using Python.
Pylons Project
We can specify the mode while opening a file. In the mode, we specify whether we
want to
• read ‘r’
• write ‘w’ or
• append ‘a’ to the file. We also specify if we want to open the file in text mode
or binary mode.
The default is reading in text mode. In this mode, we get strings when reading
from the file.
Syntax
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done
using Python close() method.
1 o = open ("edureka.txt")
2 o.close()
Python Modules
This python tutorial will also explain what modules are in python. Modules are
simply a ‘program logic’ or a ‘python script’ that can be used for variety of
applications or functions. We can declare functions, classes etc in a module.
The focus is to break down the code into different modules so that there will be
no or minimum dependencies on one another. Using modules in a code helps to
write lesser line of codes, a single procedure developed for reuse of the code as
well. It also eliminates the need to write the same logic again and again.
Built-in modules are written in C and integrated with python interpreter. Each
built-in module contains resources for certain specific functionalities like
Operating system management, disk input/output etc.
The standard library also has many python scripts containing useful
utilities. There are several built-in modules in python at our disposal that we can
use whenever we want.
Some Of the Most Common and most useful built-in modules are:
• OS
• MATH
• RANDOM
• DATETIME
OS Module In Python
Example: os.popen(): This function is a part of file object manipulation and is used
to open a pipe to and from a command. The return value of this function can be
read or written dependent upon your use of r or w. The syntax for this function is
as follows, os.popen(command[, mode[, bufsize]]). The parameters taken into
consideration are, mode as well as bufsize. Take a look at the example below to
understand this better.
1
2 import os
3 fd = "GFG.txt"
4
# popen() is similar to open()
5 file = open(fd, 'w')
6 file.write("Hello")
7 file.close()
8 file = open(fd, 'r')
9 text = file.read()
print(text)
10
11 # popen() provides a pipe/gateway and accesses the file directly
12 file = os.popen(fd, 'w')
13 file.write("Hello")
14 # File not closed, shown in the next function.
15
Output: Hello
Some of the most important mathematical functions are defined in the math
module in python, the following example shows how we can use it in a program.
1 import math
2 print(math.pi)
3 #it will print the value of pi
Random Module In Python
The following example shows how we can use random in a program in python.
1 import random
2 print(random.random())
Datetime Module In Python
A date in python is not a type of its own, we can work on it by using the datetime
module in python. The following example shows how we can use it in a program
in python.
1 import datetime
2 print(datetime.datetime.now())
3 #it will print the current date and time
Python OOPs
OOPs refers to the Object-Oriented Programming in Python. Well, Python is not
completely object-oriented as it contains some procedural functions. Now, you
must be wondering what is the difference between a procedural and object-
oriented programming. To clear your doubt, in a procedural programming, the
entire code is written into one long procedure even though it might
contain functions and subroutines. It is not manageable as both data and logic get
mixed together. But when we talk about object-oriented programming, the
program is split into self-contained objects or several mini-programs. Each object
is representing a different part of the application which has its own data and logic
to communicate among themselves. For example, a website has different objects
such as images, videos etc.
Python Classes
A class in python is the blueprint from which specific objects are created. It lets
you structure your software in a particular way. Here comes a question how?
Classes allow us to logically group our data and function in a way that it is easy to
reuse and a way to build upon if need to be.
Using a class, you can add consistency to your programs so that they can be used
in cleaner and efficient ways. The attributes are data members (class variables and
instance variables) and methods which are accessed via dot notation.
1 class employee:
2 pass
3 #no attributes and methods
4 emp_1=employee()
emp_2=employee()
5 #instance variable can be created manually
6 emp_1.first='aayushi'
7 emp_1.last='Johari'
8 emp_1.email='[email protected]'
emp_1.pay=10000
9
10
emp_2.first='test'
11 emp_2.last='abc'
12 emp_2.email='[email protected]'
13 emp_2.pay=10000
14 print(emp_1.email)
print(emp_2.email)
15
16
17
Output:
[email protected]
[email protected]
Python Inheritance
A class which inherits the properties is known as Child Class whereas a class
whose properties are inherited is known as Parent class.
Say, I want to create classes for the types of employees. I’ll create ‘developers’ and
‘managers’ as sub-classes since both developers and managers will have a name,
email and salary and all these functionalities will be there in the employee class.
So, instead of copying the code for the sub-classes, we can simply reuse the code
by inheriting from the employee.
1
2 class employee:
3 num_employee=0
4 raise_amount=1.04
5 def __init__(self, first, last, sal):
self.first=first
6 self.last=last
7 self.sal=sal
8 self.email=first + '.' + last + '@company.com'
9 employee.num_employee+=1
10 def fullname (self):
return '{} {}'.format(self.first, self.last)
11 def apply_raise (self):
12 self.sal=int(self.sal * raise_amount)
13 class developer(employee):
14 pass
15
16 emp_1=developer('aayushi', 'johari', 1000000)
print(emp_1.email)
17
18
Output:
[email protected]
This brings us to the end of this Python tutorial article where we have learned
Python programming. I hope you have a clear understanding of everything that
has been shared with you in this blog. If you have additional questions or
suggestions, please leave a comment below and we will get back to you as soon
as possible.