Python Notes
Python Notes
Software
Software is a generic term used to describe computer programs to perform a specific task .
What is Python?
Python is an interpreted, high-level, general-purpose programming language. Python is an open
source and cross-platform programming language that has become increasingly popular over the
years. It was created by Guido van Rossum and first released in 1991.
The programming language is maintained and available from Python Software Foundation:
[Link] Here you can download the basic Python features in one package,
which includes the Python programming language interpreter, and a basic code editor, or an
integrated development environment, called IDLE.
The python interpreter is a very basic editor, and the minimum needed to create basic Python
programs. To solve complex tasks we need to install and use separate Python packages created
by third parties like Anaconda.
A compiled language is a programming language that is converted into machine code so that the
processor can execute it. The overhead for the translation is incurred just once, when the source
is compiled; thereafter, it need only be loaded and executed. It is faster than interpreted language.
Compiled languages are better for permanent applications where speed is in [Link] compiled
languages are usually compiled, not interpreted. For example – COBOL, C, C++, C#, etc.
An interpreted language is also a programming language that is commonly interpreted.
Interpreted language must be parsed, interpreted, and executed each time the program is run. . It
is reduced to machine instructions at run-time. For this reason interpreted programs are less
efficient than compile programs. An interpreted language is generally more suited for doing ‖ad
hoc‖ calculations or simulations. For example: Python, BASIC, JavaScript, Perl, etc.
Steps used
1. Lexing
2. Parsing
3. Creation of byte code
4. Conversion to machine-executable code
5. Returning output
Step 1: Lexing
Analyzing a code block in Python starts with Lexing, wherein the single line of code being
executed by the interpreter and converted into smaller parts. Each of these parts is called a token,
and these tokens are generated by the lexer, which is a part of the Python interpreter. Essentially,
Here the interpreter breaks down the user instruction into small pieces, to process it piecewise.
Step 2: Parsing
Another component of the Python interpreter called the Parser performs the process of Parsing.
Parsing is a process in which the tokens generated in the Lexing stage into a structure
called Abstract Syntax Tree. This tree shows the relationship between the tokens generated from
a particular line of code and checks for syntax errors, and if an error is found, the interpreter
stops translating code and shows an error message.
Step 3: Creation of Byte Code
The compiler(a part of interpreter) converts the Abstract Syntax Tree into an intermediate
language code, called bytecode . This is a compiled version of the original code which is a low-
level, platform independent representation. This byte code is stored in a file with the same name
as the original source file, but with a ‗.pyc‘ extension instead of ‗.py‘. This is a step completely
hidden from the developer which happens internally, and is performed as executing byte code is
much faster than original code statements.
The PVM(Python Virtual Machine ) is the actual runtime engine of Python, and can be
summarized as a big loop which iterates through the byte code instructions stored in the file with
.pyc extension statement wise. Then it converts the statements into machine code, that is binary
(0s and 1s). It also integrates and loads the inputs and libraries involved in the program, so that
the required instructions can be carried out successfully. The PVM is the part of the interpreter
that truly executes Python scripts.
After the code is converted to binary, it is executed by the interpreter. If there is an error, it
displays the message and exits. Such an error is called a runtime error. If there is no runtime
error during program execution, then the interpreter prints the output and exits successfully.
History of Python
Python was developed by Dutch programmer Guido van Rossum in the late 1980s and He began
working on Python in December 1989 as a hobby project while working at the Centrum
Wiskunde & Informatica (CWI) in the Netherlands. Python's first version (0.9.0) was released in
1991.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages. Guido van Rossum wanted Python to
be a high-level language that was powerful yet readable and easy to use.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
The word Python is related to a species of snake. Rossum though attributes the choice of the
name Python to a popular comedy series Monty Python's Flying Circus on BBC.
Being the principal architect of Python, the developer community conferred upon him the title
of Benevolent Dictator for Life (BDFL). However, in 2018, Rossum relinquished the title.
Thereafter, the development and distribution of the reference implementation of Python is
handled by a nonprofit organization Python Software Foundation.
Evaluation of python
Python 0.9.0
Python's first published version is 0.9. It was released in February 1991. It consisted of features
such as classes with inheritance, exception handling, and core data types like lists and
dictionaries..
Python 1.0
In January 1994, version 1.0 was released, armed with functional programming tools, features
like support for complex numbers etc and module system which allows a better code
organization and reuse.
Python 2.0
The next major version − Python 2.0, was launched in October 2000. Many new features such as
list comprehension, garbage collection and Unicode support were included with it. Throughout
the 2000s, Python 2.x became the dominant version, gaining traction in industries ranging from
web development to scientific research. Various useful libraries like NumPy, SciPy, and Django
were also developed.
Python 3.0
Python 3.0, a completely renewed version of Python was released in December 2008. The
primary objective of this revamp was to remove a lot of discrepancies that had crept in Python
2.x versions. Python 3 was back ported to Python 2.6. It also included a utility named as python
2to3 to facilitate automatic translation of Python 2 code to Python 3. Python 3 provided new
syntax, unicode support and Improved integer division.
Even after the release of Python 3, Python Software Foundation continued to support the Python
2 branch with incremental micro versions till 2019. However, it decided to discontinue the
support by the end of 2020, at which time Python 2.7.17 was the last version in the branch.
Meanwhile, more and more features have been incorporated into Python's 3.x branch. As of date,
Python 3.13.5 is the current stable version, released in April 2025.
Python 3.13 is the latest stable release of the Python programming language, with a mix of
changes to the language, the implementation and the standard library. The biggest changes
include a new interactive interpreter, experimental support for running in a free-threaded
mode (PEP 703), and a Just-In-Time compiler (PEP 744). Error messages continue to improve,
with tracebacks now highlighted in color by default. The library changes contain removal of
deprecated APIs and modules, as well as the usual improvements in user-friendliness and
correctness.
Python is evolving everyday where Python 3.x receives regular updates. Python's developers
community is focusing on performance improvements making it more efficient while retaining
its ease of use.
Python is being heavily used for machine learning, AI, and data science, so for sure its future
remains bright. It's role in these rapidly growing fields ensures that Python will stay relevant for
years.
Python is also increasingly becoming the first programming language taught in schools and
universities worldwide, solidifying its place in the tech landscape.
Why Python?
● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a functional way.\
Features of python
Here are the top features of Python that make it a standout programming language:
Python supports GUI programming through libraries such as Tkinter, PyQt, and Kivy, making it
easy to create user-friendly desktop applications. These libraries provide tools and widgets to
build interactive, cross-platform graphical user interfaces.
2. Object-Oriented Programming
Python is fully object-oriented, enabling developers to create classes and objects to model real-
world entities. Features like inheritance, encapsulation, and polymorphism are supported, making
it easier to build complex applications using reusable and organized code.
3. Dynamic Language
Python is dynamically typed, meaning that variable types are determined at runtime. This allows
for more flexibility in coding since developers do not need to declare variable types explicitly,
speeding up development process.
4. Easy to Code
Python's simple and readable syntax makes it one of the most beginner-friendly programming
languages. It emphasizes readability and reduces code complexity, enabling quick development
and accessible learning for newcomers.
Python is free to download, use, and distribute, as it is open-source under the Python Software
Foundation License. This makes it accessible to everyone, fostering innovation and collaborative
improvements within the community.
7. Interpreted Language
Python is an interpreted language, meaning code is executed line by line at runtime without
requiring prior compilation. This simplifies debugging and testing, enhancing the development
workflow.
8. Standard Library
This is one of the key features of Python. Python has a vast standard library that provides built-in
modules and functions for tasks such as file I/O, web development, data manipulation, regular
expressions, and more. This reduces the need for external dependencies and speeds up
development.
9. Community Support
Python boasts a large and active community of developers. This means extensive documentation,
tutorials, forums, and open-source libraries are readily available, making it easier for developers
to find support and contribute to the language.
10. Portable Language
Python code can run on various operating systems like Windows, Linux, macOS, and more
without modification. This cross-platform portability enables developers to create software that
can be executed in multiple environments seamlessly.
11. Databases
Python offers excellent support for database connectivity. Libraries like SQLite3, SQLAlchemy,
and PyMySQL allow developers to interact with databases, execute queries, and manage data
efficiently, making Python suitable for building database-driven applications.
12. Extensible
Python can be extended with code written in languages like C or C++. This allows for enhanced
performance and the ability to use existing libraries and modules from other ecosystems within
Python programs.
Python is cross-platform, allowing the same codebase to be run on different operating systems
without modification. This is essential for developing software that needs to be compatible
across various devices and platforms.
Python supports enhancements and type hints through tools like typing and type checkers such as
mypy. This allows developers to specify types for variables, function parameters, and return
values, leading to better readability and fewer runtime errors.
While primarily used for backend development in frameworks like Django and Flask, Python can
also be used in the front end through frameworks like Brython or Pyodide. This flexibility makes
Python a versatile choice for full-stack development
Applications of Python
Here is a list of popular applications of Python:
1. Web Development: Using frameworks like Django, Flask, and FastAPI.
2. Data Science and Analytics: For data manipulation and visualization with libraries like
Pandas, NumPy, and Matplotlib.
3. Machine Learning and AI: With powerful libraries like TensorFlow, PyTorch, and scikit-
learn.
4. Game Development: Utilizing libraries like Pygame.
5. Desktop GUI Applications: Using Tkinter, PyQt, and Kivy.
6. Web Scraping: Through tools like Beautiful Soup and Scrapy.
7. Automation/Scripting: Writing scripts for task automation and system administration.
8. Network Programming: This is used to build networked applications using libraries such as
Socket and Twisted.
9. Cybersecurity and Penetration Testing: Employed to write security tools and scripts.
10. Robotics and Embedded Systems: Using frameworks like MicroPython.
11. Finance and Fintech: For quantitative analysis, financial modeling, and algorithmic trading.
12. Blockchain Development: Creating smart contracts and blockchain solutions.
13. Education: Widely used as a teaching tool in computer science courses due to its simplicity.
14. Cloud Computing: Employed in cloud environments for automation, serverless
applications, and more.
15. Audio and Video Processing: With libraries like OpenCV and PyDub.
16. Scientific Computing: Using libraries like SciPy for complex mathematical and scientific
tasks.
17. Chatbots and Conversational Interfaces: Using libraries like ChatterBot.
18. E-commerce Solutions: Backend development for online stores and inventory management
systems.
19. Business Applications: Developing enterprise software, ERP systems, and other business
solutions.
20. IoT (Internet of Things): Integrating with hardware and IoT platforms for smart
applications
Chapter 2
Standard Data types
What is a Data Type in Python?
Python data types are referred to as the classification of different data items. It represents
different types of variables that inform what operations a user can perform on specific data items.
Since everything in the Python programming language is identified as an object, data types are
classified as classes and variables as objects of the same classes.
A variable holding a value will always have a data type. With Python being a dynamic type of
programming language, there is no need for the users to specify the variable type while declaring
it. It is the interpreter who implicitly binds the value of the variable with the data type. Moreover,
Python provides the type () function to determine a particular variable‘s data type.
For example –
a=6
The variable in the given example holds an integer value of six, and the data type is not defined.
Python interpreter will implicitly interpret the variable ‗a‘ as an integer type.
Integers (int)
The numeric data type represented by the int class, integers, includes positive and negative whole
numbers, excluding fractions and decimals. In Python, there is no limitation on the length of the
integer value. For example, 5, 13, 87, -65, -47, -98, etc.
String
In Python, strings are a sequence of bytes that represents Unicode characters. A string is
typically a collection of one or more characters that a user can put in a single, double, or triple
quote. The ‗str‘ class represents the string data type in Python. Python provides built-in functions
and operators for performing operations in the string.
List
The list data type is similar to the arrays – an ordered collection of data. This data type is
relatively flexible since there is no need for the items in the list to be of the same type. You can
create lists in Python simply by putting the items inside the square brackets []. Subsequently, to
separate the items stored in the lists, you can use a comma (,).
Example: tup1=('a','b','c')
The boolean data type provides two built-in values, which are ‗True‘ and ‗False‘. These two
values help in determining if the given statement is true or false. Boolean objects that are true are
referred to as truthy (true), and false Boolean objects are referred to as falsy (false).
However, Python allows evaluating the non-Boolean objects in the Boolean context and
determining whether they are true or false. The class ‗bool‘ represents the Boolean data type. A
non-zero value or ―T‖ represents the True values, and zero or ―F‖ represents the False values.
The set data type is an unordered collection of iterable, mutable, and unique data values.
Although the set contains various elements, the order of the elements remains unidentified. You
can create the set by using a built-in function set () in Python. A sequence of elements is
enclosed in the curly brackets {}, and the comma (,) is used to separate the elements. The set can
consist of various types of values.
In Python, implicit conversion happens automatically during operations when the interpreter can
safely transform one data type into another without losing information.
# Implicit Conversion
x=5 # Integer
y = 2.0 # Float
# Adding integer and float results in float
result = x + y
print(result)
print(type(result))
Output: 7.0
<class 'float'>
Here, Python converts the integer x into a float to perform the addition, ensuring that the result
(7.0) is a float.
Explicit conversion or typecasting requires the developer to manually convert a variable from
one data type to another using Python's built-in functions. This is especially useful when implicit
conversion isn‘t possible or when precision is necessary.
a = "42"
b = int(a)
print(type(b))
Output
<class 'int'>
In this case, the string "42" is explicitly converted to an integer using the int() function.
Arithmetic operators:
Arithmetic operators are used to perform arithmetic/mathematical operations.
Assignment operators:
These operators are used to assign values to variables.
Name Evaluated As
= a=b
+= a+=b or a=a+b
-= a-=b or a=a-b
*= a*=b or a=a*b
**= a**=b or a=a**b
/= a/=b or a=a/b
//= a//=b or a=a//b
%= a%=b or a=a%b
&= a&=b or a=a&b
** =**
^= a^=b or a=a^b
>>= a>>=b or a=a>>b
<<= a<<=b or a=a<<b
Bitwise operators:
Bitwise operators are used to deal with binary operations.
Name Operator Example
Bitwise AND & a&b
Bitwise OR | a|b
Bitwise NOT ~ ~a
Bitwise XOR ^ a^b
Bitwise right shift >> a>>
Bitwise left shift << b<<
Comparison operators:
These operators are used to compare values.
Name Operator Example
Equal == a==b
Not Equal != a!=b
Less Than < a<b
Greater Than > a>b
Less Than or Equal to <= a<=b
Greater Than or Equal to >= a>=b
Identity operators:
Name Example Evaluated As
is a is b Returns True if a and b are same
is not a is not b Returns True if a and b are not same
Logical operators:
These operators are used to deal with logical operations.
Name Operator Example
AND and a=2 and b=3
OR or a=2 or b=3
NOT not Not(a=2 or b=3)
Membership operators:
Name Example Evaluated As
in a in b Returns True if a is present in given sequence or
collection
not in a not in b Returns True if a is not present in given sequence or
collection
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.
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
and
else returns false.
This is also a logical operator which returns true if anyone operand is true
or
else returns false.
This is again a logical operator it returns True if the operand is false else
not
returns false.
if This is used to make a conditional statement.
Elif is a condition statement used with an if statement. The elif statement is
elif
executed if the previous conditions were not true.
Else is used with if and elif conditional statements. The else block is
else
executed if the given condition is not true.
for This is used to create a loop.
while This keyword is used to create a while loop.
break This is used to terminate the loop.
as This is used to create an alternative.
def It helps us to define functions.
lambda It is used to define the anonymous function.
pass This is a null statement which means it will do nothing.
return It will return a value and exit the function.
True This is a Boolean value.
False This is also a Boolean value.
try It makes a try-except statement.
with The with keyword is used to simplify exception handling.
This function is used for debugging purposes. Usually used to check the
assert
correctness of code
class It helps us to define a class.
continue It continues to the next iteration of a loop
del It deletes a reference to an object.
except Used with exceptions, what to do when an exception occurs
Finally is used with exceptions, a block of code that will be executed no
finally
matter if there is an exception or not.
from It is used to import specific parts of any module.
global This declares a global variable.
import This is used to import a module.
in It's used to check whether a value is present in a list, range, tuple, etc.
is This is used to check if the two variables are equal or not.
This is a special constant used to denote a null value or avoid. It's important
none to remember, 0, any empty container(e.g empty list) do not compute to
None
nonlocal It's declared a non-local variable.
raise This raises an exception.
yield It ends a function and returns a generator.
async It is used to create asynchronous co routine.
await It releases the flow of control back to the event loop.
Python Variables
Variables are used to store data that can be referenced and manipulated during program
execution. A variable is essentially a name that is assigned to a value. Unlike many other
programming languages, Python variables do not require explicit declaration of type. The type of
the variable is inferred based on the value assigned. Variables act as placeholders for data. They
allow us to store and reuse values in our program.
Example
x=5
Valid Examples
age = 21
_colour = "lilac"
total_score = 90
Invalid Examples
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
Basic Assignment
Variables in Python are assigned values using ― = ‖ operator.
x=5
y = 3.14
z = "Hi"
Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold different types of
values during execution.
x = 10
x = "Now a string"
Multiple Assignments
Python allows multiple variables to be assigned values in a single line.
Output
100 100 100
Output
1 2.5 Python
Multi-Line Comments
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 (#)
1. Constant Expressions: These are the expressions that have constant values only.
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis. The result of this type of expression is also a numeric
value. The operators used in these expressions are arithmetic operators like addition, subtraction,
etc. Here are some arithmetic operators in Python:
Example
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: Expressions that produce only integer results after all
computations and type conversions.
Example: # Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: Expressions which produce floating point numbers as result after
all computations and type conversions.
Example: # Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written
on both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated
first, and then compared as per relational operator and produce a boolean output in the end.
These expressions are also called Boolean expressions.
Example: # Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions: Expressions that result in either True or False. It basically specifies
one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it
is not correct, so it will return False. Here are some logical operators in Python:
Example:- P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
Statements in Python:
A statement in Python is an instruction that performs a specific action. It is the smallest
unit of code the Python interpreter can execute, usually written on a single line. Python includes
different types of statements like simple, conditional, looping, and assignment. Each statement
typically ends with a NEWLINE.
We use a backslash to split one logical statement into multiple lines manually.
Example: # Multi-line addition using backslash
total = 10 + 20 + \
30 + 40
print("Total:", total)
Output:
Total: 100
We use the implicit line continuation to split a long statement using brackets [], parentheses (),
and braces {}.
Example: # Multi-line addition using parentheses
total = (10 + 20 +
30 + 40)
print("Total:", total)
Output:
Total: 100
Chapter 6
1. Python If Statement
if is a conditional statement in Python used to decide whether a given code or block of code will
be executed or not. It is the simplest decision-making statement in Python and executes a code
only when a certain condition is true.
Syntax:
if condition:
# code to run if condition is true
Flowchart of an if Statement
Example: x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
Example: age = 18
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
Output:
You can vote
if condition1:
# code if condition1 is true
elif condition2:
# code if condition2 is true
else:
# code if none of the above conditions are true
Example: marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Grade C")
Output:
Grade B
Example: bug_count = 5
tests_passed = True
if bug_count == 0:
if tests_passed:
print("Ready for deployment")
else:
print("Fix test issues before deployment")
else:
if bug_count < 10:
print("Minor bugs – fix before release")
else:
print("Too many bugs – not ready for release")
Output:
Minor bugs – fix before release
Chapter 7
In Python, we use the for loop to iterate over various types like lists, tuples, sets, strings, and
dictionaries.
1. Iterating over a List
Example: fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. Iterating over a Tuple
Example: numbers = (1, 2, 3)
for number in numbers:
print(number)
Output:
1
2
3
3. Iterating over a Set
Example: colors = {"red", "green", "blue"}
for color in colors:
print(color)
Output (order may vary):
red
green
blue
4. Iterating over a String
Example: word = "hello"
for letter in word:
print(letter)
Output: h
e
l
l
o
5. Iterating over a Dictionary
Example: person = {"name": "Alex", "age": 30, "city": "New York"}
for key, value in [Link]():
print(key, ":", value)
Output:
name : Alex
age : 30
city : New York
Example: count = 1
while count <= 3:
print("Count is:", count)
count += 1
Output:
Count is: 1
Count is: 2
Count is: 3
7. Python try-except
We use the try-except statement in Python to manage errors within the code. The try block
checks the code for any errors and executes the program if there are no errors in the code given
inside the try block. However, if the program finds an error in the try block, it executes the code
inside the except block.
Syntax:
try:
# code that may raise an error
except:
# code to handle the error
Example: num = int("abc")
print("Conversion successful")
In Python, expression statements are lines of code that evaluate and return a value. They can
assign values to variables, call functions, or perform calculations to produce results during
execution.
Example:
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8
for i in range(3):
pass # loop does nothing for now
The program does not show any output, and the code runs without error.
3. Python break Statement
The break statement in Python terminates the loop in which it is placed. After breaking, control
passes to the first statement following the loop. If used inside a nested loop, it only breaks the
innermost loop where the break occurs.
Syntax:
for/while item in iterable:
if condition:
break
Example:
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
Python's input() function is used to take user input. By default, it returns the user input in form of
a string.
Example: name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: Priya
Hello, Priya! Welcome!
The code prompts the user to input their name, stores it in the variable "name" and then prints a
greeting message addressing the user by their entered name.
Printing output in Python is straightforward using print() function. This function allows us to
display text, variables and expressions on the console.
In this example, "Hello, World!" is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.
print("Hello, World!")
Output
Hello, World!
Printing Variables
We can use the print() function to print single and multiple variables. We can print multiple
variables by separating them with commas. Example:
# Single variable
s = "Bob"
print(s)
# Multiple Variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)
Output
Bob
We are taking multiple input from the user in a single line, splitting the values entered by the
user into separate variables for each value using the split() method. Then, it prints the values with
corresponding labels, either two or three, based on the number of inputs provided by the user.
Output Formatting
Output formatting in Python with various techniques including the format() method,
manipulation of the sep and end parameters, f-strings and the versatile % operator. These
methods enable precise control over how data is displayed, enhancing the readability and
effectiveness of your Python programs.
amount = 150.75
print("Amount: ${:.2f}".format(amount))
Output
Amount: $150.75
# another example
print('pratik', ‗AGM Ltd.‘, sep='@')
Output
Python@Priya
STM
09-12-2016
pratik@ AGM Ltd.
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")
We can use '%' operator. % values are replaced with zero or more value of elements. The
formatting using % is similar to that of ‗printf‘ in the C programming language.
%d –integer
%f – float
%s – string
%x –hexadecimal
%o – octal