Python Notes
Python Notes
Overview of Python
What is Python?
Python is a high-level, general-purpose programming language known for its
simplicity and readability. It supports various programming paradigms, including
object-oriented, imperative, and functional programming. Python is widely used in
industries like web development, data science, artificial intelligence, automation, and
more due to its ease of use and versatility.
Why Do We Need Python?
Python has become one of the most popular languages because it addresses many
common needs in the software development world, including:
• Ease of Learning and Use: Python's simple and intuitive syntax makes it
easy for beginners to learn and use. The language is designed to be readable
and straightforward, reducing the complexity of writing and understanding
code.
• Versatility: Python is used in a wide range of applications, including web
development (with frameworks like Django and Flask), data analysis (with
libraries like Pandas and NumPy), machine learning (with TensorFlow and
Scikit-learn), automation (using libraries like Selenium), and much more.
• Extensive Libraries and Frameworks: Python comes with a vast standard
library, as well as third-party packages, which make development faster and
easier by providing pre-built modules for various tasks (e.g., requests for
HTTP requests, matplotlib for plotting, etc.).
• Cross-Platform: Python is available on all major platforms (Windows,
macOS, Linux), making it an excellent choice for developing applications that
need to run across multiple operating systems.
• Community Support: Python has a large and active community that
continuously contributes to the language's development and provides support
for various libraries and frameworks.
Key Features of Python
• Interpreted Language: Python code is executed line-by-line, which makes
debugging easier. There's no need to compile the code before running it.
• Dynamically Typed: You don't need to declare variable types. The interpreter
automatically determines the type based on the value assigned to the
variable.
x = 10 # Integer
y = "Hello" # String
• High-Level Language: Python abstracts low-level details, making it easier to
work with complex data structures and algorithms without worrying about
memory management or other hardware-level details.
• Readable Syntax: Python's syntax is clean and easy to understand. It
emphasizes readability, often compared to writing pseudocode, allowing
developers to express concepts in fewer lines of code than many other
languages.
• Object-Oriented and Functional: Python supports both object-oriented and
functional programming paradigms, giving developers flexibility in how they
structure their programs.
Applications of Python
Python can be used in various domains:
• Web Development: Frameworks like Django, Flask.
• Data Science: Libraries like Pandas, NumPy, and SciPy.
• Artificial Intelligence and Machine Learning: TensorFlow, Scikit-learn,
PyTorch.
• Automation and Scripting: Automating repetitive tasks like web scraping
(using Selenium, BeautifulSoup).
• Game Development: Libraries like Pygame.
• Networking and Cybersecurity: Tools like Scapy for network analysis and
security testing.
Python Installation
To start programming in Python, you'll first need to install it on your system.
1. Downloading Python:
o Go to the official Python website.
o Choose the version compatible with your operating system (Windows,
macOS, Linux) and download the installer.
2. Installing Python:
o Follow the installation steps. Ensure that you select the option to Add
Python to PATH during installation for easy access through the
command line.
3. Verifying Installation:
o After installation, open your terminal (Command Prompt on Windows or
terminal on macOS/Linux) and type:
bash
python --version
o You should see the installed Python version, confirming the installation.
What is an Interpreter?
An interpreter is a program that reads and executes code line by line. Python is an
interpreted language, meaning it does not require prior compilation like languages
such as C or Java. The Python interpreter translates your code into machine-
readable instructions as it runs, making it easier to test and debug.
Interpreters vs Compilers
• Interpreter:
o Executes code line by line.
o Easier for debugging because you can test code interactively.
o Slower execution since translation happens in real-time.
o Example: Python, JavaScript, Ruby.
• Compiler:
o Converts the entire source code into machine code before running it.
o Faster execution once compiled, but slower initial start due to the
compilation process.
o Example: C, C++, Java.
Using the Python Interpreter
To start the Python interpreter, open a terminal (or command prompt) and type:
python
This will launch the Python interactive shell, where you can execute Python
commands.
Example:
>>> print("Hello, Python!")
Output:-
Hello, Python!
You can type in any Python statement or expression, and the interpreter will execute
it immediately.
Interactive Mode
In Interactive Mode, you can quickly test Python commands directly in the terminal
or Python shell.
Advantages:
• Fast feedback: Great for experimenting with small snippets of code.
• No need to write or save the entire program to run.
Example:
>>> 5 + 3
8
>>> name = "Alice"
>>> print(f"Hello, {name}")
Output:
Hello, Alice
Exiting Interactive Mode:
• Type exit() or press Ctrl+D (on Linux/macOS) or Ctrl+Z (on Windows).
# calculator.py
def add(a, b):
return a + b
result = add(5, 3)
print(f"Result: {result}")
• Run in terminal:
python calculator.py
• Output:
Result: 8
1. Output Statement
The most common way to output data in Python is by using the print() function. It is
used to display data to the console.
Syntax of print():
print(object(s), sep=' ', end='\n', file=sys.stdout, flush=False)
• object(s): The data you want to display (strings, numbers, etc.).
• sep: Separator between objects if there are multiple.
• end: Specifies what to print at the end (default is a newline).
• file: The output destination (default is the console).
• flush: Forces the output to appear immediately.
Example
# Simple print statement
print("Hello, Python!") # Output: Hello, Python!
Formatted Output:
You can format output using either formatted string literals (f-strings) or the
format() method.
name = "Aditya"
age = 25
print(f"My name is {name} and I am {age} years old.") # Output: My name is Aditya
and I am 25 years old.
Using the format() method:
2. Input Statement
To take input from the user, Python provides the built-in input() function. It reads a
line of text from the user, and by default, it returns the input as a string.
Syntax of input():
input(prompt)
• prompt: Optional. A message displayed to the user before taking input.
Examples:
Since input() always returns a string, you might need to convert the input to another
type, such as an integer or float.
import sys
Output:
First argument: Hello
Second argument: World
import sys
# Convert command-line arguments to integers
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
result = num1 + num2
How to Run:
$ python script_name.py 10 20
Output:
bash
Copy code
The sum is: 30
Variables in Python
2. Multiple Assignment
Python allows you to assign values to multiple variables simultaneously.
Example of Multiple Assignment:
# Assigning multiple variables in a single line
a, b, c = 5, 10, 15
print(a) # Output: 5
print(b) # Output: 10
print(c) # Output: 15
You can also assign the same value to multiple variables at once:
x = y = z = 100
print(x) # Output: 100
print(y) # Output: 100
print(z) # Output: 100
3. Variable Reassignment
In Python, variables can be reassigned to a new value, even if the new value
is of a different data type. This is possible because Python is dynamically typed.
Example:
x = 10 # Initially an integer
print(x) # Output: 10
4. Scope of Variables
The scope of a variable refers to the part of the program where it is
accessible. Variables can be defined at different scopes:
• Global Variables: Defined outside of any function or block, accessible
throughout the program.
• Local Variables: Defined inside a function or block, accessible only within
that function or block.
1. Identifiers in Python
An identifier is the name used to identify a variable, function, class, module,
or other objects in Python. Identifiers help in naming the entities in your code and
must follow specific rules and guidelines.
Rules for Naming Identifiers:
1. Starts with a letter or underscore: Identifiers must begin with a letter (a-z,
A-Z) or an underscore (_).
2. Contains letters, numbers, and underscores: After the first character,
identifiers can include letters, digits, and underscores.
3. No spaces or special characters: Identifiers cannot contain spaces,
punctuation marks, or symbols like @, #, %, $, etc.
4. Cannot start with a number: Identifiers cannot begin with digits (0-9).
5. Case-sensitive: Python is case-sensitive, meaning name and Name are two
different identifiers.
6. No reserved words: Identifiers cannot be the same as Python's reserved
words (keywords).
Examples of Valid Identifiers:
my_var = 10
age = 25
_name = "Naveen"
Data types define the type of data that can be stored in a variable. Python is
a dynamically typed language, meaning the type of a variable is determined at
runtime based on the value assigned to it. Python provides several built-in data types
that can store different kinds of data, such as numbers, text, and more complex
collections.
Categories of Data Types:
1. Numeric Types:
o int (Integer)
o float (Floating-Point Number)
o complex (Complex Number)
2. Sequence Types:
o str (String)
o list (List)
o tuple (Tuple)
3. Mapping Type:
o dict (Dictionary)
4. Set Types:
o set (Set)
o frozenset (Frozen Set)
5. Boolean Type:
o bool (Boolean)
1. Numeric Types
a. Integer (int):
The int data type is used to represent whole numbers, both positive and negative,
without decimal points.
Example:
x = 10 # Positive integer
y = -5 # Negative integer
z = 0 # Zero
print(type(x))
Output: <class 'int'>
b. Floating-Point (float):
The float data type is used to represent real numbers (numbers with decimal points).
Example:
pi = 3.14 # Floating-point number
gravity = 9.8
print(type(pi))
Output: <class 'float'>
2. Sequence Types
a. String (str):
A str in Python is a sequence of characters enclosed in single, double, or triple
quotes.
Example:
name = "Alice" # Using double quotes
greeting = 'Hello' # Using single quotes
multiline_text = '''This is a
multi-line string.''' # Triple quotes for multi-line strings
print(type(name))
Output:
<class 'str'>
b. List (list):
A list is a mutable, ordered collection of elements. Lists can contain elements of
different types and are defined using square brackets [].
Example:
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4]
mixed_list = [1, "hello", 3.14]
print(type(fruits))
Output:
<class 'list'>
You can modify a list:
fruits[0] = "orange" # Changing 'apple' to 'orange'
c. Tuple (tuple):
A tuple is an immutable, ordered collection of elements. Tuples are defined using
parentheses ().
Example 1:
coordinates = (10, 20)
names = ("Alice", "Bob", "Charlie")
print(type(coordinates)) # Output: <class 'tuple'>
Example 2:
Tuples are immutable, so you can't modify them:
coordinates[0] = 15 # This will raise an error (Tuples are immutable)
3. Mapping Type
a. Dictionary (dict):
A dict is an unordered collection of key-value pairs. It is defined using curly braces {}.
Keys must be unique and immutable, while values can be of any data type.
Example 1:
person = {"name": "John", "age": 30, "city": "New York"}
print(person["name"])
print(type(person))
Output: John <class 'dict'>
Example 2:
You can add, modify, or delete key-value pairs:
5. Boolean Type
Boolean (bool):
The bool type represents two values: True or False. Booleans are often used in
conditions and control flow.
Example 1:
is_active = True
is_valid = False
print(type(is_active))
Output: <class 'bool'>
Example 2:
Booleans are often used in comparisons:
x = 10
y=5
print(x > y)
print(x == y)
Output:
True
False
Summary:
Python supports a variety of data types, each designed for specific types of data:
• Numeric types: For numbers (int, float, complex).
• Sequence types: For ordered collections (str, list, tuple).
• Mapping types: For key-value pairs (dict).
• Set types: For unique collections (set, frozenset).
• Boolean type: For true/false values (bool).
• Binary types: For handling binary data (bytes, bytearray, memoryview).
• None type: For representing the absence of a value (NoneType).
Each type comes with its own properties and operations, making Python a powerful
and flexible programming language.
Python Operators
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition,
subtraction, multiplication, etc
Operator Description Example
+ Addition 5+2=7
- Subtraction 5-2=3
* Multiplication 5 * 2 = 10
/ Division (float) 5 / 2 = 2.5
// Division (floor) 5 // 2 = 2
% Modulus (remainder) 5%2=1
** Exponentiation 5 ** 2 = 25
Example:
a = 10
b=3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.33
print(a // b) # Output: 3
print(a % b) # Output: 1
print(a ** b) # Output: 1000
2. Assignment Operators
Assignment operators are used to assign values to variables.
Operator Description Example
Example 1:
x = 10
x += 5 # Same as x = x + 5
print(x)
Output: 15
Example 2:
x *= 2 # Same as x = x * 2
print(x)
Output: 30