Python Notes
Python Notes
1. For learning it is easy and to use: Python is easy to learn and use, even
for beginners. The syntax is plain and straightforward, almost like writing in
English.
2. Object-oriented: Python is an object-oriented programming language that
has highlights such as code reusability and measured quality. It supports
highlights such as abstraction, encapsulation, inheritance and
polymorphism.
1
complimentary. You'll be able download Python and the related libraries
and documentation from the official Python site. In expansion to
downloading, you'll too make and convey your possess modules or
libraries.
2
Python is a versatile programming language that can be used for various
applications. Some typical applications of Python include:
3
5. Desktop GUI applications: Python provides several GUI toolkits like
Tkinter, PyQt, and wxPython, allowing developers to create desktop
applications with a native look and feel.
4
• Python is an interpreted high-level programming dialect known for its
straightforwardness, flexibility and meaningfulness.
• It is simple to learn and utilize, object-oriented, interpreted, cross-platform,
has an broad standard library, is powerfully written, and supports numerous
programming standards.
• Python is free and open source and bolsters databases and GUI
programming.
• It incorporates a wide extend of applications, counting web advancement,
information science and analytics, logical computing, computerization and
scripting, and manufactured insights and machine learning.
• Its adaptability to distinctive functionalities makes it an greatly flexible
programming dialect within the program improvement industry.
QUIZ
1. Which of the following is NOT a feature of Python?
a. Cross-platform
b. Object-oriented
c. Compiled
d. Dynamically typed
Answer: c. Compiled
2. What is the advantage of Python's dynamically typed nature?
a. It makes the language more rigid
b. It allows for more excellent type safety
c. It makes the language more flexible and adaptable to changing
requirements
d. It makes the language faster
Answer: c. It makes the language more flexible and adaptable to changing
requirements
3. What is the advantage of Python's extensive standard library?
a. It makes the language faster
b. It reduces the amount of code developers need to write, saving time
and effort
5
c. It makes the language more rigid
d. It allows for more excellent type safety
Answer: b. It reduces the amount of code developers need to write, saving time
and effort
4. What are some common applications of Python?
a. Web development, data science and analytics, scientific computing,
and automation and scripting
b. Web development, machine learning, scientific computing, and
database management.
c. Web development, data science and analytics, machine learning,
and database management
d. Web development, data analysis, scientific computing, and artificial
intelligence
Answer: a. Web development, data science and analytics, scientific computing,
and automation and scripting
2.1 Identifiers
An identifier is a name given to a variable, function, class, or module. Identifiers may
consist of one or more characters and follow these rules:
❖ Identifiers can be a combination of lowercase letters (a–z), uppercase letters (A–Z), digits
(0–9), and underscores (_).
❖ Examples of valid identifiers: myCountry, other_1, good_morning.
❖ A Python identifier must begin with a letter (A–Z, a–z) or an underscore (_).
❖ An identifier cannot start with a digit but can have digits elsewhere.
(Example: 1plus is invalid, but plus1 is valid)
❖ Keywords cannot be used as identifiers.
❖ One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
❖ Identifier can be of any length.
2.2 Keywords
Keywords are a list of reserved words that have predefined meaning. Keywords are
special vocabulary and cannot be used by programmers as identifiers for variables,
functions, constants or with any identifier name. Attempting to use a keyword as an
identifier name will cause an error. The following TABLE 2.1 shows the Python keywords.
6
7
Introduction to Features and Applications of Python; Python Versions; Installation of Python;
Python Command Line mode and Python IDEs; Simple Python Program.
Python Basics: Identifiers; Keywords; Statements and Expressions; Variables; Operators;
Precedence and Association; Data Types; Indentation; Comments; Built-in Functions-
Console Input and Console Output, Type Conversions; Python Libraries; Importing Libraries
with Examples.
Python Control Flow: Types of Control Flow; Control Flow Statements- if, else, elif, while loop,
break, continue statements, for loop Statement; range () and exit () functions.
8
8. Finance & Banking – Used for risk analysis, stock market predictions, and fraud
detection.
9. Networking – Supports socket programming and network automation.
10. Cloud Computing & DevOps – Automation using Ansible, Terraform, and AWS
SDKs.
Python Versions
Python has gone through several versions, with major improvements in each.
Key Python Versions:
1. Python 1.x – Initial version (1991), mainly used for scripting.
2. Python 2.x – Introduced Unicode support, print statement, and more libraries.
o Python 2.7 was the last version before discontinuation in 2020.
3. Python 3.x – Modern Python version with improved syntax and features.
o Introduced print() as a function, f-strings, better integer division, type
hints, and async/await.
o Latest version: Python 3.12 (as of 2024).
Differences between Python 2 and Python 3
Feature Python 2 Python 3
Print print "Hello" print("Hello")
Integer Division 5/2 = 2 5/2 = 2.5
Unicode Support Strings are ASCII by default Strings are Unicode by default
Iterating over Dictionaries .iteritems() .items()
xrange() Available Removed, use range() instead
End of Life Discontinued (2020) Actively maintained
Installation of Python
Python can be installed on different operating systems like Windows, macOS, and
Linux.
Steps to Install Python
1. Download Python Installer:
o Visit the official Python website: https://www.python.org/downloads/
o Choose the latest Python 3 version.
2. Install on Windows:
o Run the downloaded .exe file.
o Check the "Add Python to PATH" option before installation.
o Click on Install Now and follow the setup instructions.
o Verify installation by running:
o python --version
3. Install on macOS:
o macOS has Python pre-installed, but it is outdated.
9
o Install the latest version using:
o brew install python
o Verify installation:
o python3 --version
4. Install on Linux:
o Use package managers like apt (for Debian-based systems) or yum (for
RedHat-based systems):
o sudo apt update
o sudo apt install python3
o Verify installation:
o python3 --version
10
Simple Python Program
Here’s a simple Python program to print "Hello, World!" and perform basic arithmetic.
# Printing a message
print("Hello, World!")
# Performing arithmetic
a = 10
b=5
sum_value = a + b
print("The sum is:", sum_value)
Explanation
1. print("Hello, World!") → Prints text on the screen.
2. a = 10, b = 5 → Assigns values to variables.
3. sum_value = a + b → Adds two numbers.
4. print("The sum is:", sum_value) → Prints the result.
Output:
Hello, World!
The sum is: 15
Python Basics
1. Identifiers
Identifiers are names given to variables, functions, classes, and objects in Python.
Rules for Identifiers:
• Can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
• Cannot start with a digit.
myVar is valid, 1stVar is invalid.
• Case-sensitive (name and Name are different).
• Cannot use keywords as identifiers (e.g., if = 10 is invalid).
• Can contain underscores (first_name, _hiddenVar).
• Naming should be meaningful ( total_score, x1).
Examples:
name = "John" # Valid
_age = 25 # Valid
1stName = "Alice" # Invalid (cannot start with digit)
if = 5 # Invalid (cannot use keyword)
2. Keywords
Python keywords are reserved words that cannot be used as identifiers.
List of Python Keywords:
import keyword
print(keyword.kwlist)
11
Sample output:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
Example Usage:
if True:
print("Hello") # "if" is a keyword
4. Variables
A variable is a container for storing data in memory.
Declaring Variables:
name = "Alice"
age = 25
price = 99.99
Dynamic Typing:
Python automatically detects the type of a variable.
x = 10 # Integer
x = "Hello" # Now it's a string
5. Operators
Operators perform operations on values and variables.
Types of Operators:
1. Arithmetic Operators: +, -, *, /, //, %, **
2. x = 10 + 3 # Addition
3. y = 10 % 3 # Modulus (remainder)
4. z = 2 ** 3 # Exponentiation (2^3 = 8)
12
5. Comparison Operators: ==, !=, >, <, >=, <=
6. print(10 > 5) # True
7. Logical Operators: and, or, not
8. print(True and False) # False
9. Assignment Operators: =, +=, -=, *=, /=
10. x = 10
11. x += 5 # x = x + 5 → 15
12. Bitwise Operators: &, |, ^, ~, <<, >>
13. print(5 & 3) # 1 (Bitwise AND)
14. Membership Operators: in, not in
15. print("a" in "apple") # True
16. Identity Operators: is, is not
17. print(10 is 10) # True
7. Data Types
Python provides different data types:
Data Type Example
int x = 10
float y = 3.14
str name = "Alice"
list numbers = [1, 2, 3]
tuple colors = ("red", "blue")
13
Data Type Example
dict person = {"name": "John"}
set fruits = {"apple", "banana"}
bool is_valid = True
8. Indentation
Python uses indentation (spaces/tabs) to define code blocks instead of {}.
Example:
if 10 > 5:
print("Indentation is required!") # Correct
# No indentation → SyntaxError
9. Comments
Comments help explain the code.
Types of Comments
1. Single-line Comment:
2. # This is a comment
3. print("Hello") # Comment at end
4. Multi-line Comment:
5. """
6. This is a
7. multi-line comment
8. """
14
11. Python Libraries
Python has many useful libraries.
Popular Python Libraries:
Library Purpose
math Mathematical functions
random Generate random numbers
datetime Work with dates & time
Os Interact with the OS
Sys System-specific functions
Json JSON data handling
pandas Data analysis
numpy Numerical computations
import random
print(random.randint(1, 10)) # Random number between 1 and 10
Conclusion
This guide covers Python Basics, including variables, operators, statements, data
types, functions, and libraries.
15
Python Libraries
Python libraries are collections of modules that provide pre-written code for performing
various tasks.
• Standard Libraries: Built-in modules available in Python (e.g., math, datetime,
os, sys)
• Third-Party Libraries: External libraries installed using pip (e.g., numpy, pandas,
matplotlib)
16
• continue: Skips the current iteration and moves to the next.
for num in range(1, 6):
if num == 3:
break # Stops at 3
print(num)
This concludes the detailed notes on Type Conversions, Python Libraries, Importing
Libraries, and Control Flow in Python.
17