Unit 1
Unit 1
What is Python
Python is an easy-to-learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.
With its interpreted nature, Python's syntax and dynamic typing make it an ideal language for
scripting and rapid application development.
We don't need to use data types to declare variable because it is dynamically typed, so we can
write a=10 to assign an integer value in an integer variable.
Python makes development and debugging fast because no compilation step is included in
Python development, and the edit-test-debug cycle is very fast.Python has many web-based
assets, open-source projects, and a vibrant community. Learning the language, working together
on projects, and contributing to the Python ecosystem are all made very easy for developers.
Because of its straightforward language framework, Python is easier to understand and write
code in. This makes it a fantastic programming language for novices. Additionally, it assists
seasoned programmers in writing clearer, error-free code.
Python is an open-source, cost-free programming language. It is utilized in several sectors and
disciplines as a result.
In Python, code readability and maintainability are important. As a result, even if the code was
developed by someone else, it is easy to understand and adapt by some other developer.
Python has many third-party libraries that can be used to make its functionality easier. These libraries cover
many domains, for example, web development, scientific computing, data analysis, and more.
Python Basic Syntax
1. def func():
2. statement 1
3. statement 2
4. …………………
5. …………………
6. statement N
In the above example, the statements that are the same level to the right belong to the function.
Generally, we can use four whitespaces to define indentation.
Instead of Semicolon as used in other languages, Python ends its statements with a NewLine
character.
Python is a case-sensitive language, which means that uppercase and lowercase letters are treated
differently. For example, 'name' and 'Name' are two different variables in Python.
In Python, comments can be added using the '#' symbol. Any text written after the '#' symbol is
considered a comment and is ignored by the interpreter. This trick is useful for adding notes to
the code or temporarily disabling a code block. It also helps in understanding the code better by
some other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords in Python
that cannot be used as variable names. These terms are used in the language for particular
reasons and have fixed meanings. If you use these keywords, your code may include errors, or
the interpreter may reject them as potential new Variables.
Python provides many useful features to the programmer. These features make it the most
popular and widely used language. We have listed below few-essential features of Python.
o Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike
traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
o Expressive Language: It allows programmers to express complex concepts in just a few
lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
o Object-Oriented Language: It supports object-oriented programming, making writing
reusable and modular code easy.
o Open Source Language: Python is open source and free to use, distribute and modify.
o Extensible: Python can be extended with modules written in C, C++, or other languages.
o Learn Standard Library: Python's standard library contains many modules and
functions that can be used for various tasks, such as string manipulation, web
programming, and more.
o GUI Programming Support: Python provides several GUI frameworks, such as Tkinter
and PyQt, allowing developers to create desktop applications easily.
o Integrated: Python can easily integrate with other languages and technologies, such as
C/C++, Java, and . NET.
o Embeddable: Python code can be embedded into other applications as a scripting
language.
o Dynamic Memory Allocation: Python automatically manages memory allocation,
making it easier for developers to write complex programs without worrying about
memory management.
o Wide Range of Libraries and Frameworks: Python has a vast collection of libraries
and frameworks, such as NumPy, Pandas, Django, and Flask, that can be used to solve a
wide range of problems.
o Versatility: Python is a universal language in various domains such as web development,
machine learning, data analysis, scientific computing, and more.
o Large Community: Python has a vast and active community of developers contributing
to its development and offering support. This makes it easy for beginners to get help and
learn from experienced developers.
o Career Opportunities: Python is a highly popular language in the job market. Learning
Python can open up several career opportunities in data science, artificial intelligence,
web development, and more.
o High Demand: With the growing demand for automation and digital transformation, the
need for Python developers is rising. Many industries seek skilled Python developers to
help build their digital infrastructure.
o Increased Productivity: Python has a simple syntax and powerful libraries that can help
developers write code faster and more efficiently. This can increase productivity and save
time for developers and organizations.
o Big Data and Machine Learning: Python has become the go-to language for big data
and machine learning. Python has become popular among data scientists and machine
learning engineers with libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and
more.
o Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
o Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI -
Graphical User Interface-based Desktop Applications. There are better languages for this
field, but it can be used with other languages for making Applications.
o Console-based Applications: Python is also commonly used to create command-line or
console-based applications because of its ease of use and support for advanced features
such as input/output redirection and piping.
o Mobile Applications: While Python is not commonly used for creating mobile
applications, it can still be combined with frameworks like Kivy or BeeWare to create
cross-platform mobile applications.
o Software Development: Python is considered one of the best software-making
languages. Python is easily compatible with both from Small Scale to Large Scale
software.
o Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language
for artificial intelligence and machine learning because of the availability of powerful
libraries such as TensorFlow, Keras, and PyTorch.
o Web Applications: Python is commonly used in web development on the backend with
frameworks like Django and Flask and on the front end with tools like JavaScript and
HTML.
o Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing, networking, and parallel
processing.
o 3D CAD Applications: Python can be used for 3D computer-aided design (CAD)
applications through libraries such as Blender.
o Machine Learning: Python is widely used for machine learning due to its simplicity,
ease of use, and availability of powerful machine learning libraries.
o Computer Vision or Image Processing Applications: Python can be used for computer
vision and image processing applications through powerful libraries such as OpenCV and
Scikit-image.
o Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.
o Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like data analysis, machine learning, and
more.
o Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
o Testing: Python is used for writing automated tests, providing frameworks like unit tests
and pytest that help write test cases and generate reports.
o Gaming: Python has libraries like Pygame, which provide a platform for developing
games using Python.
o IoT: Python is used in IoT for developing scripts and applications for devices like
Raspberry Pi, Arduino, and others.
o Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
o DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
o Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
o Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
o Writing scripts: Python is used for writing utility scripts to automate tasks like file
operations, web scraping, and data processing.
Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.
Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our Python code. It converts the program into byte code, and any platform can use
that byte code.
It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.
9) GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by
line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language into
our code.
In Python, we don't need to specify the data-type of the variable. When we assign some value to
the variable, it automatically allocates the memory to the variable at run time. Suppose we are
assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.
Python programming language is being updated regularly with new features and supports. There
are lots of update in Python versions, started from 1994 to current release.
Usage of Python
Python is a general purpose, open source, high-level programming language and also provides
number of libraries and frameworks. Python has gained popularity because of its simplicity, easy
syntax and user-friendly environment. The usage of Python as follows.
o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing
In the next topic, we will discuss the Python Application, where we have defined Python's usage
in detail.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any application.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One
of Python web-framework named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface. Some popular GUI
libraries are given below.
o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
o PyQt or Pyside
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the
old generation of computers. Python can develop this kind of application very effectively. It is
famous for having REPL, which means the Read-Eval-Print Loop that makes it the most
suitable language for the command-line applications.
Python provides many free library or module which helps to build the command-line apps. The
necessary IO libraries are used to read and write. It helps to parse argument and create console
help text out-of-the-box. There are also advance libraries that can develop independent console
apps.
4) Software Development
Python is useful for the software development process. It works as a support language and can be
used to build control and management, testing, etc.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example
of a business application. This kind of application requires extensively, scalability and
readability, and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications. Python provides a Tryton platform which is used to develop the business
application.
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. The
few multimedia libraries are given below.
o Gstreamer
o Pyglet
o QT Phonon
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used
to develop the 3D representation of a part of a system. Python can create a 3D CAD application
by using the following functionalities.
o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements. Some libraries of image processing are given below.
o OpenCV
o Pillow
o SimpleITK
Python Variables
A Variable is a location that is named in order to store data while the program is being run.
In a programming language, Variables are words that are used to store values of any data
type.
In simple words, when you create a variable, it takes up some memory space based on the value and
the type you set to it. The Python interpreter allocates RAM to the variable based on its data type.
The variables’ values can be altered at any time during the program.
An Identifier is a term used in programming language in order to denote unique name given to these
variables.
Syntax
Note – In Python, we do not specify the data type for the variable. Python automatically
understands which data type is being used and allocates memory space accordingly.
1. A Variable’s name cannot begin with a number. Either an alphabet or the underscore
character should be used as the first character.
2. Variable names are case-sensitive and can include alphanumeric letters as well as the
underscore character.
3. Variable names cannot contain reserved terms.
4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables in Python.
There are few different methods to assign data elements to a Variable. The most common ones are
described below –
In this type, the data values are directly assigned to the Variables in the declaration statement.
Example
num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'
print(num)
print(numlist)
print(str)
Output
10
[1, 3, 5, 7, 9]
Hello World
Here, we have created 3 variables named as ‘num’, ‘numlist’, and ‘str’. We have assigned all the 3
variables an int value 10, a list of integers, and a string of characters respectively.
Data values assigned to the variables can be changed at any time. In Layman language, you can
think of a Variable as a bag to store items and these items can be replaced at any time.
Example
val = 50
print("Initial value:", val)
Output
Initial value: 50
Updated value: 100
In the above program, initially the value of Variable ‘val’ was 50. Later it was reassigned to a value
of 100.
3. Assign multiple values to multiple Variables
In Python, we can assign multiple values to multiple variables in the same declaration statement by
using the following method –
Example
print(name)
print(age)
print(city)
Output
David
27
New York
We can also assign a single value to multiple variables. Let us look at the below example to
understand this,
Example
a = b = 'Hello'
print('Value of a:', a)
print('Value of b:', b)
Output –
Value of a: Hello
Value of b: Hello
Python Constants
A Python Constant is a variable whose value cannot be changed throughout the program.
Certain values are fixed and are universally proven to be true. These values cannot be changed over
time. Such types of values are called as Constants. We can think of Python Constants as a bag full
of fruits, but these fruits cannot be removed or changed with other fruits.
Note – Unlike other programming languages, Python does not contain any constants. Instead,
Python provides us a Capitalized naming convention method. Any variable written in the Upper
case is considered as a Constant in Python.
Rules to be followed while declaring a Constant
1. Python Constants and variable names should contain a combination of lowercase (a-z) or
capital (A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT = 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized when
declaring a constant.
5. We should come up with a catchy name for the python constants. VALUE, for example,
makes more sense than V. It simplifies the coding process.
Assigning Values to Constants
Constants are typically declared and assigned in a module in Python. In this case, the module is a
new file containing variables, functions, and so on that is imported into the main file. Constants are
written in all capital letters with underscores separating the words within the module.
We create a separate file for declaring constants. We then use this file to import the constant module
in the main.py file from the other file.
Example
# main.py file
import constant as const
Output
Python Literals
The data which is being assigned to the variables are called as Literal.
In Python, Literals are defined as raw data which is being assigned to the variables or
constants.
Let us understand this by looking at a simple example,
Here, we have declared a variable ‘str’, and the value assigned to it ‘How are you, Sam?’ is a literal
of type string.
Python supports various different types of Literals. Let us look at each one of them in detail.
Numeric Literals
Numeric Literals are values assigned to the Variables or Constants which cannot be changed i.e.,
they are immutable. There are a total of 3 categories in Numeric Literals. They are – Integer, Float,
and Complex.
Example
# Int Numeric Literal
a = 30
print(a)
print(b)
print(c)
print(c.real, c.imag)
Output
30
40.67
(10+4j)
10.0 4.0
To generate real and imaginary components of complex numbers, we utilize real literal (c.real) and
imaginary literal (c.imag), respectively.
Long
Long literals were nothing but integers with unlimited length. From Python 2.2 and onwards, the
integers that used to overflow were automatically converted into long ints. Since Python 3.0, the
long literal has been dropped. What was the long data type in Python 2 is now the standard int
type in Python 3.
Long literals used to be represented with a suffix- l or L. The usage of L was strongly
recommended as l looked a lot like the digit 1.
Example
#usage long literal before it was depreciated
x=037467L
print(x)
Note– The code snippet was executed using Python 1.8. Output
Success #stdin
print(string)
print(multi_line)
print(char)
Output –
Hello Guys
Hey
There!!
Z
Boolean Literals
A Boolean Literal has either of the 2 values – True or False. Where True is considered as 1 and
False is considered as 0.
Example
boolean1 = (1 == True)
boolean2 = (1 == False)
num = 20
age = 20
x = True + 10
y = False + 50
print(boolean1)
print(boolean2)
print(num==age)
print('Value of x:', x)
print('Value of y:', y)
Output
True
False
True
Value of x: 11
Value of y: 50
True indicates a value of 1 in Python, while False represents a value of 0. Because 1 equals True,
the value of boolean1 is True. And as 1 does not equal False, the value of boolean2 is False.
Similarly, we can utilize True and False as values in numeric expressions.
Special Literals
Python provides a special kind of literal known as None. We use this type of Literal in order to
specify the field has not been created. It also denotes the end of a list in Python.
Example
soap = "Available"
handwash = None
def items(x):
if x == soap:
print('Soap:', soap)
else:
print('Soap:', handwash)
items(soap)
items(handwash)
Output
Soap: Available
Soap: None
In the above program, we define a function named ‘item’. Inside the ‘item’ function, when we set
the argument as ‘soap’ then, it displays ‘Available’. And, when the argument is ‘handwash’, it
displays ‘None’.
Literal Collections
In Python, there are 4 different types of Literal Collections. They represent more complicated and
complex data and assist Python scripts to be more extensible. Let us look at each one of them in
detail.
1. List Literals
The elements in a list are of many data types. The values in the List are surrounded by square
brackets ([]) and separated by commas (,). List values can be changed i.e., they are mutable.
Example –
print(cars)
print(student)
Output
2. Tuple Literals
Just like a List, a tuple is also a collection of various data types. It is surrounded by parentheses ‘(),’
and each element is separated by a comma (,). It is unchangeable (immutable).
Example –
num = (1, 2, 4, 5, 7, 8)
student = ('John', 20, 9876432113, 'Mumbai')
print(num)
print(student)
Output –
(1, 2, 4, 5, 7, 8)
('John', 20, 9876432113, 'Mumbai')
3. Dict Literals
The data is stored in the dictionary as a key-value pair. It is surrounded by curly braces ‘{}‘, and
each pair is separated by commas (,). A dictionary can hold various types of data. Dictionaries are
subject to change.
Example –
print(student.keys())
print(student.values()))
Output
Output
In the Python programming language, Constants are types of variables whose values cannot be
altered or changed after initialization. These values are universally proven to be true and they cannot
be changed over time. Generally, python constants are declared and initialized on different
modules/files.
Example
# constant.py file
PI = 3.14
# main.py file
import constant
print(‘Value of PI:’, constant.PI)
Output
Keywords in Python
Python Keywords are some predefined and reserved words in python that have special
meanings. Keywords are used to define the syntax of the coding. The keyword cannot be used
as an identifier, function, or variable name. All the keywords in python are written in
lowercase except True and False. There are 35 keywords in Python 3.11.
In python, there is an inbuilt keyword module that provides an iskeyword() function that can
be used to check whether a given string is a valid keyword or not. Furthermore we can check
the name of the keywords in Python by using the kwlist attribute of the keyword module.
Keywords Description
This is a logical operator which returns true if both the operands are true else
and
returns false.
This is also a logical operator which returns true if anyone operand is true else
or
returns false.
Keywords Description
This is again a logical operator it returns True if the operand is false else returns
not
false.
Else is used with if and elif conditional statements. The else block is executed if
else
the given condition is not true.
This function is used for debugging purposes. Usually used to check the
assert
correctness of code
Keywords Description
Finally is used with exceptions, a block of code that will be executed no matter if
finally
there is an exception or not.
in It’s used to check whether a value is present in a list, range, tuple, etc.
This is a special constant used to denote a null value or avoid. It’s important to
none
remember, 0, any empty container(e.g empty list) do not compute to None
The following code allows you to view the complete list of Python’s keywords.
This code imports the “keyword” module in Python and then prints a list of all the keywords in
Python using the “kwlist” attribute of the “keyword” module. The “kwlist” attribute is a list of
strings, where each string represents a keyword in Python. By printing this list, we can see all
the keywords that are reserved in Python and cannot be used as identifiers.
# code
import keyword
print(keyword.kwlist)
Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
‘num’ and ‘Num’ and ‘NUM’ are three different identifiers in python. It is a good
programming practice to give meaningful names to identifiers to make the code
understandable.
We can also use the Python string isidentifier() method to check whether a string is a valid
identifier or not.
Rules for Naming Python Identifiers
It cannot be a reserved python keyword.
It should not contain white space.
It can be a combination of A-Z, a-z, 0-9, or underscore.
It should start with an alphabet character or an underscore ( _ ).
It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
var1
_var1
_1_var
var_1
Invalid Identifiers
!var1
1var
1_var
var#1
var 1
Keywords in Python are predefined words that have a special meaning to the interpreter. They
are reserved words that are used to perform a specific task in Python programming.
Identifiers in Python are names given to different parts of a Python program like variables,
functions, classes, etc. They are user-defined and the users must follow a set of rules to define
them in a python program.
A Keyword in Python is a predefined reserved word that is meaningful to the interpreter and
performs a specific task. Whereas, an identifier is a user-defined word given to different parts
of python programming. An identifier can be a name given to a variable, function or a class.
Python Operators
Operators are special symbols that perform operations on variables and values. Operators allow
us to perform various computations, comparisons, and manipulations on data in a programming
language. They are a fundamental part of any programming language and play a crucial role in
writing expressions and statements to achieve specific tasks.
For example,
print(5 + 6) # 11
Run Code
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Special Operators
+ Addition 5+2=7
Subtraction 4-2=2
* Multiplication 2*3=6
Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
Example
** 1: Arithmetic Operators in Python
Power 4 ** 2 = 16
a=7
b=2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
+ to add a and b
- t subtract b from a
* multiply a and b
/ t divide a by b
// to floor divide a by b
% to get the remainder
** to get a to the power b
# assign 5 to x
var x = 5
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
# assign 5 to b
b=5
print(a)
# Output: 15
<
b=2
# equal to operator
print('a == b =', a == b)
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Note: Comparison operators are used in decision-making and loops. We'll discuss more of the
comparison operator and decision-making in later tutorials.
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is True.
Operator Example Meaning
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
Logical NOT:
not not a
True if the operand is False and vice-versa.
Example 4: Logical Operators
# logical AND
print(True and True) # True
print(True and False) # False
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the same x is not
is not
object) True
Output
True
True
True
False
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Python Data Types are used to define the type of a variable. It defines what type of data we are
going to store in a variable. 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.
Every value has a datatype, and variables can hold values. Python is a powerfully composed
language; consequently, we don't have to characterize the sort of variable while announcing it.
The interpreter binds the value implicitly to its type.
a=5
We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data types.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can contain a variety of values. On the other hand, a person's id must be stored as an
integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk about every single
one of them exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a
place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so
on. An integer can be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like 2.14j,
2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string can
be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities and
administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition
operator.
Example - 1
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put
away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
Example:
Output:
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
Example:
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key,
like an associative array or a hash table. Value is any Python object, while the key can hold any
primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Output:
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is not zero.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the curly
braces and separated by a comma to create the set or the built-in function set() is used to create
the set. It can contain different kinds of values.
Output:
In Python, we use the input() function to take input from the user. Whatever you enter as
input, the input function converts it into a string. If you enter an integer value still input()
function converts it into a string.
Example:
Python3
In this example, we are using the Python input() function which takes input from the user and
prints it.
# Output
print(string)
Output:
geeksforgeeks
User Input in Python
In this example, we are taking input from the user with a prompt and printing it.
# Output
print("Hello", name)
Output:
Enter your name:ankit rai
Hello ankit rai
In this example, we are using the Python input() function which takes input from the user
in string format converting it into an integer adding 1 to the integer, and printing it.
Python3
# Output
print(add)
Output:
Enter a number:15
16
In this example, we are using the Python input() function which takes input from the user in
string format converts it into float adds 1 to the float, and prints it.
Python3
# Taking input from the user as float
# output
print(add)
Output:
Enter number 5
6.0
In this example, we are taking input from the user in string format converting it into a list, and
printing it.
Python3
# output
print(li)
Output:
Enter number 12345
['1', '2', '3', '4', '5']
Take User Input for Tuples and Sets
In this example, we are taking input from the user in string format converting it into a tuple,
and printing it.
Python3
# output
print(num)
Output:
Enter number 123
('1', '2', '3')
In this example, we are taking the words separated by space and we make a dictionary of the
word as key with their length as value.
Python3
words_str = input("Enter a list of words, separated by spaces: ")
words = {word: len(word) for word in words_str.split()}
print(words)
Output :
Enter a list of words, separated by spaces: geeks for geeks
{'geeks': 5, 'for': 3}
Output Statement in Python:
Python print() function prints the message to the screen or any other standard output device.
Example
In this example, we have created three variables integer, string and float and we are printing all
the variables with print() function in Python.
Python3
name = "John"
age = 30
print("Name:", name)
print("Age:", age)
Output
Name: John
Age: 30
Python print() Function Syntax
Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s): Any value, and as many as you like. Will be converted to a string before
printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more
than one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered
(False). Default: False
Return Type: It returns output to the screen.
Though it is not necessary to pass arguments in the print() function, it requires an empty
parenthesis at the end that tells Python to execute the function rather than calling it by name.
Now, let’s explore the optional arguments that can be used with the print() function.
Output :
Hello, my name is Alice and I am 25 years old.
Python print() Function with Examples
Python String Literals
String literals in Python’s print statement are primarily used to format or design how a specific
string appears when printed using the print() function.
\n: This string literal is used to add a new blank line while printing a statement.
“”: An empty quote (“”) is used to print an empty line.
Example
This code uses \n to print the data to the new line.
Python3
print("GeeksforGeeks \n is best for DSA Content.")
Output
GeeksforGeeks
is best for DSA Content.
Python “end” parameter in print()
The end keyword is used to specify the content that is to be printed at the end of the execution
of the print() function. By default, it is set to “\n”, which leads to the change of line after the
execution of print() statement.
Example
In this example, we are using print() with end and without end parameters.
Python3
# This print() function ends with "**" as set in the end argument.
print ("GeeksForGeeks is the best platform for DSA content", end= "**")
print("Welcome to GFG")
Output
GeeksForGeeks is the best platform for DSA content
GeeksForGeeks is the best platform for DSA content**Welcome to GFG
flush parameter in Python with print() function
The I/Os in Python are generally buffered, meaning they are used in chunks. This is where
flush comes in as it helps users to decide if they need the written content to be buffered or not.
By default, it is set to false. If it is set to true, the output will be written as a sequence of
characters one after the other. This process is slow simply because it is easier to write in
chunks rather than writing one character at a time. To understand the use case of the flush
argument in the print() function, let’s take an example.
Example
Imagine you are building a countdown timer, which appends the remaining time to the same
line every second. It would look something like below:
3>>>2>>>1>>>Start
The initial code for this would look something like below as follows:
Python3
import time
count_seconds = 3
if i > 0:
print(i, end='>>>')
time.sleep(1)
else:
print('Start')
So, the above code adds text without a trailing newline and then sleeps for one second after
each text addition. At the end of the countdown, it prints Start and terminates the line. If you
run the code as it is, it waits for 3 seconds and abruptly prints the entire text at once. This is a
waste of 3 seconds caused due to buffering of the text chunk as shown below :
Though buffering serves a purpose, it can result in undesired effects as shown above. To
counter the same issue, the flush argument is used with the print() function. Now, set the flush
argument as true and again see the results.
Python3
import time
count_seconds = 3
for i in reversed(range(count_seconds + 1)):
if i > 0:
print(i, end='>>>', flush = True)
time.sleep(1)
else:
print('Start')
Output
Python print() flush argument
Python “sep” parameter in print()
The print() function can accept any number of positional arguments. To separate these
positional arguments, the keyword argument “sep” is used.
Note: As sep, end, flush, and file are keyword arguments their position does not change the
result of the code.
Example
This code is showing that how can we use the sep argument for multiple variables.
Python3
a=12
b=12
c=2022
print(a,b,c,sep="-")
Output :
12-12-2022
Example
Positional arguments cannot appear after keyword arguments. In the below
example 10, 20 and 30 are positional arguments where sep=’ – ‘ is a keyword argument.
Python3
print(10, 20, sep=' - ', 30)
Output :
File "0b97e8c5-bacf-4e89-9ea3-c5510b916cdb.py", line 1
print(10, 20, sep=' - ', 30)
^
SyntaxError: positional argument follows keyword argument
File Argument in Python print()
Contrary to popular belief, the print() function doesn’t convert messages into text on the
screen. These are done by lower-level layers of code, that can read data(message) in bytes. The
print() function is an interface over these layers, that delegates the actual printing to a stream
or file-like object. By default, the print() function is bound to sys.stdout through the file
argument.
With IO Module
This code creates a dummy file using the io module in Python. It then adds a message “Hello
Geeks!!” to the file using the print() function and specifies the file parameter as the dummy
file.
Python3
import io
Output
Hello Geeks!!
Writing to a File with Python’s print() Function
This code is writing the data in the print() function to the text file.
Python3
print('Welcome to GeeksforGeeks Python world.!!', file=open('Testfile.txt', 'w'))
Output
There are several ways to deliver the output of a program. In Python, we use the print() function
to output data to the screen. Sometimes we might want to take input from the user. We can do so
by using the input() function. Python takes all the input as a string input by default. To convert it
to any other data type, we have to convert the input explicitly.
Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully.
There are three types of comments in Python:
Single line Comments
Multiline Comments
Docstring Comments
Python3
# sample comment
name = "geeksforgeeks"
print(name)
Output:
geeksforgeeks
Types of Comments in Python
print("GeeksforGeeks")
Output
GeeksforGeeks
Multi-Line Comments in Python
Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.
Multiline comments using multiple hashtags (#)
We can multiple hashtags (#) to write multiline comments in Python. Each and every line will
be considered as a single-line comment.
Python3
print("Multiline comments")
Output
Multiline comments
Python ignores the string literals that are not assigned to a variable so we can use these string
literals as Python Comments.
Single-line comments using string literals
On executing the above code we can see that there will not be any output so we use the strings
with triple quotes(“””) as multiline comments.
Python3
print("Multiline comments")
Output
Multiline comments
Docstring in Python
Python docstring is the string literals with triple quotes that are appeared right after the
function. It is used to associate documentation that has been written with Python modules,
functions, classes, and methods. It is added right below the functions, modules, or classes to
describe what they do. In Python, the docstring is then made available via the doc
attribute.
Example:
Python3
return a*b
print(multiply. doc )
Output:
Multiplies the value of a and b
Advantages of comments in Python
Comments are generally used for the following purposes:
Code Readability
Explanation of the code or Metadata of the project
Prevent execution of code
To include resources
Expression in Python
A combination of operands and operators is called an expression. The expression in Python
produces some value or result after being interpreted by the Python interpreter. An expression in
Python is a combination of operators and operands.
An example of expression can be : = +10x=x+10. In this expression, the first 1010 is added
to the variable x. After the addition is performed, the result is assigned to the variable x.
Example :
x = 25 # a statement
x = x + 10 # an expression
print(x)
Output :
35
Example :
a = 25 # a statement
print(a) # a statement
Output :
25
An expression in Python can contain identifiers, operators, and operands. Let us briefly
discuss them.
An identifier is a name that is used to define and identify a class, variable, or function in Python.
An operand is an object that is operated on. On the other hand, an operator is a special symbol
that performs the arithmetic or logical computations on the operands. There are many types of
operators in Python, some of them are :
+ : add (plus).
- : subtract (minus).
x : multiply.
/ : divide.
** : power.
% : modulo.
<< : left shift.
>> : right shift.
& : bit-wise AND.
| : bit-wise OR.
^ : bit-wise XOR.
~ : bit-wise invert.
< : less than.
> : greater than.
<= : less than or equal to.
>= : greater than or equal to.
== : equal to.
!= : not equal to.
and : boolean AND.
or : boolean OR.
not : boolean NOT.
The expression in Python can be considered as a logical line of code that is evaluated to obtain
some result. If there are various operators in an expression then the operators are resolved based
on their precedence. We have various types of expression in Python, refer to the next section for
a more detailed explanation of the types of expression in Python.
We have various types of expression in Python, let us discuss them along with their respective
examples.
1. Constant Expressions
A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a
value that cannot be changed after its initialization.
Example :
x = 10 + 15
Output :
- x- y Subtraction of y from x.
/ x/ y Division of x and y.
Example :
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
Output :
3. Integral Expressions
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)
Output :
4. Floating Expressions
A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the integer number into a floating-point number or vice versa for
summation.
result = float(x) + y
Output :
(i.e. >,<,>=,<=)(i.e.>,<,>=,<=).
A relational operator produces a boolean result so they are also known as Boolean Expressions.
For example :
10+15>2010+15>20
In this example, first, the arithmetic expressions (i.e. 10+1510+15 and 2020) are evaluated, and
then the results are used for further comparison.
Example :
a = 25
b = 14
c = 48
d = 45
# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)
Output :
As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical
expressions in Python, let us discuss them briefly.
and x and y The expression return True if both x and y are true, else it returns False.
Note :
In the table specified above, x and y can be values or another expression as well.
Example :
x = (10 == 9)
y = (7 > 5)
and_result = x and y
or_result = x or y
not_x = not x
Output :
The expression in which the operation or computation is performed at the bit level is known as
a bitwise expression in Python. The bitwise expression contains the bitwise operators.
Example :
x = 25
left_shift = x << 1
right_shift = x >> 1
As the name suggests, a combination expression can contain a single or multiple expressions
which result in an integer or boolean value depending upon the expressions involved.
Example :
x = 25
y = 35
result = x + (y << 1)
Output :
Result obtained: 95
Whenever there are multiple expressions involved then the expressions are resolved based on
their precedence or priority. Let us learn about the precedence of various operators in the
following section.
The operator precedence is used to define the operator's priority i.e. which operator will be
executed first. The operator precedence is similar to the BODMAS rule that we learned in
mathematics. Refer to the list specified below for operator precedence.
1. ()[]{} Parenthesis
2. ** Exponentiation
8. ^ Bitwise XOR
x = 12
y = 14
z = 16
result_1 = x + y * z
print("Result of 'x + y + z' is: ", result_1)
result_2 = (x + y) * z
print("Result of '(x + y) * z' is: ", result_2)
result_3 = x + (y * z)
print("Result of 'x + (y * z)' is: ", result_3)
Output :
We have earlier discussed statement expression in Python, let us learn the differences between
them.
A statement in Python is used for creating The expression in Python produces some value or result
variables or for displaying values. after being interpreted by the Python interpreter.
The execution of a statement changes the The expression evaluation does not result in any state
state of the variable. change.
Summary
The spaces at the beginning of a code line are referred to as indentation. Whereas
indentation in code is only for readability in other programming languages, it is critical in
Python. Python employs indentation to denote a block of code. Indentation is an important
concept in the Python programming language that is used to group statements that belong to the
same block of code. In Python, a block of code is a group of statements that are executed
together as a unit. Indentation in python is used to define the beginning and end of these blocks.
In Python, indentation is the leading whitespace (spaces or/and tabs) before any statement. The
importance of indentation in Python stems from the fact that it serves a purpose other than code
readability. Python treats statements with the same indentation level (statements preceded by the
same number of whitespaces) as a single code block. So, whereas in languages such as C, C++,
and others, a block of code is represented by curly braces, a block in Python is a group of
statements with the same Indentation level, i.e. the same number of leading whitespaces.
Python’s default indentation spaces are four spaces. The number of spaces, however, is
entirely up to the user. However, a minimum of one space is required to indent a
statement.
To indent in Python, whitespaces are preferred over tabs. Also, use either whitespace or
tabs to indent; mixing tabs and whitespaces in indentation can result in incorrect
indentation errors.
Example 1
Below we have code implementation and explanation
python
else:
Output
Logging on to prepbytes...
All set !
Explanation:
In the above python program, we have Print(‘Logging on to prepbytes…’) and print(‘retype the
URL.’) are two distinct code blocks. In our example, if-statement, the two blocks of code are
both indented four spaces. Because the final print (‘All set!’) is not indented, it is not part of the
else block.
Example 2
Below we have code implementation and explanation
python
Output
1
2
Explanation: In Python, you must indent each line of code by the same amount of whitespace to
indicate a block of code. The while loop’s two lines of code are both indented four spaces. It is
required to indicate which code block a statement belongs to. For instance, j=1 and while(j=5):
are not indented and thus do not fall within the Python while block. Indentation is used to
structure Python code.
If we are writing a certain code of lines based on some logic to get the desired result, but,
meanwhile, we are following the above rules of indentation. The compiler will generate an
indentation error.
In the above figure, if we observe that it is mentioned how python recognises every block of
code.
As we will notice in this figure, the indentation of every block is the calculation of whitespaces
from the left corner to the statement began. Whenever the particular block of code starts, it will
follow the indentation. At first, it will maintain the proper whitespaces and tabs, whenever the
block starts and until it ends. If in the case inside that particular block includes a nested block, it
will assign whitespaces to it till that nested block ends.
In this way, in the python programming language the indentation of a block matches.
An indentation error occurs whenever there is no ending of the particular block, or the number of
whitespaces assigned for starting the code block is not the same. At the same time that blocks
ends, ultimately, an indentation error occurs.
Improved Readability: Indentation makes the code more readable by clearly indicating
which statements belong to which block of code. This makes it easier for other
developers to understand your code and makes it more maintainable.
Consistency: By requiring consistent indentation levels, Python ensures that the code
follows a consistent style, making it easier to read and understand.
Reduced Syntax: Python’s use of indentation reduces the amount of syntax required to
define blocks of code. This makes Python code shorter and easier to read than code
written in other languages.
Increased Efficiency: Python’s use of indentation simplifies the coding process and
allows developers to write code faster and with fewer errors.
Limited Flexibility: Python’s use of indentation can limit the flexibility of code
formatting, as all code blocks must follow a consistent indentation level. This can be
problematic in certain situations where code formatting needs to be adjusted for different
environments or requirements.
Difficulties with Copy and Paste: If code is copied and pasted from one editor to
another, the indentation levels may not be preserved. This can lead to errors in the code
and make it more difficult to debug.
Increased Learning Curve: The requirement for consistent indentation levels can
increase the learning curve for new Python programmers. This can make it more difficult
to get started with Python, especially for those who are used to other programming
languages that use different syntax to define blocks of code.
Maintenance Issues: In some cases, changes to the indentation levels can have
unintended consequences that may be difficult to diagnose and fix. This can make
maintenance more difficult and time-consuming.
There are points that one must remember while fixing the indentation error :
As we have seen earlier, indentation error occurs only due to the unmatched whitespaces and
tabs; hence, we need to fix all the whitespaces and tabs.
Python defines type conversion functions to directly convert one data type to another which is
useful in day-to-day and competitive programming. This article is aimed at providing
information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
Let’s discuss them in detail.
Implicit Type Conversion
In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement. To get a more clear view of
the topic see the below examples.
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
As we can see the data type of ‘z’ got automatically changed to the “float” type while one
variable x is of integer type while the other variable y is of float type. The reason for the float
value not being converted into an integer instead is due to type promotion that allows
performing operations by converting data into a wider-sized data type without any loss of
information. This is a simple case of Implicit type conversion in python.
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the user as per
their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type. Various forms of explicit type
conversion are explained below:
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies
the base in which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-
point number.
Example
# Python code to demonstrate Type conversion
# using int(), float()
# initializing string
s = "10010"
# initializing integer
s = '4'
# initializing string
s = 'geeks'
Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.
Python3
# initializing integers
a=1
b=2
# initializing tuple
c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)
c = dict(tup)
print (c)
Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
12. chr(number): This function converts number to its corresponding ASCII character.
Python3
print(a)
print(b)
Output:
L
M