0% found this document useful (0 votes)
7 views22 pages

Python Notes

Python is a high-level programming language known for its simplicity and versatility, widely used in various fields such as web development, data science, and automation. It features dynamic typing, extensive libraries, and a supportive community, making it accessible for beginners and powerful for professionals. The document also covers Python installation, execution modes, input/output operations, variable management, and identifiers, providing a comprehensive overview of the language.

Uploaded by

snehal.dholi30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views22 pages

Python Notes

Python is a high-level programming language known for its simplicity and versatility, widely used in various fields such as web development, data science, and automation. It features dynamic typing, extensive libraries, and a supportive community, making it accessible for beginners and powerful for professionals. The document also covers Python installation, execution modes, input/output operations, variable management, and identifiers, providing a comprehensive overview of the language.

Uploaded by

snehal.dholi30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Python

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.

Environment Setup and Execution Types in Python

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.

Execution Types in Python


Python can be executed in various ways:
1. Interactive Mode: Execute Python commands one line at a time in the
Python shell.
2. Script Mode: Run Python programs saved as .py files.
3. Integrated Development Environments (IDEs): Use tools like PyCharm,
VSCode, or Jupyter for writing, debugging, and executing Python code more
efficiently.

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).

Running Python Files (Script Mode)


In Script Mode, you write your Python code in a .py file and run it through the
terminal or IDE.
Steps:
1. Write your Python code in a text editor and save it with a .py extension.
Example: example.py
# example.py
print("Hello, Python!")
2. Open a terminal and navigate to the directory containing your script, then run:
python example.py
3. This will execute the code in the file and print the output:
Hello, Python!

Working with the Python Shell


The Python shell is the environment where the Python interpreter runs and
executes code interactively. It's used for:
• Running simple Python commands.
• Testing code quickly before adding it to a full script.
The Python shell can be accessed by typing python in the terminal.

Integrated Development Environments (IDEs)


IDEs are tools that provide a rich set of features for writing, testing, and debugging
Python code. Popular Python IDEs include:
• PyCharm: A full-featured IDE with support for debugging, testing, and project
management.
• VSCode (Visual Studio Code): A lightweight editor with Python support
through extensions.
• Jupyter Notebooks: Ideal for data analysis and scientific computing, allowing
you to mix code with rich text and visualizations.
These environments offer features like syntax highlighting, code completion,
debugging tools, and integrated terminal windows.

Interactive Mode Programming


In Interactive Mode, you can write and execute code line by line in the Python shell,
allowing you to:
• Quickly test ideas.
• Debug small code snippets.
Example:
>>> num = 10
>>> num + 5
Output:
15
This is ideal for quick experiments and trying out small code chunks without creating
a full file.

Script Mode Programming


In Script Mode, you write and save code in a .py file and execute the entire file as a
script. This is better for larger, more complex programs.
Example of a Python script (calculator.py):

# 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

Input and Output in Python:

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!

# Print multiple objects


print("Hello", "World", sep="-") # Output: Hello-World

# Custom end of line


print("Hello", end="!") # Output: Hello!

Formatted Output:

You can format output using either formatted string literals (f-strings) or the
format() method.

Using f-strings (Python 3.6+):

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:

print("My name is {} and I am {} years old.".format(name, age))

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:

# Taking input from the user


name = input("Enter your name: ")
print(f"Hello, {name}!")

Converting Input to Other Data Types:

Since input() always returns a string, you might need to convert the input to another
type, such as an integer or float.

Example (Converting to int):

age = int(input("Enter your age: "))


print(f"You are {age} years old.")

Example (Converting to float):

temperature = float(input("Enter the temperature: "))


print(f"The temperature is {temperature} degrees.")
3. Command-Line Arguments
Python provides a way to pass arguments from the command line using the sys
module. The sys.argv list stores the command-line arguments passed to the script.
• sys.argv[0] is always the name of the script.
• The remaining elements (sys.argv[1], sys.argv[2], ...) are the arguments
passed to the script.
Steps to Use Command-Line Arguments:
1. Import the sys module:

import sys

2. Access command-line arguments:


# Accessing command-line arguments
script_name = sys.argv[0]
arg1 = sys.argv[1] # First command-line argument
arg2 = sys.argv[2] # Second command-line argument
How to Run:
From the command line, you can pass arguments like this:

$ python script_name.py Hello World

Output:
First argument: Hello
Second argument: World

Example with Integer Arguments:


If the script expects numbers, you should convert the string arguments to integers:

import sys
# Convert command-line arguments to integers
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
result = num1 + num2

print(f"The sum is: {result}")

How to Run:

$ python script_name.py 10 20

Output:
bash
Copy code
The sum is: 30

Variables in Python

A variable in Python is a symbolic name that represents a value stored in the


computer's memory. Variables act as containers for data and allow you to reference
and manipulate values throughout a program. Unlike many programming languages,
Python does not require you to declare the type of a variable explicitly. Python
automatically infers the variable type based on the value assigned to it.

Key Features of Variables in Python:


1. Dynamic Typing: You do not need to specify the data type of a variable;
Python determines it at runtime based on the value assigned.
2. Reassignment: A variable can be reassigned to a new value, and the type of
the variable can change dynamically.
3. Case Sensitivity: Variables in Python are case-sensitive, meaning age and
Age are two different variables.
Variable Naming Rules:
• A variable name must start with a letter (a-z, A-Z) or an underscore (_).
• The rest of the variable name can contain letters, numbers, or underscores
(_).
• Variable names cannot start with a number.
• You cannot use reserved words or keywords (like if, while, class, etc.) as
variable names.
• Variable names are case-sensitive.

1. Declaring and Assigning Values to Variables


You can create a variable by assigning a value to it using the = operator.
Python uses dynamic typing, so the variable type is inferred from the value you
assign.
Example
# Assigning an integer value
x = 10

# Assigning a string value


name = "Neha"

# Assigning a floating-point value


price = 19.99

# Assigning a boolean value


is_valid = True

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

x = "Hello" # Now reassigned to a string


print(x) # Output: Hello

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.

5. Variable Type Inference


Python automatically detects the data type of a variable based on the value
assigned to it. You can use the type() function to check the data type of any variable.
Example:
x = 42
y = 3.14
z = "Hello"

print(type(x)) # Output: <class 'int'>


print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'str'>

Identifiers and Reserved Words in Python

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"

Examples of Invalid Identifiers:


2name = "Bob" # Starts with a number (Invalid)
my-var = 10 # Contains a hyphen (Invalid)
name@ = "Alice" # Contains special character @ (Invalid)
2. Reserved Words (Keywords) in Python
Reserved words, also known as keywords, are predefined words in Python that
have special meanings and cannot be used as identifiers for variables, functions, or
other objects. These keywords are part of the Python language syntax.

List of Python Reserved Words:


As of Python 3.x, here are the commonly used reserved words:

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

Data Types in Python

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'>

c. Complex Numbers (complex):


The complex data type represents complex numbers with a real and imaginary part.
It is denoted as a + bj, where a is the real part and b is the imaginary part.
Example:
comp = 2 + 3j
print(type(comp))
print(comp.real)
print(comp.imag)
Output:
<class 'complex'>
2.0
3.0

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:

person["age"] = 31 # Update age


person["profession"] = "Engineer" # Add new key-value pair
4. Set Types
a. Set (set):
A set is an unordered collection of unique elements. It is defined using curly braces {}
or the set() constructor.
Example 1:
unique_numbers = {1, 2, 3, 4, 5}
empty_set = set() # Creates an empty set
print(type(unique_numbers))
Output: <class 'set'>
Example 2:
Sets automatically remove duplicates:
numbers = {1, 2, 2, 3, 4}
print(numbers)
Output: {1, 2, 3, 4}

b) Frozen Set (frozenset):


A frozenset is like a set, but it is immutable, meaning once created, you cannot
modify it.
Example:
frozen = frozenset([1, 2, 3, 4])
print(type(frozen))
Output: <class 'frozenset'>

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

Operators in Python are special symbols or keywords used to perform operations on


variables and values. Python supports various types of operators, each designed for
specific types of operations.
Types of Operators in Python:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison (Relational) Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity 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

= Assign value x=5

+= Add and assign x += 3 (x = x + 3)

-= Subtract and assign x -= 3 (x = x - 3)


*= Multiply and assign x *= 3 (x = x * 3)

/= Divide and assign x /= 3 (x = x / 3)

//= Floor divide and assign x //= 3

%= Modulus and assign x %= 3

**= Exponentiate and assign x **= 3

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

You might also like