Python Unit-1
Python Unit-1
History of Python
Origin:: Python was developed in the late 1980s by Guido van Rossum,
Rossum a Dutch
programmer, while he was working at the Centrum Wiskunde & Info Informatica (CWI) in
the Netherlands.
Inspiration:: Guido van Rossum aimed to create a language with an emphasis on code
readability and simplicity, which was lacking in the languages at the time. He was
inspired by the ABC language
language, a teaching language he had previously worked on.
Purpose:: Python was designed as a successor to the ABC language, with improvements
in handling exceptions and interfacing with the Amoeba operating system.
Initial Release:: The first official version, Python 0.9.0,, was released in 1991.
Guido chose the name "Python" not after the snake but as a reference to the popular
British comedy show “Monty Python's Flying Circus.”
This influence led to Python's lighthearted naming conventions and its focus on
readability and enjoyment in programming.
Python 2.0: Released in October 2000, Python 2.0 brought significant advancements:
o List Comprehensions: Simplified syntax for creating lists.
o Garbage Collection: Added automatic memory management.
o Unicode Support: Expanded Python's ability to handle international character
sets.
Development Community: Python 2.0 was the first release developed collaboratively
by the open-source community, marking a shift in its development process.
Subsequent Updates: Many 2.x versions were released over the years, refining and
adding features, and Python 2.7 (2010) became the final release in the Python 2 series.
End of Support: Python 2.x support officially ended on January 1, 2020, urging users
to migrate to Python 3.
Python 3.0: Released in December 2008, Python 3 was a major revision aimed at
fixing fundamental design flaws:
o Enhanced Syntax and Readability: Emphasis on readability and reduced
ambiguity.
o Print Function: Replaced print as a statement with print() as a function.
o New Integer Division: Division of integers produces a float (5 / 2 = 2.5), while
// performs integer division.
o Unicode by Default: All strings are Unicode by default, making Python more
versatile with international languages.
o Standard Library Overhaul: Many modules were improved or rewritten for
better consistency and performance.
Backward Incompatibility: Python 3 was intentionally made incompatible with
Python 2 to eliminate legacy issues, though this posed a challenge for developers to
migrate their codebases.
Python 3.x Versions: Subsequent 3.x releases introduced features like async
programming, f-strings, type hinting, and data classes.
Python 1.0 (1994): Introduced core features such as functions, modules, and
exceptions.
Python 2.0 (2000): Introduced garbage collection, list comprehensions, and the first
community-driven development approach.
Python 2.7 (2010): Last version of Python 2, widely used until end of support in 2020.
Python 3.0 (2008): Major rewrite with improved consistency, Unicode support, and
clean syntax.
Python 3.5 (2015): Added async and await for asynchronous programming.
Python 3.6 (2016): Introduced f-strings for efficient string formatting.
Python 3.9 (2020): End of life for Python 2.x and enhanced modern features.
Popularity: Python is one of the most popular programming languages in the world,
thanks to its readability, community support, and versatility in web development, data
science, AI, automation, and more.
Python 3.x Continuity: Python's current and future versions continue in the 3.x series,
focusing on language stability, performance improvements, and adding capabilities that
meet modern needs (e.g., data science, machine learning).
PEP 563 and Beyond: The future of Python is community-driven, with the PEP process
continuing to shape its evolution. Recent PEPs focus on performance enhancements,
syntax improvements, and expanding support for typing and async programming.
Features of Python
Line-by-Line Execution: Python code is executed one line at a time, making it easier to
debug errors as they appear.
No Compilation: Unlike compiled languages (e.g., C, Java), Python does not require
compilation before running. This reduces development time.
REPL: Python provides an interactive shell (REPL - Read-Eval-Print Loop) where users
can execute Python statements line by line.
No Type Declarations: Variables do not require explicit type declarations; types are
assigned at runtime based on the variable’s value.
Flexibility: This feature allows programmers to write code faster without worrying
about declaring data types.
Reduced Code Complexity: Dynamic typing reduces verbosity and complexity, making
the code concise.
4. Object-Oriented Language
Built-In Modules: Python's standard library includes modules for various purposes
like file I/O, system calls, sockets, and more.
Libraries for All Needs: Python’s standard library supports web development, data
manipulation, math operations, regular expressions, and more.
Reduced Need for External Packages: This library reduces the need for installing
external packages, as it covers many common programming requirements.
6. Platform Independent
7. Open Source
Free to Use: Python is open-source, meaning it’s freely available for anyone to
download, use, and modify.
Community Contributions: Python’s development is driven by a global community of
contributors who suggest enhancements, contribute code, and participate in
discussions.
Python Software Foundation (PSF): The PSF manages Python's development, and the
open-source model ensures continual improvement.
9. High-Level Language
10. Portability
Global Community: Python boasts a large and active global community, offering
support through forums, tutorials, and resources.
Comprehensive Documentation: Python.org provides extensive documentation for all
Python versions, helping users to understand Python and its libraries.
Third-Party Libraries and Packages: Python’s community maintains a vast repository
of third-party libraries and packages, covering a broad range of functionalities.
Tkinter: Python includes Tkinter, a library for building simple graphical user
interfaces.
Other GUI Frameworks: External libraries like PyQt, Kivy, and wxPython allow for
more advanced GUI development.
Cross-Platform GUIs: These libraries are cross-platform, enabling GUI applications to
run on different operating systems.
Database Support: Python offers support for databases like MySQL, PostgreSQL,
SQLite, MongoDB, and others.
Libraries and Modules: Libraries such as sqlite3, SQLAlchemy, and PyMySQL enable
database connectivity.
Data-Driven Applications: These integrations make Python suitable for data-driven
applications and back-end development.
Scientific and Numeric Computing: Libraries like NumPy, SciPy, and Pandas enable
advanced mathematical and statistical computations.
Data Science and Machine Learning: Libraries like TensorFlow, Keras, and scikit-
learn support machine learning and data science.
Web Development: Frameworks like Django and Flask simplify web development.
Automation and Scripting
Scripting: Modules like os, sys, and subprocess make Python ideal for
scripting and automation tasks.
Simplicity of Deployment
Deployment:: Python applications can be packaged easily, which
simplifies deployment.
API Integration:: Python’s simplicity allows easy integration with various APIs,
especially for web development and data science.
Interoperability with Other Languages
Languages:: Python is compatible with languages like
Java, C, and C++, facilitating the integration of Python with other systems.
literal
A literal in Python is a syntax that is used to completely express a fixed value of a specific
data type. Literals are constants that are self-explanatory and don’t need to be computed or
evaluated. They are used to provide variable values or to directly utilize them in expressions.
Generally, literals are a notation for representing a fixed value in source
urce code. They can also
be defined as raw values or data given in variables or constants. In this article, we will
explore the different types of literals in Python, along with examples
mples to demonstrate their
usage.
Literals in Python
Table of Content
Python String Literals
Python Character Literal
Python Numeric Literal
Python Boolean Literal
Python Literal Collections
Python Special Literal
Types of Literals in Python
Python supports various types of literals, such as numeric literals, string literals, Boolean
literals, and more. Let’s explore different types of literals in Python with examples:
Python String Literals
A string is literal and can be created by writing a text(a group of Characters ) surrounded by
a single(”), double(“), or triple quotes. We can write multi-line strings or display them in the
desired way by using triple quotes. Here geekforgeeks is a string literal that is assigned to a
variable(s). Here is an example of a Python string literal.
Python
# in single quote
s = 'geekforgeeks'
# in double quotes
t = "geekforgeeks"
# multi-line String
m = '''geek
for
geeks'''
print(s)
print(t)
print(m)
Output
geekforgeeks
geekforgeeks
geek
for
geeks
Python Character Literal
It is also a type of Python string literal where a single character is surrounded by single or
double quotes.
Python
print(v)
print(w)
Output
n
a
Python Numeric Literal
They are immutable and there are three types of numeric literal:
Integer
Float
Complex
Integer
Both positive and negative numbers including 0. There should not be any fractional part. In
this example, We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different
variables. Here, ‘a‘ is a binary literal, ‘b’ is a decimal literal, ‘c‘ is an octal literal, and ‘d‘ is a
hexadecimal literal. But on using the print function to display a value or to get the output
they were converted into decimal.
Python
# integer literal
# Binary Literals
a = 0b10100
# Decimal Literal
b = 50
# Octal Literal
c = 0o320
# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)
Output
20 50 208 299
Float
These are real numbers having both integer and fractional parts. In this example, 24.8 and
45.0 are floating-point literals because both 24.8 and 45.0 are floating-point numbers.
Python
# Float Literal
e = 24.8
f = 45.0
print(e, f)
Output
24.8 45.0
Complex
The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b‘ is the complex
part. Numeric literal [ Complex ]
Python
z = 7 + 5j
Output
(7+5j) 7j
Python Boolean Literal
There are only two Boolean literals in Python. They are true and false. In
Python, True represents the value as 1, and False represents the value as 0. In this example
‘a‘ is True and ‘b‘ is False because 1 is equal to True.
Python
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7
print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
Output
a is True
b is False
c: 4
d: 7
Python Literal Collections
Python provides four different types of literal collections:
1. List literals
2. Tuple literals
3. Dict literals
4. Set literals
List literal
The list contains items of different data types. The values stored in the List are separated by
a comma (,) and enclosed within square brackets([]). We can store different types of data in
a List. Lists are mutable.
Python
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)
Output
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
Tuple literal
A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and each
element is separated by the comma(,). It is immutable.
Python
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)
print(odd_number)
Output
(2, 4, 6, 8)
(1, 3, 5, 7)
Dictionary literal
The dictionary stores the data in the key-value pair. It is enclosed by curly braces ‘{}‘ and
each pair is separated by the commas(,). We can store different types of data in a dictionary.
Dictionaries are mutable.
Python
print(alphabets)
print(information)
Output
print(vowels)
print(fruits)
Output
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.
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
Copy Code
Copy Code
# main.py file
import constant as const
print(counter)
print(miles)
print(name)
Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles, and name variables,
respectively. When running the above Python program, this produces the following result −
100
1000.0
Zara Ali
Variable Types in Python
Identifiers
Identifier is a name used to identify a variable, function, class, module, etc. The identifier is a
combination of character digits and underscore. The identifier should start with a character or
Underscore then use a digit. The characters are A-Z or a-z, an Underscore(_), and digit (0-9).
We should not use special character (! #, @, $, %,) in identifiers.
Keywords
Keywords are predefined, reserved words used in Python programming that have special
meanings to the compiler.
We cannot use a keyword as a variable name, function name, or any other identifier. They are
used to define the syntax and structure of the Python language.
All the keywords except True, False and None are in lowercase and they must be
Python Keywords
Here is the list of some reserved keywords in Python that cannot be used as identifiers.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not await
class form or async
continue global pass
Keyword Description
or A logical operator
Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything is an
object in Python programming, data types are actually classes and variables are instance
(object) of these classes.
Following are the standard or built-in data type of Pytho
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value
can be integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
# Python program to
# demonstrate numeric value
a =5
print("Type of a: ", type(a))
b =5.0
print("\nType of b: ", type(b))
c =2+4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
# Creating a String
# with single Quotes
String1 ='Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 ="I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 ='''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
Python3
String1 ="GeeksForGeeks"
print("Initial String: ")
print(String1)
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Python3
# Creating a List
List=[]
print("Initial blank List: ")
print(List)
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Accessing elements of List
In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. In Python, negative sequence indexes represent positions from the
end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to
just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second-last item, etc.
# Python program to demonstrate
# accessing of element from list
Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference
between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of the data sequence. Tuples can contain any
number of elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a
tuple.
# Python program to demonstrate
# creation of Set
# Creating a Tuple
# with nested tuples
Tuple1 =(0, 1, 2, 3)
Tuple2 =('python', 'geek')
Tuple3 =(Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
Accessing elements of Tuple
In order to access the tuple items refer to the index number. Use the index operator [ ] to
access an item in a tuple. The index must be an integer. Nested tuples are accessed using
nested indexing.
Python3
# Python program to
# demonstrate accessing tuple
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
Set
In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by ‘comma’. Type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.
# Creating a Set
set1 =set()
print("Initial blank Set: ")
print(set1)
# Creating a set
set1 =set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)
Elements of set:
Geeks For
True
# Creating a Dictionary
# with Integer Keys
Dict={1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict={'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict=dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict=dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
# Creating a Dictionary
Dict={1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Addition
c =a +b
print("Addition:",c)
d =9
e =6
# Subtraction
f =d -e
print("Subtraction:",f)
g =8
h =2
# Division
i =g //h
print("Division:",i)
j =3
k =5
# Multiplication
l =j *k
print("Multiplication:",l)
m =25
n =5
# Modulus
o =m %n
print("Modulus:",o)
p =6
q =2
# Exponent
r =p **q
print("Exponent:",r)
Output:
Addition: 11
Subtraction: 3
Division: 4
Multiplication: 15
Modulus: 0
Exponent: 36
Float type
This is a real number with floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be appended
to specify scientific notation. . Some examples of numbers that are represented as floats are
0.5 and -7.823457.
They can be created directly by entering a number with a decimal point, or by using
operations such as division on integers. Extra zeros present at the number’s end are ignored
automatically.
Example 1: Creating float and checking type
num =3/4
num =6*7.0
print(type(num))
Output:
<class 'float'>
Example 2: Performing arithmetic Operations on float type
Python3
a =5.5
b =3.2
# Addition
c =a +b
print("Addition:", c)
# Subtraction
c =a-b
print("Subtraction:", c)
# Division
c =a/b
print("Division:", c)
# Multiplication
c =a*b
print("Multiplication:", c)
Output
Addition: 8.7
Subtraction: 2.3
Division: 1.71875
Multiplication: 17.6
Note: The accuracy of a floating-point number is only up to 15 decimal places, the 16th place
can be inaccurate.
Complex type
A complex number is a number that consists of the real and imaginary parts. For example, 2
+ 3j is a complex number where 2 is the real component, and 3 multiplied by j is an
imaginary part.
Example 1: Creating Complex and checking type
Python3
num =6+9j
print(type(num))
Output:
<class 'complex'>
Example 2: Performing arithmetic operations on complex type
a =1+5j
b =2+3j
# Addition
c =a +b
print("Addition:",c)
d =1+5j
e =2-3j
# Subtraction
f =d -e
print("Subtraction:",f)
g =1+5j
h =2+3j
# Division
i =g /h
print("Division:",i)
j =1+5j
k =2+3j
# Multiplication
l =j *k
print("Multiplication:",l)
Output:
Addition: (3+8j)
Subtraction: (-1+8j)
Division: (1.307692307692308+0.5384615384615384j)
Multiplication: (-13+13j)
Type Conversion between numbers
We can convert one number into the other form by two methods:
Using Arithmetic Operations: We can use operations like addition, subtraction to
change the type of number implicitly(automatically), if one of the operands is float. This
method is not working for complex numbers.
Example: Type conversion using arithmetic operations
a =1.6
b =5
c =a +b
print(c)
Output:
6.6
Using built-in functions: We can also use built-in functions like int(), float() and
complex() to convert into different types explicitly.
Example: Type conversion using built-in functions
Python3
a =2
print(float(a))
b =5.6
print(int(b))
c ='3'
print(type(int(c)))
d ='5.6'
print(type(float(c)))
e =5
print(complex(e))
f =6.5
print(complex(f))
Output:
2.0
5
<class 'int'>
<class 'float'>
(5+0j)
(6.5+0j)
When we convert float to int, the decimal part is truncated.
Note:
1. We can’t convert a complex data type number into int data type and float data type
numbers.
2. We can’t apply complex built-in functions on strings.
Decimal Numbers in Python
Arithmetic operations on the floating number can give some unexpected results. Let’s
consider a case where we want to add 1.1 to 2.2. You all must be wondering that the result of
this operation should be 3.3 but let’s see the output given by Python.
Example:
a =1.1
b =2.2
c =a+b
print(c)
Output:
3.3000000000000003
You can the result is unexpected. Let’s consider another case where we will subtract 1.2 and
1.0. Again we will expect the result as 0.2, but let’s see the output given by Python.
Example:
Python3
a =1.2
b =1.0
c =a-b
print(c)
Output:
0.19999999999999996
Example:
Python3
importdecimal
a =decimal.Decimal('1.1')
b =decimal.Decimal('2.2')
c =a+b
print(c)
Output
3.3
Random Numbers in Python
Python provides a random module to generate pseudo-random numbers. This module can
create random numbers, select a random element from a sequence in Python, etc.
Example 1: Creating random value
Python3
importrandom
print(random.random())
Output
0.9867200671824407
Example 2: Selecting random element from string or list
Python3
importrandom
s ='geeksforgeeks'
L =[1, 2,3, 5, 6, 7, 7, 8, 0]
print(random.choice(s))
print(random.choice(L))
Output
f
0
Note: For more information about random numbers, refer to our Random Number tutorial
Python Mathematics
The math module of Python helps to carry different mathematical operations trigonometry,
statistics, probability, logarithms, etc.
Example:
Python3
# importing "math" for mathematical operations
importmath
a =3.5
Boolean
Python boolean type is one of the built-in data types provided by Python, which represents
one of the two values i.e. True or False. Generally, it is used to represent the truth values of
the expressions. For example, 1==1 is True whereas 2<1 is False.
Python Boolean Type
The boolean value can be of two types only i.e. either True or False. The output <class
‘bool’> indicates the variable is a boolean data type.
Python3
a =True
type(a)
b =False
type(b)
Output:
<class 'bool'>
<class 'bool'>
Evaluate Variables and Expressions
We can evaluate values and variables using the Python bool() function. This method is used
to return or convert a value to a Boolean value i.e., True or False, using the standard truth
testing procedure.
Syntax:
bool([x])
# Returns False as x is 0
x =0.0
print(bool(x))
Python3
# Declaring variables
a =10
b =20
# Comparing variables
print(a ==b)
Output:
False
Integers and Floats as Booleans
Numbers can be used as bool values by using Python’s built-in bool() method. Any integer,
floating-point number, or complex number having zero as a value is considered as False,
while if they are having value as any positive or negative number then it is considered as
True.
Python3
var1 =0
print(bool(var1))
var2 =1
print(bool(var2))
var3 =-9.7
print(bool(var3))
Output:
False
True
True
Boolean Operators
Boolean Operations are simple arithmetic of True and False values. These values can be
manipulated by the use of boolean operators which include AND, Or, and NOT. Common
boolean operations are –
or
and
not
== (equivalent)
!= (not equivalent)
Boolean OR Operator
The Boolean or operator returns True if any one of the inputs is True else returns False.
A B A or B
True True True
True False True
False True True
False False False
Python3
# Python program to demonstrate
# or operator
a =1
b =2
c =4
The Boolean and operator returns False if any one of the inputs is False else returns True.
A B A and B
True True True
True False False
False True False
False False False
Python3
# Python program to demonstrate
# and operator
a =0
b =2
c =4
The Boolean Not operator only require one argument and returns the negation of the
argument i.e. returns the True for False and False for True.
A Not A
True False
False True
Python3
# Python program to demonstrate
# not operator
a =0
ifnota:
print("Boolean value of a is False")
Output
Boolean value of a is False
Both the operators are used to compared two results. == (equivalent operator returns True
if two results are equal and != (not equivalent operator returns True if the two results are
not same.
Python3
# Python program to demonstrate
# equivalent an not equivalent
# operator
a =0
b =1
ifa ==0:
print(True)
ifa ==b:
print(True)
ifa !=b:
print(True)
Output
True
True
is Operator
The is keyword is used to test whether two variables belong to the same object. The test will
return True if the two objects are the same else it will return False even if the two objects
are 100% equal.
Python3
# Python program to demonstrate
# is keyword
x =10
y =10
ifx isy:
print(True)
else:
print(False)
print(x isy)
Output
True
False
in Operator
in operator checks for the membership i.e. checks if the value is present in a list, tuple, range,
string, etc.
Example: in Operator
Python3
# Python program to demonstrate
# in keyword
# Create a list
animals =["dog", "lion", "cat"]
Output Statements
Python print() function prints the message to the screen or any other standard output
device. In this article, we will cover about print() function in Python as well as it’s various
operations.
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.
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.
Python
name = "John"
age = 30
print("Name:", name)
print("Age:", age)
Output
Name: John
Age: 30
How print() works in Python?
You can pass variables, strings, numbers, or other data types as one or more parameters
when using the print() function. Then, these parameters are represented as strings by their
respective str() functions. To create a single output string, the transformed strings are
concatenated with spaces between them.
In this code, we are passing two parameters name and age to the print function.
Python
name = "Alice"
age = 25
Output
Output
GeeksforGeeks
is best for DSA Content.
# 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
Output
Output formatting
In this example, we are formatting our output to make it look more attractive by
using str.format() function.
Python
a,b,=10,1000
print('The value of a is {} and b is {}'.format(a,b))
Output
Python input() function is used to take user input. By default, it returns the user input in
form of a string.
input() Function
Syntax:
input(prompt)
prompt [optional]: any string value to display as input message
Ex: input(“What is your name? “)
Returns: Return a string value as input by the user.
By default input() function helps in taking user input as string.
If any user wants to take input as int or float, we just need to typecast it.
Refer to all datatypes and examples from here.
Python input() Function Example
Python
# printing
print("The sum of the two given numbers is {} ".format(addition))
Output:
Similarly, we can use float() to take two float numbers. Let’s see one more example of how to
take lists as input
Example 3: Taking Two lists as input and appending them
Taking user input as a string and splitting on each character using list() to convert into list of
characters.
Python
# printing list1
print(list1)
Output:
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
# Python program to demonstrate comments
# sample comment
name ="geeksforgeeks"
print(name)
Output:
geeksforgeeks
In the above example, it can be seen that comments are ignored by the interpreter during
the execution of the program.
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
Types of Comments in Python
There are three main kinds of comments in Python. They are:
Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next
line and continue the comment. Python’s single-line comments are proved useful for
supplying short explanations for variables, function declarations, and expressions. See the
following code snippet demonstrating single line comment:
Example:
Python3
# Print “GeeksforGeeks !” to console
print("GeeksforGeeks")
Output
GeeksforGeeks
Multi-Line Comments
Python does not provide the option for multiline comments. However, there are different
ways through which we can write multiline comments.
We can multiple hashtags (#) to write multiline comments in Python. Each and every line
will be considered as a single-line comment.
Python3
Output
Multiline comments
Python ignores the string literals that are not assigned to a variable so we can use these
string literals as a comment.
Example 1:
Python3
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
""" Python program to demonstrate
multiline comments"""
print("Multiline comments")
Output
Multiline comments
Python Docstring
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
defmultiply(a, b):
"""Multiplies the value of a and b"""
returna*b
Python Operators in general are used to perform operations on values and variables. These
are standard symbols used for the purpose of logical and arithmetic operations. In this article,
we will look into different types of Python operators.
OPERATORS: Are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Types of Python Operators
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
Example
# Addition
print("a + b : ", a + b)
# Subtraction
print("a - b : ", a - b)
# Multiplication
print("a * b : ", a * b)
# Division
print("a / b : ", a / b)
# Modulus
print("a % b : ", a % b)
# Exponent
print("a ** b : ", a ** b)
# Floor Division
print("a // b : ", a // b)
This produce the following result −
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
Python Comparison Operators
Python comparison operators compare the values on either sides of them and decide the
relation among them. They are also called relational operators. These operators are equal, not
equal, greater than, less than, greater than or equal to and less than or equal to.
Example
# Equal
print("a == b : ", a == b)
# Not Equal
print("a != b : ", a != b)
# Greater Than
print("a >b : ", a > b)
# Less Than
print("a <b : ", a < b)
= Assignment Operator a = 10
Example
# Addition Assignment
a +=5
print("a += 5 : ", a)
# Subtraction Assignment
a -=5
print("a -= 5 : ", a)
# Multiplication Assignment
a *=5
print("a *= 5 : ", a)
# Division Assignment
a /=5
print("a /= 5 : ",a)
# Remainder Assignment
a %=3
print("a %= 3 : ", a)
# Exponent Assignment
a **=2
print("a **= 2 : ", a)
<< Binary Left Shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off
Example
# Binary AND
c=a&b # 12 = 0000 1100
print("a &b : ", c)
# Binary OR
c=a|b # 61 = 0011 1101
print("a | b : ", c)
# Binary XOR
c=a^b # 49 = 0011 0001
print("a ^ b : ", c)
# Binary Ones Complement
c =~a;# -61 = 1100 0011
print("~a : ", c)
and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.
not Logical NOT Used to reverse the logical state of its Not(a and b) is false.
operand.
not in Evaluates to true if it does not finds a x not in y, here not in results in a
variable in the specified sequence 1 if x is not a member of
and false otherwise. sequence y.
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@
and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >><<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= <>>=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Expressions
In the above example x, y and z are variables, 5 and 3 are values, = and + are operators.
So, the first combination x = 5 is an expression, the second combination y = 3 is an another
expression and at last, z = x + y is also an expression.
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
2. Arithmetic Expressions
Example :
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
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)
4. Floating Expressions
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
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 :
Type: <class 'bool'>
The result of the expression is: False
6. Logical Expressions
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 xx and yy The expression return True if both xx and yy are true, else it
returns False.
Note :
In the table specified above, xx and yy can be values or another expression as well.
Example :
from operator import and_
x = (10 == 9)
y = (7 > 5)
and_result = x and y
or_result = x or y
not_x = not x
7. Bitwise Expressions
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
8. Combinational Expressions
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)
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.
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 :
Result of 'x + y + z' is: 236
Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236
Difference between Statements and Expressions in Python
We have earlier discussed statement expression in Python, let us learn the differences
between them.
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.
Example:
Python3
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.
Python3
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
Python3
# initializing integer
s ='4'
c =ord(s)
print(c)
c =hex(56)
print(c)
c =oct(56)
print(c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.
Python3
# initializing string
s ='geeks'
c =tuple(s)
c =set(s)
print(c)
c =list(s)
print(c)
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(c)
# printing integer converting to string
c =str(a)
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
a =chr(76)
b =chr(77
print(a)
print(b)
Output:
M
Defining and Processing Arrays – Array methods.
An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array).
To get a detailed explanation of Python Array go through the Python Self Paced course , this
course offers you a complete fundamental of Python Array.
Create an Array in Python
Array in Python can be created by importing an array
module. array( data_type , value_list ) is used to create array in Python with data type and
value list specified in its arguments.
In below code Python create array : one of integers and one of doubles . It then prints the
contents of each array to the console.
Python
Output
Output
Output
import array
arr = array.array('i', [1, 2, 3, 1, 5])
print("The new created array is : ", end="")
for i in range(0, 5):
print(arr[i], end=" ")
print("\r")
print("The popped element is : ", end="")
print(arr.pop(2))
print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")
print("\r")
arr.remove(1)
print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")
Output
This code employs slicing to extract elements or subarrays from an array. It starts with an
initial array of integers and creates an array from the list. The code slices the array to extract
elements from index 3 to 8, from index 5 to the end, and the entire array and In below code
Python print array as The sliced arrays are then printed to demonstrate the slicing
operations.
Python
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)
Output
Initial Array:
1 2 3 4 5 6 7 8 9 10
Slicing elements in a range 3-8:
array('i', [4, 5, 6, 7, 8])
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("The new created array is : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))
print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))
Output
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("Array before updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
arr[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print()
arr[4] = 8
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
Output