0% found this document useful (0 votes)
17 views

Introduction

bca python

Uploaded by

hriday arora
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Introduction

bca python

Uploaded by

hriday arora
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Python

Python is a high-level, general-purpose,


interpreted programming language. By "interpreted", we mean
that Python code is "not compiled", instead the
Python interpreter turns the source code, line by line, once at a
time, into the machine code when the Python program executes.

Python is a case sensitive programming language.

Python is a popular programming language. It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

Python supports multiple and different programming paradigms,


such as:

Structural programming-a programming paradigm that


facilitates the creation of programs with only the three
constructions sequence of statements, decision (if..else)
and repetitions (loops).

Object-oriented programming-a computer programming


model that organizes software design around data, or
objects. object-oriented programming is an approach for
modeling concrete, real-world things, like cars, as well as
relations between things, like companies and employees,
students and teachers, and so on. OOP models real-world
entities as software objects that have some data
associated with them and can perform certain functions.

Functional programming-is a programming paradigm in which


we try to bind everything in pure mathematical functions style. Its
main focus is on “what to solve” in contrast to an imperative
style where the main focus is “how to solve“. It includes the
concepts like pure functions (produce the same output for the
same arguments irrespective of anything else), recursion,
Mutable and immutable objects.
History of Python
Python was developed by Guido van Rossum in the late
eighties and early nineties at the National Research Institute
for Mathematics and Computer Science in the
Netherlands.

Python is derived from many other languages, including


Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and
other scripting languages.
Python is now available under the GNU General Public License
(GPL).

Python labeled version was first published in February 1991


whereas, Python 1.0 was launched in 1994. List
comprehensions and garbage collection mechanisms were
included in Python 2.0. Python 3.0 (commonly known as “Py3K”)
was released on December 3, 2008. It was created to correct
language’s underlying weakness.
The ABC programming language (ABC, stands for is an interactive
programming language and environment for personal computing,
originally intended as a good replacement for BASIC-Beginners'
All-purpose Symbolic Instruction Code), had a major influence on
the design of the language Python,.

Generally, almost every type of company uses Python. For


example:

 Netflix
It is using Python for their "Recommender Systems" which
recommend the best web shows, and movies for users
by analyzing the data of customer’s/user’s watch history.

 Amazon

It is using Python to recommend the best shopping


items. It displays the similar products and products which
are usually purchased together.
 Facebook

Is displays custom ads on the next day according product


the seen in previous few days. This happens
because Facebook is using Python to generate 'custom ads'
according to the user behaviour and search history.

Features of python
Some of the important features of Python are as follows:
 Easy-to-learn − Python has few keywords, simple structure,
and a clearly defined syntax. Due to its simple syntax, you
can focus on the logic part rather than the syntax
implementations. This allows us to learn and maintain the
code in a better way.
 Dynamically typed language- we need not declare the
data types of the variables that they are working with
right at the beginning. This promotes creative freedom to
use variables as they please and even modify their type later
on.
 Versatile-It means to be able to adapt or to be used for
many different functions. There are countless domains
and scenarios where we use Python such as Artificial
Intelligence, Machine Learning, Data Analysis, Data Science
and Software Engineering.

 A broad standard library − Python's vast library set is very


which help to design complex applications and solve
problems. Some of the most widely used ones are- Django
for building Backend using Python, PyTorch for Deep
Learning, NumPy and Pandas for Data Science, PyGame for
Game Development
 Portable − Python can run on a wide variety of hardware
platforms and has the same interface on all platforms like
UNIX, Windows, and Macintosh.
 Extendable − You can add low-level modules to the Python
interpreter. These modules enable programmers to add to
or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major
commercial databases.
TIOBE "(The Importance Of Being Earnest)" represents the
popularity of programming languages based on search queries
across 20+ search engines.

Here is an image source from "TIOBE".

All these statistics show that Python is one of the fastest-growing


programming languages.

Python Libraries

A Python library is a collection of related modules. It contains


bundles of code that can be used repeatedly in different
programs. It makes Python Programming simpler and convenient
for the programmer. As we don’t need to write the same code
again and again for different programs. Python libraries play a
very vital role in fields of Machine Learning, Data Science, Data
Visualization, etc.
Most of the Python Libraries are written in the C programming
language. The Python standard library consists of more than 200
core modules. All these work together to make Python a high-
level programming language.
Python Standard Library plays a very important role. Without it,
the programmers can’t have access to the functionalities of
Python. But other than this, there are several other libraries in
Python that make a programmer’s life easier. Let’s have a look at
some of the commonly used libraries:

1. TensorFlow:
It is an open-source library used for high-level computations. It
is also used in machine learning and deep learning
algorithms. Researchers also use this Python library to solve
complex computations in Mathematics and Physics.

TensorFlow is designed to be fast, and it employs techniques


such as Accelerated Linear Algebra is a domain-specific
compiler for linear algebra.

With TensorFlow we can visualize each and every part of


the graph and it is flexible in its operations while working.

2. Matplotlib
This library is responsible for plotting numerical data. And
that’s why it is used in data analysis. It is also an open-
source library and plots high-defined figures like pie charts,
histograms, scatterplots, graphs, etc.

3. Pandas:
It is an open-source machine learning library that provides
flexible high-level data structures and a variety of analysis
tools. It eases data analysis, data manipulation, and
cleaning of data. Pandas support operations like analysis,
cleaning, Sorting, Concatenation, Conversion of data,
Visualizations, Aggregations, etc.

4. Numpy:
The name “Numpy” stands for “Numerical Python”. It is a
popular machine learning library that supports large
matrices and multi-dimensional data. It consists of in-built
mathematical functions for easy computations. Numpy is very
interactive and user friendly.

5. SciPy:
The name “SciPy” stands for “Scientific Python”. It is an
open-source library used for high-level scientific computations.
This library is built over an extension of Numpy. It works with
Numpy to handle complex computations. While Numpy
allows sorting and indexing of array data, the numerical data
code is stored in SciPy. It is also widely used by application
developers and engineers.

6. Scrapy:
It is an open-source library that is used for extracting data
from websites. It provides very fast web crawling and high-
level screen scraping. It can also be used for data mining
and automated testing of data.

7. Scikit-learn:
It is a famous Python library to work with complex data. Scikit-
learn is an open-source library that supports machine
learning. It supports variously supervised and
unsupervised algorithms like linear regression,
classification, clustering, etc. This library works in
association with Numpy and SciPy.
8. PyGame:
This library provides an easy interface to the Standard
Directmedia Library (SDL) platform-independent graphics,
audio, and input libraries. It is used for developing video
games using computer graphics and audio libraries along with
Python programming language. Pygame was officially written
by Pete Shinners.

9. PyTorch:

 PyTorch is the largest machine learning library that


optimizes tensor (Tensors are a type of data structure used in
linear algebra, and like vectors and matrices) computations.
It has rich APIs to perform tensor computations with strong
GPU acceleration. It also helps to solve application issues
related to neural networks. Graphs can be set up
dynamically and computed dynamically at any point during
code execution in PyTorch. In PyTorch, coding is simple
and processing is quick.

10. PyBrain:
The name “PyBrain” stands for Python Based Reinforcement
Learning, Artificial Intelligence, and Neural Networks library. It
is an open-source library built for beginners in the field of
Machine Learning. It provides fast and easy-to-use
algorithms for machine learning tasks. It is so flexible and
easily understandable and that’s why is really helpful for
developers that are new in research fields.

11. Keras
Keras is a Python-based open-source neural network library
that lets us experiment with deep neural networks
quickly. With deep learning becoming more common, Keras
emerges as a great option because, according to the
creators, it is an API (Application Programming Interface)
designed for humans, not machines. Keras has a higher
adoption rate in the industry and research community than
TensorFlow or Theano. It is recommended that you install
the TensorFlow backend engine before installing
Keras. Keras’ modular design makes it very expressive,
adaptable, and suited really well to cutting edge research.

Application areas of Python

Python in Data Science.

Just knowing “What is Python Programming?” is not enough, we


also have to be aware of its industry-based applications.

Data is the new oil and data is everywhere. With the passing of
every second of every day, more and more data is being
generated. Thus, there is a need to manage, analyze and
interpret this humongous data. That’s where Data Science comes
into the picture.

Managing data using database systems is not enough and neither


is just storing data. The data available can be used to solve a lot
of real-world problems- from "Risk Management" to building
intuitive "Healthcare solutions". The most common Python
libraries and modules that are used in Machine learning are
"Scikit-learn", "OpenCV" and "TensorFlow".

Python in Machine Learning

Technology has come a long way and now in our current times,
we are successfully able to make machines learn. That’s Machine
Learning in a nutshell for you! So it is advisable to learn more
about Machine Learning along with the answer to “What is Python
Programming?”
We use Python for building algorithms and models using Statistics
to allow computers to perform actions.

Python in AI

Just like Python is being used in Machine Learning, its presence in


the field of Artificial Intelligence is also very significant. Be it the
Terminator movies or Star Wars, we have loved watching AIs at
play in the movies. Well now, we can use Python to create our
very own!

Artificial intelligence is nothing but the intelligence that is not


displayed by humans i.e the intelligence depicted by machines. In
Python, packages libraries like NLTK and FANN help you build your
own AIs.

Python in Web Development


Python is also very popular for Web Development. Python has a
lot of libraries and frameworks such as Django, Flask, Web2py,
Pyramid etc- which are used extensively to develop the backend
and the related APIs.

The numerous frameworks make it much easier for developers to


develop web applications using Python.

There are many websites that are powered using these


frameworks of Python such as Spotify, Reddit etc.

Python is used in Automation

Python is not just a programming language but also a scripting


language! A scripting language basically allows us to automate
our work so that the work can be executed without human
intervention. Automation saves both the time and energy of the
programmer.

Redundant tasks such as reading-writing files, scraping files from


the web can be achieved very easily through automation using
scripting.

Python in Building GUI


"GUI" refers to the interface that a user can use to interact with
applications. You can also use Python for building a graphical user
interface (GUI). There are many cross-platform GUI toolkits
available such as "PyQt", Pyside etc. The standard Python GUI
library is "Tkinter", which is included when we install Python for
almost all Operating Systems.

Python in testing frameworks

The process of evaluating the product or application’s proper


functioning is known as testing.

Automated testing is a well-known context in the field of testing.


Python comes with several testing frameworks & libraries that
support automated testing for your system.

Python test cases are comparatively easy to write. Python also


supports cross-platform and cross-browser testing with
frameworks like PyTest, Robot.

There are also other testing frameworks available in Python such


as:Unittest, DocTest, Nose2, Testify

Python in Web Development

Web development is a huge domain, and Python is one of the


most preferred languages.

Python can be used in web development to create the backends


for websites.

There are two parts of a website:

1. Frontend: All the part of the website that is visible to you


2. Backend: All the behind the scene work that is performed on
your request

The most popular frameworks of Python for creating backends


are:

 Flask
 Django

Both of these allow the creation of a fully functional website. They


are easy to learn as they have great documentation.

Many big websites like Instagram, Netflix, and Spotify use Python
to develop their product.

Python in Developing Games

Python can be used for game development. It can be used to


create both 2D and 3D games. One of the most popular modules
for 2D game development is PyGame. It is simple, easy to learn,
and has a huge community.

We can use it to create games like Flappy Bird, Tic Tac Toe,
Minesweeper, etc.

Not only 2D games, we can also make 3D games. For this, PySoy
can be used.

Some famous games that used Python include Battlefield 2,


Pirates of the Caribbean Online, The Sims 4, World of Tanks, Vega
Strike, etc.

Python in Creating GUI Apps

Python can run on almost all platforms, making it a great choice


to develop Graphical User Interface (GUI) based applications.

Tkinter, PyQt, and Kivy are some of the most famous libraries for
this purpose.

Tkinter comes as an inbuilt module with Python by default. The


other two can be installed very easily.

Some famous applications made with Python are Anki and


Dropbox.
Python in performing Complex Calculations

This is yet another field where simple syntax and powerful


libraries help.

There is a need for many complex calculations that need to be


performed quickly in the research field. Many mathematicians and
computer scientists have created libraries like SciPy, Numpy and
Pandas that enable us to do complex mathematical calculations
very quickly.

Python in Software Development

Python has many packages which aim to simplify some task or


the other. Python is used for development and as a support
language for management and testing.

The most popular tools and libraries for this purpose are SCons,
Buildbot, Trac, etc.

Python in Business Applications

Python is used in business/enterprise applications. These are very


different from standard applications. These applications focus
mainly on readability, extensibility, and scalability. Another
important point in this domain is the capability to integrate with
legacy systems.

Python can handle these things easily with its useful features like
performance, flexibility, cross-platform support, and scalability.

Examples of these tools include Oddo and Tryton.

Python in Human-Machine Interaction

As everything becomes digital, interacting with machines has


become a necessity rather than a skill. It is very easy to find
Python being used in different fields for interacting with
machines.

The steep learning curve of Python makes it a great choice in


fields where programming is not the main skill.
An example of this scenario is that Mechanical Engineers are
taught Python, which helps them create and test various complex
projects. This includes making a digital circuit, a model of a
machine, or making a machine using Raspberry Pi or Arduino.

Python in Audio and Video-based Applications

Python has many packages which can be used for multimedia


applications. TimPlayer and Cplay have been developed using
Python.

Some packages that can be used for this purpose are wave,
audioloop, gstreamer, pyglet

Python in Scraping Websites

Python is the first choice for extracting and handling huge


amounts of data from websites. Extracting data from websites
may include applications in various fields like research, price
comparison, and job listing.

Some popular libraries and frameworks which are commonly used


for this purpose are

 BeautifySoup
 Scrapy
 Requests
 Selenium

Python in CAD Applications

CAD or Computer Aided Designing uses computers to help create,


modify, analyze, and optimize a design. This is heavily used in
automobiles, weapons, and the aerospace industry.

Python supports a wide range of CAD applications like Fandango,


FreeCAD
Python in Image Processing and Graphic Design Applications

Python allows us to work with images. We can do some


processing on the images to make them beautiful or analyze
them to extract some useful information.

OpenCV and Pillow are two modules that allow us to do almost


anything with the images.

One of the most famous applications of OpenCV is OCR (Optical


Character Recognition), which uses Machine Learning to detect
the written text in images.

Python in Writing Scripts

A Python script is a collection of commands stored in a file


designed to be executed like a program. The main idea is that this
file can be executed from the command line. Generally, a script
focuses on accomplishing some specific task.

Python is the most preferred scripting language, thanks to its


runtime nature.

Many types of scripts can be written with Python.

Some common use cases are:

 Scraping websites and saving their data in excel or any other


file type.
 Automation like sending emails, converting images.
 Writing scripts to automate tasks in Adobe Photoshop,
Blender.
 Performing actions on excel files.
 Creating PDFs or editing them.
 Entering bulk data on a website.
 Writing tests for your code.

Versions
Python 2 Vs. Python 3

The two versions of Python- Python 2 and Python 3 are the most
widely used Python versions and there are many differences
between these versions which are as follows:
Python 2 Python 3

The release year of Python 2 is 2000 The release year of Python 3 is 2008

The syntax is more complex in this The syntax is comparatively easy


version than in Python 3 and simple

By default, strings are saved in ASCII By default, strings are saved in


(American Standard Code for Information UNICODE (Universal Character Set)
Interchange ) format in version 2 of format in this version.
Python

In Python 2, Print is a statement. So, In Python 3, Print is a function. So,


the syntax is print “hello” the syntax is print (“hello”).

Python 2 is not that popular after Python 3 is a more popular version of


2020 compared to Python 3 Python and is being used for many
purposes

Install Python on Windows

First, download the latest version of Python from the download


page.

Second, double-click the installer file to launch the setup wizard.

In the setup window, you need to check the Add Python 3.8 to
PATH and click the Install Now to begin the installation.
It’ll take few minutes to complete the setup.
Once the setup completes, you’ll see the following window:

Verify the installation

To verify the installation, you open the Run window and type cmd
and press Enter:

In the Command Prompt, type python command as follows:


If you see the output like the above screenshot, you’ve
successfully installed Python on your computer.

To exit the program, you type Ctrl-Z and press Enter.

If you see the following output from the Command Prompt after
typing the python command:

‘python’ is not recognized as internal or external command,


operable program or batch file

Code language: Shell Session (shell)

It’s likely that you didn’t check the Add Python 3.8 to
PATH checkbox when you install Python.

Start with Python-Execute a command

Any python statement can be executed by writing directly in the


Command Line:

>>> print("Hello World!!!")


Hello World!!!

Or by writing the content in the file and then using the .py file
extension, and running it in the Command Line:
Example:

Save file as: Myfirstfile.py

print("Hello world");

c:\users\.....>python myfirstfile.py

Comments

The comments are the lines of explanation that we include in the


code just to make our code more understandable. These lines
help the programmer to recall the purpose of each and every
variable and function that is included in the code.

When the Python interpreter executes the code, it ignores the


comments.

In Python, a single line comment begins with a hash (#) symbol


followed by the comment. For example:

Example 1:

#this program prints a message

print("Hello world");

Output:

Hello world

Note: In python, Singlw quote (‘ ’), double quote (“ ”) and triple


quote works (‘’’ ‘’’)
Example 2:
print('Hello world');
print("Hello world");
print('''Hello world''');
Output:
Hello world
Hello world
Hello world

Note: Triple quote works like a single statement, even after


written in different line.
print('''This is first line
This is second line
This is third line''');

Continuation of statements

Python uses a newline character to separate statements. It places


each statement on one line.

However, a long statement can span multiple lines by using the


backslash (\) character.

The following example illustrates how to use the backslash (\)


character to continue a statement in the second line:

Example:

print("In this print statement we will print a very\

long statement with help of slash\

which allow us to write content in continuation to previous


content.")

Output:
In this print statement we will print a very long statement with
help of slash which allow us to write content in continuation to
previous content.
Identifiers

Identifier means anything that is used to identify something in the


program, be it a variable name, function name, array name or
anything else.

There are certain rules for identifier which we should keep in


mind:

May start with a letter A to Z or a to z or an underscore (_)


followed by zero or more letters, underscores and digits (0 to 9).
Punctuation characters such as @, $, and % are not allowed.

Python identifiers are case-sensitive. For example,


the count and Count are different identifiers.

Keywords

Keywords are the reserved words. These reserved words have a


special meaning and are reserved for some specific purpose in
python. Some of the keywords are as follows:

Python is a growing and evolving language. So its keywords will


keep increasing and changing.

To find the current keyword list, you use the following code:

Example:

import keyword

print(keyword.kwlist)

Output:
String literals

Python uses single quotes ('), double quotes ("), triple single
quotes (''') and triple-double quotes (""") to denote a string literal.

The string literal need to be enclose with the same type of quotes.
For example, if you use a single quote to start a string literal, you
need to use the same single quote to end it.

The following shows some examples of string literals:

Example:
s = 'This is a string'

print(s)

s = "Another string using double quotes"

print(s)

s = ''' string can span

multiple line '''

print(s)

Variable

Variable is a named location to save a value. The value can be


a number, float or characters.

When we develop a program, we need to manage some values.


To store values, we use variables. The values of variable can
be changed at any point of time during the program.
In Python, a variable is a label that you can assign a value to it.
And a variable is always associated with a value. Variable
names should be concise and descriptive. For example: Use
emp_sal to save salary of employee instead of es.

Example:

str="Hello"

print(str)

a=25

print(a)

b=14.7

print(b)

Output:

Here, str, a and b are variables.

The declaration happens automatically when you assign a value


to a variable. The equal sign (=) is used to assign values to
variables.

The operand to the left of the = operator is the name of the


variable and the operand to the right of the = operator is the
value stored in the variable.

Rule for naming a variable

When you name a variable, you need to adhere to some rules. If


you don’t, you’ll get an error.

The following are the variable rules that you should keep in mind:
 Variable names can contain only letters, numbers, and
underscores (_).
 Variable can start with a letter or an underscore (_),
not with a number.
 Variable names cannot contain spaces. To separate words
in variables, you use underscores, Eg. stud_age (for student
age).
 Variable names cannot the same as keywords and built-
in functions in Python.

Multiple Assignment
Python allows you to assign a single value to several
variables simultaneously.
Example:
a=b=c=1
print(a,b,c)
Output:

Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location.
Note:We can also assign multiple objects to multiple variables.
Example:
a,b,c = 1,2,"john"
print(a,b,c)
Output:

Here, two integer objects with values 1 and 2 are assigned to


variables a and b respectively, and one string object with the
value "john" is assigned to the variable c.
Note:
Example 1:
a,b,c = 1,2
print(a,b,c)
Output:
Error
Example 2:

a,b,c = 1,2,3,"abc"

print(a,b,c)
Output:

Error

Data types
The data stored in memory can be of many types. For example, a
person's age is stored as a numeric value and his or her address
is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations
possible on them and the storage method for each of them.
Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary
The two basic categories of data types are:

Mutable

Mutable in Python can be defined as the object that can change or be


regarded as something changeable in nature. Mutable means the ability to
modify or edit a value.

Mutable objects in Python enable the programmers to have objects that can
change their values. They generally are utilized to store a collection of data.
It can be regarded as something that has mutated, and the internal state
applicable within an object has changed.

Mutable means those objects which can change themselves after we


instantiate them. There are several methods and functions by which we can
change the mutable objects. By using those methods and functions the
original objects get modified.

While doing any changes to the mutable objects the memory at which those
objects are stored remains the same. This is explained in different
sections Mutable Objects read along to know more.

Example: list, dictionary, set and user-defined classes.


Example:
color = ["Red", "Green", "Blue"]

print(color)

Output:

['Red', 'Green', 'Blue']

color[0] = "Black"

color[-1] = "White"

print(color)

Output:

['Black', 'Green', 'White']

Immutable

Immutable objects in Python can be defined as objects that do not change


their values and attributes over time.
These objects become permanent once created and initialized, and they form a
critical part of data structures used in Python.

Python is used in numbers, tuples, strings, frozen sets, and user-defined classes
with some exceptions. They cannot change, and their values and it remains
permanent once they are initialized and hence called immutable.

Immutable means those objects which can't change themselves after we


initialize them. There are no methods and functions which can be used to
modify those immutable objects. We have to convert those immutable
objects to the mutable once and then we can modify those objects.

While doing any changes to the immutable objects, the memory at which
these objects were stored during initialization, gets updated. This is
explained in different sections Immutable Objects read along to know more.

Immutable means those objects which can't change themselves after we


initialize them. There are no methods and functions which can be used to
modify those immutable objects. We have to convert those immutable
objects to the mutable once and then we can modify those objects.

Example:

int, float, decimal, bool, string, tuple, and range.

Example:

greeting = "Welcome to EyeHunts"

greeting[0] = 'Hello'

print(greeting)

Output:

Error

Conclusion
1. Mutable and immutable objects are handled differently in python. Immutable
objects are quicker to access and are expensive to change because it involves the
creation of a copy.
Whereas mutable objects are easy to change.
2. Use of mutable objects is recommended when there is a need to change the size or
content of the object.
3. Exception : However, there is an exception in immutability as well. We know that
tuple in python is immutable. But the tuple consists of a sequence of names with
unchangeable bindings to objects.
Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t change
its value. But the contents of the list can change. The tuple itself isn’t mutable
but contain items that are mutable.
As a rule of thumb, Generally Primitive-like types are probably immutable and
Customized Container-like types are mostly mutable.

In programming, data type is an important concept.


Variables can store data of different types, and different types
can do different things.

Python has the following data types built-in by default, in these


categories:

Text Type: str

Numeric Types: int, float, complex

Sequence list, tuple, range


Types:

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Getting the Data Type

You can get the data type of any object by using


the type() function:

Example:

Print the data type of the variable x:

x=5
print(type(x))

Output:
<class 'int'>

Python Numbers

There are three numeric types in Python:

 int
 float
 complex

Variables of numeric types are created when you assign a value


to them:

Example

To verify the type of any object in Python, use the type() function:

x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))

Output:

<class 'int'>

<class 'float'>

<class 'complex'>

Int

Int, or integer, is a whole number, positive or negative, without


decimals, of unlimited length.
Example

Integers:

x=1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))

Try it Yourself »

Float

Float, or "floating point number" is a number, positive or negative,


containing one or more decimals.

Example

Floats:

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Try it Yourself »

Float can also be scientific numbers with an "e" to indicate the


power of 10.

Example

Floats:
x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

Try it Yourself »

ADVERTISEMENT

Complex

Complex numbers are written with a "j" as the imaginary part:

Example

Complex:

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))

Try it Yourself »

Type Conversion

You can convert from one type to another with the int(), float(),
and complex() methods:
Example

Convert from one type to another:

x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Try it Yourself »

Note: You cannot convert complex numbers into another number


type.

Random Number

Python does not have a random() function to make a random


number, but Python has a built-in module called random that can
be used to make random numbers:
Example

Import the random module, and display a random number


between 1 and 9:

import random

print(random.randrange(1, 10))

Try it Yourself »

Python Casting

❮ PreviousNext ❯

Specify a Variable Type

There may be times when you want to specify a type on to a


variable. This can be done with casting. Python is an object-
orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a


float literal (by removing all decimals), or a string literal
(providing the string represents a whole number)
 float() - constructs a float number from an integer literal, a
float literal or a string literal (providing the string represents
a float or an integer)
 str() - constructs a string from a wide variety of data types,
including strings, integer literals and float literals

Example

Integers:

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Try it Yourself »

Example

Floats:

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

Try it Yourself »

Example

Strings:

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Boolean Values

In programming you often need to know if an expression


is True or False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

When you compare two values, the expression is evaluated and


Python returns the Boolean answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

Output:
True

False

False

Preventing Escape Sequence Interpretation in Python


 Last Updated : 04 Dec, 2021
Escape Sequence is a combination of characters (usually prefixed
with an escape character), that has a non-literal character
interpretation. Such that, the characters sequences which are
considered as an escape sequence have a meaning other than
the literal characters contained therein. Most Programming
languages use a backslash \ as an escape character. This
character is used as an escape sequence initiator, any character
(one or more) following this is interpreted as an escape sequence.
If an escape sequence is designated to a Non-Printable Character
or a Control Code, then the sequence is called a control
character.
List of Escape Sequence in Python:
Escape
Character Meaning

\’ Single quote

\” Double quote

\\ backslash

\n New line

\r Carriage Return

\t Horizontal tab

\b Backspace

\f form feed
Escape
Character Meaning

\v vertical tab

\0 Null character

\N{name} Unicode Character Database named Lookup

\uxxxxxxxx Unicode Character with 16-bit hex value XXXX

Unicode Character with 32-bit hex value


\Uxxxxxxxx XXXXXXXX

\ooo Character with octal value OOO

\xhh Character with hex value HH


The above table is applicable for Python programming language,
as different languages have different control sequences and
control characters so the above table may not work in your
programming language of choice. Ex. Windows Command Line
interpreter uses a caret ( ^ ) to escape characters, and therefore
the above table won’t be applicable there.
Escape Sequence Interpretation
Escape sequence interpretation is done, when a backslash is
encountered within a string. After the encounter of a backslash
(inside a string), any following character (with the ( \ )) would be
looked upon the aforementioned table. If a match is found then
the sequence is omitted from the string, and its translation
associated with the sequence is used. If a match is not found,
then no lookup happens, and the control sequence is copied as it
is.

Suppose you have the string containing a double backslash (\\\\),


and you want to print the string with a double backslash, but it is
impossible to print it directly. So here comes the role of escape
sequences.
Firstly, understand sequences. A sequence is just a set of two or
more characters and an escape where the sequence begins with a
backslash (\\) and other characters in the set follow that
backslash.

An escape sequence is a sequence of characters that, when used


inside a character or string, does not represent itself but is
converted into another character or series of characters. So
escape sequences are formed using two things: the first is a
backslash (\\), and the second is the set of one or more characters
following that backslash (\\).

List of Escape Sequence Available in Python


Escape Sequence Meaning

\’ Single quote

\\’ Double quote

\\ Backslash

\n Newline

\r Carriage Return

\t Horizontal Tab

\b Backspace

\f Formfeed

\v Vertical Tab

\0 Null Character

\N{Name} Unicode character Database named lookup

\uxxxxxxxx Unicode character with a 16-bit hex value

\Uxxxxxxxx Unicode character with a 32-bit hex value

\000 Character with octal value ooo

\xhh Character with hex value hh


Escape Sequence Meaning

How to escape single quotes in Python

As we know, if we use a single quote inside the string directly,


and that string is closed inside a pair of single quotes, then the
interpreter will get confused and give an error output.

For Example,
We want to print who's this.

print('Who's this?')

If we execute this directly, we get an error message -

SyntaxError: invalid syntax. Perhaps you forgot a comma?


^^^^^^
print('Who's this?')
Line 1 (Solution.py)

Why this error occurred?

The interpreter is confused, it can't find the starting position of a


single quote since it occurred three times.

How to overcome?

To overcome this problem we can use escape sequences here.

print('Who\'s this?')

Output:

Who's this?

The above examples show how a single quote is printed in


(Who’s) using a backslash (‘\’).

It happened because of the backslash (‘\’) before any character


tells the interpreter that this combination is an escape sequence
in python, removing the backslash from the string and putting the
quote inside the string.

n Escape Sequence in Python

Suppose I give a string, so it will not be considered a new line.


What if we want to print some part of the particular string in the
new line?

We can use “\n” here, which tells the interpreter to print some
characters in the new line separately.

Example:

print('Interview\nBit')

Output:

Interview
Bit

The above example shows that "Bit" is printed in a new line.

So we can say that we will get the new line when we type \n in
the string before any word or character.

Backslash Escape Sequence in Python

What if we want to print a single backslash? We can't do it by just


writing "", so we'll use "\\".

Example:

print('Interview\\Bit')

Output:

Interview\Bit
Python escape sequence for Space

If we want to add tab space between words, then this escape


sequence will give the tab space between the words or characters
using “\t”.

Example:

print('Interview\tBit')

Output:

Interview Bit

From the above screenshot, you can see that if we want a tab
space between two words, then we can use this ‘\t’ escape
sequence to print the spaces.

Backspace Escape Sequence in Python

This escape sequence is used to remove the space between the


words.

Example:

print('Interview \bBit')

Output:

InterviewBit
Python escape sequence for Hexa value

Now, there may be a situation where we have Hexa values, and


we want to print alphabets using their Hexa values? In such a
case, we can use “\xhh”, where hh is the unique Hexa value of
the alphabets.

Example:

print("\x48\x45\x4C\x4C\x4F\x20\x57\x4F\x52\x4C\x44")

Output:
Hello World

As you can see in the above example, the characters are printed
according to their respective Hexa values, followed by the ‘\x’.

Python escape sequence for Octal value

Now, what if we want to print alphabets using their octal values?


So for that, we will use “\ooo”, where ooo is the unique octal
value of the alphabets.

Example:

print("\110\105\114\114\117\040\127\117\122\114\104")

Output:

Hello World

As you can see in the above example, the characters are printed
according to their respective octal values, followed by the ‘\’.

Remove all escape sequence from a list

Now, what if we want to remove all the escape sequences from


the list? So let’s take an example:

Example:

s = ['Hello','\x50','to','\x44','World']
print(s)

Output:

['Hello', 'P', 'to', 'D', 'World']

In the above example, there is a list that contains two Hexa


values (‘x50’ and ‘x44’), so if we just put a "\" before them, then
we can escape them all. As you can see, “x50” is replaced by its
Hexa value ‘P’, and “x44” is replaced by ‘D’ by putting "\" before
them.
Python escape sequence ignore

To ignore all the escape sequences in the string, we have to make


a string as a raw string using ‘r’ before the string. After that
escape sequence will also be considered normal characters. Let's
take an example.

Example:

print(r"Hello\nWorld")

Output:

Hello\nWorld

From the example above, you can observe that when we


typed ‘r’ before the string, it ignored the escape sequence that is
a new line “\n” in the string.

Python escape sequence remove

To remove all the characters from the left and right of an


argument string, we will use the string.strip() function.

Example:

s = '\r\r\b InterviewBit \r\r\n '


s.strip
print(s)

Output:

Escape Sequence Interpretation

When a backslash appears in a string, the escape sequence is


interpreted. After encountering a backslash (inside a string), the
subsequent character (with the (\)) would be checked on the
escape sequence table, which is the table mentioned earlier. If a
match is detected in the table, the sequence is removed from the
string and is translated to normal character. If no match is
detected, no lookup is performed, and the control sequence is
copied exactly as it is.

Example:

# A string with a Valid escape sequence


print("Interview\tBit")

# A string with a Invalid escape sequence


print("Scaler\cAcademy")

Output:

Interview Bit
Scaler\cAcademy

As seen in the above output, the first print statement produced


output with one tab space because of \t is present in the table. On
the other hand, in the second print statement, the \c persists, as
no legal resolution for that sequence exists.

Preventing Escape Sequence Interpretation

There are some situations where we don't want the string to


behave as shown above (which means printing the translation of
the sequence present in the sequence table). Some situations are
shown below where we must print the same sequence instead of
its translation.

 A string contains a network or a local path.


 The strings that contain regex, which the regex engine would
further process.

Methods of Prevention

 Method 1

It is tedious and only advised if the string size is less. Just


doubling the backlash allows us to overcome such issues. In
this method, we manually find the single backslash and
concatenate it with another backslash.
Example:

print("Interview \t Bit")

print("Interview \\t Bit")

Output:

Interview Bit
Interview \t Bit

In the first case, "\t" was considered a tab space, but in the
second one, "\t" was printed as a normal literal.

 Method 2

We can use the concept of raw string, i.e.,


adding r or R before the string, which will preserve the
escape sequences as literals.

Example:

print("C:\Interview Bit\nScaler\aAcademy")
print(r"C:\Users\Dell\OneDrive\Desktop")

Output:

C:\Interview Bit
ScalerAcademy
C:\Users\Dell\OneDrive\Desktop

In raw string as you can see that escape sequences are


preserved as literals.

You might also like