Unit 1 - Introduction To Python Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

Unit 1 : Introduction to Python Programming

Introduction to the Python programming language, features, installations, useful


editors (Pycharm, Sublime text, etc..), Introduction to Jupyter notebook and Google colab
tool. Keywords, Identifiers, Literals, Operators, Punctuators in Python. Python
interpreter and interactive mode; values and types: int, float, Boolean, string, and list;
variables, expressions, statements, precedence of operators, comments; modules and
functions, function definition and use, flow of execution, parameters and arguments. Strings:
string slices, immutability, string functions and methods, string module.

Some Important Links -

To Install Pycharm - https://youtu.be/MJJpL9EmJBs?si=gcLyvHuN4LkrpUvm


To Install Jupyter Notebook –
Google Colab - https://youtu.be/RLYoEyIHL6A?si=E2O3pVvsHvDqsMkd

Python is a high-level, interpreted programming language known for its simplicity and
readability. Created by Guido van Rossum and first released in 1991, Python's design
philosophy emphasizes code readability and simplicity, allowing programmers to express
concepts in fewer lines of code compared to languages like C++ or Java.

Key Features of Python

1. Readability and Simplicity: Python's syntax is clear and concise, making it an


excellent language for beginners. Its use of indentation to define code blocks instead
of curly braces or keywords makes the code visually appealing and easy to
understand.
2. Interpreted Language: Python is an interpreted language, meaning that the code is
executed line by line, which makes debugging easier and allows for dynamic typing.
3. Dynamic Typing: In Python, you don't need to declare the type of a variable. This
allows for more flexibility, but it also requires the programmer to be mindful of
potential type-related errors.
4. Extensive Standard Library: Python has a rich standard library that provides
modules and functions for various tasks, such as file I/O, system calls, web
development, and data manipulation, reducing the need to write code from scratch.
5. Object-Oriented: Python supports object-oriented programming (OOP) concepts
such as classes and inheritance, allowing for the creation of reusable and modular
code.
6. Cross-Platform Compatibility: Python is available on multiple platforms, including
Windows, macOS, and various distributions of Linux, making it a versatile choice for
developers working in different environments.
7. Large Community and Ecosystem: Python has a vast and active community,
contributing to a wealth of third-party libraries and frameworks. This community
support makes it easier to find solutions to problems, access documentation, and
collaborate on projects.
8. Integration Capabilities: Python can easily integrate with other languages and
technologies, such as C/C++, Java, and .NET, making it a valuable tool for extending
existing applications or creating new ones that leverage multiple technologies.
9. Frameworks and Libraries: Python boasts numerous frameworks and libraries that
simplify development in various domains. Some popular examples include:
o Web Development: Django, Flask
o Data Science and Machine Learning: Pandas, NumPy, SciPy, scikit-learn,
TensorFlow, PyTorch
o GUI Development: Tkinter, PyQt, Kivy
o Automation and Scripting: Selenium, Beautiful Soup
10. Educational Use: Python is widely used as a teaching language due to its simplicity
and the ease with which beginners can pick it up. Many educational institutions use
Python in their introductory programming courses.

Applications of Python

 Web Development: Building web applications and services using frameworks like
Django and Flask.
 Data Science and Analytics: Analyzing data, performing statistical analysis, and
building machine learning models.
 Artificial Intelligence and Machine Learning: Developing AI and ML algorithms
using libraries like TensorFlow and PyTorch.
 Automation and Scripting: Automating repetitive tasks and writing scripts for
system administration.
 Scientific Computing: Conducting complex scientific calculations and simulations
using libraries like SciPy and NumPy.
 Game Development: Creating simple games and interactive applications.
 Network Programming: Building network applications and protocols.
 Desktop Applications: Developing graphical user interface (GUI) applications.

Python's versatility, readability, and extensive ecosystem make it a powerful tool for a wide
range of applications, from simple scripting to complex machine learning models. Its ongoing
development and community support ensure that it remains a relevant and valuable language
for both beginners and experienced programmers.
Keywords in Python

 Keywords in Python are reserved words that have specific meanings and functions in the
language. These words cannot be used as identifiers (names of variables, functions, classes,
etc.) because they are part of the syntax.
 Python keywords are case-sensitive and must be used exactly as they are defined.

Explanation of Common Python Keywords

1. False, True, None:


o False and True are Boolean values.
o None represents the absence of a value.
1. is_active = True
2. is_deleted = False
3. data = None
2. and, or, not:
o Logical operators used for combining conditional statements.

if x > 0 and y > 0:


print("Both x and y are positive")

3. as:
o Used to create an alias while importing a module.

import numpy as np

try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"An error occurred: {e}")

4. break, continue:
o Control flow statements to exit or skip the current iteration of a loop.

for i in range(10):
if i == 5:
break # Exit the loop
print(i)

for number in range(10):


if number % 2 == 0:
continue
print(number)

5. class:
o Used to define a new class.

class MyClass:
def __init__(self, value):
self.value = value
6. def:
o Used to define a new function.

def my_function():
print("Hello, World!")

Here is a list of the keywords in Python (as of Python 3.10):

1. False
2. None
3. True
4. and
5. as
6. assert
7. async
8. await
9. break
10. class
11. continue
12. def
13. del
14. elif
15. else
16. except
17. finally
18. for
19. from
20. global
21. if
22. import
23. in
24. is
25. lambda
26. nonlocal
27. not
28. or
29. pass
30. raise
31. return
32. try
33. while
34. with
35. yield
Identifiers in Python

 Identifiers in Python are names used to identify variables, functions, classes, modules,
and other objects.
 An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores, and digits (0 to 9).

Rules for Naming Identifiers

1. Case Sensitivity: Identifiers are case-sensitive. For example, myVariable


and myvariable are two different identifiers.
2. Allowed Characters: Identifiers can contain letters (A-Z, a-z), digits (0-9),
and underscores (_).
3. Start with a Letter or Underscore: Identifiers must start with a letter or
an underscore (_). They cannot start with a digit.
4. No Spaces or Special Characters: Identifiers cannot contain spaces or
special characters like !, @, #, $, etc.
5. Avoid Python Keywords: Identifiers should not be Python keywords
(reserved words). For example, if, for, while, etc., cannot be used as
identifiers.

Best Practices for Naming Identifiers

1. Descriptive Names: Use meaningful and descriptive names for identifiers to make
your code more readable.

# Good
total_sum = 100
user_name = "Alice"

# Bad
x = 100
y = "Alice"

2. Follow Naming Conventions:


o Variable Names: Use lowercase letters and underscores to
separate words (snake_case).

user_age = 25
total_price = 100.5

o Function Names: Use lowercase letters and underscores to


separate words (snake_case).

def calculate_area(radius):
return 3.14 * radius * radius

o Class Names: Use uppercase letters for each word (CamelCase).

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

3. Avoid Single Character Names: Except for variables with a limited scope like loop
counters.

for i in range(10):
print(i)

4. Consistency: Be consistent with your naming conventions throughout your codebase.

Examples of Valid Identifiers


variable = 10
_variable = 20
var1 = 30
variable_name = 40
VariableName = 50

Examples of Invalid Identifiers


1variable = 10 # Starts with a digit
variable-name = 20 # Contains a hyphen
variable name = 30 # Contains a space
if = 40 # Python keyword

Literals

Literals in Python are fixed values that are used to represent data directly in the code. They
are the simplest form of data in Python and can be of various types, such as numbers, strings,
and booleans.

Types of Literals

1. Numeric Literals
2. String Literals
3. Boolean Literals
4. Special Literals
5. Collection Literals

1. Numeric Literals

Numeric literals are used to represent numbers. They can be of three types: integers, floating-
point numbers, and complex numbers.

 Integer Literals: Whole numbers without a fractional part.

decimal = 10
binary = 0b1010 # Binary literal
octal = 0o12 # Octal literal
hexadecimal = 0xA # Hexadecimal literal
 Floating-Point Literals: Numbers with a fractional part.

float_num = 10.5
float_exp = 1.5e2 # Scientific notation (1.5 * 10^2)

 Complex Literals: Numbers with a real and an imaginary part.

complex_num = 3 + 4j

2. String Literals

String literals are sequences of characters enclosed in single, double, triple single, or triple
double quotes.

 Single-line Strings:

single_quote_str = 'Hello'
double_quote_str = "World"

 Multi-line Strings:

triple_single_quote_str = '''This is a
multi-line string'''

triple_double_quote_str = """This is also a


multi-line string"""

3. Boolean Literals

Boolean literals represent the truth values True and False.

is_true = True
is_false = False

4. Special Literals

Python has one special literal, None, which represents the absence of a value or a null value.

nothing = None

5. Collection Literals

Collection literals are used to represent collections of items. These include lists, tuples,
dictionaries, and sets.

 List Literals:

list_literal = [1, 2, 3, 4]

 Tuple Literals:
tuple_literal = (1, 2, 3, 4)

 Dictionary Literals:

dict_literal = {'key1': 'value1', 'key2': 'value2'}

 Set Literals:

set_literal = {1, 2, 3, 4}

Examples

Here are some examples to illustrate the use of different literals in Python:

# Numeric Literals
integer_literal = 42
print(integer_literal)
float_literal = 3.14
complex_literal = 2 + 3j

# String Literals
single_line_str = 'Hello, World!'
multi_line_str = """This is a
multi-line string"""

# Boolean Literals
true_literal = True
false_literal = False

# Special Literal
none_literal = None

# Collection Literals
list_literal = [1, 2, 3, 4]
tuple_literal = (1, 2, 3, 4)
dict_literal = {'name': 'Alice', 'age': 30}
set_literal = {1, 2, 3, 4}

Understanding literals is fundamental for working with data in Python, as they are the
building blocks for creating variables and working with data in your programs.

Operators in Python

Operators are special symbols that perform operations on variables and values. Python
supports a variety of operators, each serving different purposes. They can be classified into
several categories:

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

Operat Exampl
Description
or e

+ Addition a + b

- Subtraction a - b

Multiplicatio
* a * b
n

/ Division a / b

% Modulus a % b

Exponentiati
** a ** b
on

Floor
// a // b
Division

2. Comparison Operators

Comparison operators are used to compare two values and return a boolean result.

Operat Exampl
Description
or e

== Equal to a == b

!= Not equal to a != b

> Greater than a > b

< Less than a < b

Greater than or
>= a >= b
equal to

Less than or equal


<= a <= b
to
3. Logical Operators

Logical operators are used to combine conditional statements.

Operat Descripti Exampl


or on e

Logical
and a and b
AND

or Logical OR a or b

Logical
not not a
NOT

4. Bitwise Operators

Bitwise operators perform bit-level operations on binary numbers.

Operat Exampl
Description
or e

& Bitwise AND a & b

` Bitwise OR a ` b

^ Bitwise XOR a ^ b

~ Bitwise NOT ~a

Bitwise left
<< a << 1
shift

Bitwise right
>> a >> 1
shift

Bitwise right shift


Example
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

Bitwise left shift


Example
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
5. Assignment Operators

Assignment operators are used to assign values to variables.

Operat
Description Example
or

= Assign a = 5

+= Add and assign a += 5

-= Subtract and assign a -= 5

*= Multiply and assign a *= 5

/= Divide and assign a /= 5

%= Modulus and assign a %= 5

**= Exponent and assign a **= 5

//= Floor divide and assign a //= 5

&= Bitwise AND and assign a &= 5

Bitwise OR and
` =`
assign

^= Bitwise XOR and assign a ^= 5

Bitwise right shift and


>>= a >>= 5
assign

Bitwise left shift and


<<= a <<= 5
assign

6. Membership Operators

Membership operators are used to test if a sequence contains a value.

Operat
Description Example
or

Returns True if a sequence contains a specified


in x in y
value

not in Returns True if a sequence does not contain a x not in y


Operat
Description Example
or

specified value

7. Identity Operators

Identity operators are used to compare the memory locations of two objects.

Operat
Description Example
or

Returns True if both variables are the same


is x is y
object

Returns True if both variables are not the


is not x is not y
same object

Examples of Operators in Use

# Arithmetic Operators

a = 10
b = 3

print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus
print(a ** b) # Exponentiation
print(a // b) # Floor Division

# Comparison Operators
print(a == b) # Equal to
print(a != b) # Not equal to
print(a > b) # Greater than
print(a < b) # Less than
print(a >= b) # Greater than or equal to
print(a <= b) # Less than or equal to

# Logical Operators
print(a > 5 and b < 5) # Logical AND
print(a > 5 or b > 5) # Logical OR
print(not(a > 5)) # Logical NOT

# Bitwise Operators
print(a & b) # Bitwise AND
print(a | b) # Bitwise OR
print(a ^ b) # Bitwise XOR
print(~a) # Bitwise NOT
print(a << 1) # Bitwise left shift
print(a >> 1) # Bitwise right shift
# Assignment Operators
c = 10
c += 5
print(c) # Add and assign

# Membership Operators
my_list = [1, 2, 3, 4]
print(2 in my_list) # True
print(5 not in my_list) # True

# Identity Operators
x = 5
y = 5
print(x is y) # True
print(x is not y) # False

Understanding and using these operators correctly allows you to perform a wide variety of
operations in Python, making your code more functional and expressive.

Punctuators in Python

In Python, punctuators (or punctuation characters) are special symbols used in the syntax of
the language to perform various operations. Here’s an overview of the most common
punctuators in Python and their usage:

1. Parentheses ()

 Function Calls: print("Hello, World!")


 Grouping: result = (a + b) * c
 Tuples: my_tuple = (1, 2, 3)

2. Square Brackets []

 Lists: my_list = [1, 2, 3]


 Indexing: my_list[0]
 Slicing: my_list[1:3]

3. Curly Brackets {}

 Dictionaries: my_dict = {"key": "value"}


 Sets: my_set = {1, 2, 3}

4. Colon :

 Dictionary Key-Value Pairs: {"key": "value"}


 Function Definitions: def my_function():
 Conditional Statements: if condition:

5. Comma ,

 Separating Items in Lists/Tuples/Dictionaries: [1, 2, 3], (1, 2, 3), {"key1":


"value1", "key2": "value2"}
 Function Arguments: def my_function(arg1, arg2):

6. Dot .

 Attribute Access: object.attribute


 Method Calls: object.method()
 Module Import: import module.submodule

9.Backslash \

 Line Continuation: long_line = "This is a very long line of code that


we " \ "need to split into multiple lines."

10. Quotation Marks " and '

 String Literals: "Hello", 'World'

11. Triple Quotes """ and '''

 Multi-line Strings: """This is a multi-line string.""", '''This is also a


multi-line string.'''

These punctuators are essential to writing syntactically correct and functional Python code.

Python Interpreter

The Python interpreter and interactive mode are essential tools for writing and testing Python
code. Here’s a detailed look at each:

The Python interpreter is a program that reads and executes Python code. It can execute code
from a script (a .py file) or interactively. When you run a Python script, the interpreter reads
the file, compiles it to bytecode, and then executes the bytecode on the Python virtual
machine (PVM).

Running the Python Interpreter

To run a Python script using the interpreter:

1. Save your Python code in a file with a .py extension (e.g., script.py).
2. Open a terminal or command prompt.
3. Run the script by typing:

python script.py

or

python3 script.py

(depending on your Python installation).


Interactive Mode

Interactive mode allows you to interact directly with the Python interpreter. You can type and
execute Python code one line at a time, which is useful for testing, debugging, and
experimenting with code snippets.

Starting Interactive Mode

To start the Python interpreter in interactive mode:

1. Open a terminal or command prompt.


2. Type python or python3 and press Enter.

python

or

python3

You will see a prompt (usually >>>) indicating that you are in interactive mode.

Using Interactive Mode

In interactive mode, you can type Python commands and see immediate results. For example:

>>> print("Hello, World!")


Hello, World!
>>> a = 10
>>> b = 20
>>> a + b
30
>>> def greet(name):
... return f"Hello, {name}!"
...
>>> greet("Alice")
'Hello, Alice!'

Features of Interactive Mode

1. Immediate Feedback: You can see the results of expressions immediately after
typing them.
2. Testing and Debugging: It’s convenient for quickly testing small code snippets or
debugging.
3. Built-in Functions and Libraries: You have access to all built-in functions and
standard libraries.
4. Help and Documentation: You can use the help() function to get information about
modules, functions, and objects.

>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout,
flush=False)
Prints the values to a stream, or to sys.stdout by default.

5. Exiting Interactive Mode: To exit, you can type exit() or use the shortcut Ctrl+D
(on Unix/Linux/Mac) or Ctrl+Z followed by Enter (on Windows).

Integrated Development Environments (IDEs)

While the Python interactive mode is very useful for quick tasks, many developers use
Integrated Development Environments (IDEs) for more extensive development work. Popular
Python IDEs include:

 PyCharm: A full-featured IDE with many tools for professional


development.
 VS Code: A lightweight but powerful editor with Python support.
 Jupyter Notebook: An interactive environment particularly popular in
data science and machine learning.

These environments often include interactive consoles, advanced debugging, code


completion, and other features that enhance productivity.

n Python, values and types are fundamental concepts. Here's an overview:

Values

Values are the core data that programs manipulate. Examples of values are numbers and
strings. Values can be assigned to variables and passed to functions.

Types

Types define the kind of data a value represents and what operations can be performed on it.
Python has several built-in data types, each with specific characteristics and uses.

Common Built-in Data Types

1. Numeric Types

 Integers (int)
o Whole numbers, positive or negative, without a decimal point.
o Examples: 1, 42, -7
 Floating-point numbers (float)
o Numbers with a decimal point.
o Examples: 3.14, -0.001, 2.0
 Complex numbers (complex)
o Numbers with a real and an imaginary part.
o Examples: 3 + 4j, -1 - 2j

2. Sequence Types

 Strings (str)
o Ordered sequences of characters.
o Enclosed in single quotes ('), double quotes ("), or triple quotes ('''
or """).
o Examples: 'hello', "world", """Python"""
 Lists (list)
o Ordered, mutable sequences of elements.
o Enclosed in square brackets ([]).
o Examples: [1, 2, 3], ['a', 'b', 'c']
 Tuples (tuple)
o Ordered, immutable sequences of elements.
o Enclosed in parentheses (()).
o Examples: (1, 2, 3), ('a', 'b', 'c')

3. Mapping Types

 Dictionaries (dict)
o Unordered collections of key-value pairs.
o Enclosed in curly braces ({}).
o Examples: {'name': 'Alice', 'age': 30}, {1: 'one', 2: 'two'}

4. Boolean Type

 Booleans (bool)
o Represents truth values.
o Only two possible values: True and False.

is_active = True
is_logged_in = False

6. None Type

 None (NoneType)
o Represents the absence of a value or a null value.
o Only one possible value: None.

result = None

Type Checking and Conversion

Type Checking

You can check the type of a value using the type() function:

python
Copy code
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type((1, 2, 3))) # <class 'tuple'>
print(type({'a': 1})) # <class 'dict'>
print(type({1, 2, 3})) # <class 'set'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>

Type Conversion

You can convert values from one type to another using built-in functions like int(),
float(), str(), list(), tuple(), set(), dict(), and bool():

python
Copy code
x = 42
y = float(x) # Converts int to float
print(y) # 42.0

s = "123"
n = int(s) # Converts str to int
print(n) # 123

lst = [1, 2, 3]
t = tuple(lst) # Converts list to tuple
print(t) # (1, 2, 3)

b = bool(1) # Converts int to bool


print(b) # True

Understanding values and types is crucial for effective programming in Python, as it ensures
correct data manipulation and utilization of Python's extensive features and capabilities.

Variables

Variables in Python are used to store data values. They act as placeholders for data that can
be manipulated throughout the program. Here’s a detailed look at variables in Python:

Declaring and Assigning Variables

In Python, you declare a variable by assigning it a value using the = operator. There is no
need to declare the type of the variable explicitly, as Python is a dynamically typed language.

python
Copy code
# Integer variable
age = 25

# Floating-point variable
pi = 3.14

# String variable
name = "Alice"

# Boolean variable
is_student = True

# List variable
numbers = [1, 2, 3, 4, 5]

# Dictionary variable
person = {"name": "Alice", "age": 25}
Variable Naming Rules

 Variable names must start with a letter (a-z, A-Z) or an underscore ( _).
 The rest of the name can contain letters, digits (0-9), and underscores.
 Variable names are case-sensitive (myVar and myvar are different
variables).
 Variable names should not be Python reserved keywords (e.g., for, while,
if, else, etc.).

Examples of Valid and Invalid Variable Names


python
Copy code
# Valid variable names
my_var = 10
var2 = 20
_var = 30
Var = 40

# Invalid variable names


2var = 50 # Cannot start with a digit
my-var = 60 # Cannot contain hyphen
my var = 70 # Cannot contain spaces

Reassigning Variables

You can change the value of a variable by assigning it a new value. The type of the variable
can also change because Python is dynamically typed.

python
Copy code
x = 5
print(x) # Output: 5

x = "Hello"
print(x) # Output: Hello

x = [1, 2, 3]
print(x) # Output: [1, 2, 3]

Multiple Assignments

You can assign values to multiple variables in a single line.

python
Copy code
a, b, c = 1, 2, 3
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3

# Assigning the same value to multiple variables


x = y = z = 10
print(x) # Output: 10
print(y) # Output: 10
print(z) # Output: 10
Swapping Variables

Swapping the values of two variables can be done easily without needing a temporary
variable.

python
Copy code
a = 5
b = 10

# Swapping values
a, b = b, a

print(a) # Output: 10
print(b) # Output: 5

Variable Scope

The scope of a variable determines where it can be accessed within the code.

 Global Scope: Variables declared outside of any function are in the global
scope and can be accessed anywhere in the code.
 Local Scope: Variables declared within a function are in the local scope
and can only be accessed within that function.

Global Variables
python
Copy code
x = "global"

def my_function():
print(x) # Accesses the global variable

my_function() # Output: global


print(x) # Output: global
Local Variables
python
Copy code
def my_function():
y = "local"
print(y) # Accesses the local variable

my_function() # Output: local


# print(y) # This will cause an error because y is not defined
outside the function
Global Keyword

To modify a global variable inside a function, use the global keyword.

python
Copy code
x = "global"

def my_function():
global x
x = "local"
print(x) # Modifies the global variable

my_function() # Output: local


print(x) # Output: local

Constants

Python doesn’t have built-in constant types, but by convention, variables that should not
change are written in uppercase.

python
Copy code
PI = 3.14159
GRAVITY = 9.81

While Python allows reassignment of these variables, by convention, they are treated as
constants.

Type Annotations

In Python 3.5 and later, you can use type annotations to specify the expected type of a
variable. This is mainly for documentation and doesn't affect the execution of the code.

python
Copy code
age: int = 25
name: str = "Alice"
pi: float = 3.14

Understanding variables is essential for writing efficient and readable Python code. Proper
naming, scoping, and usage can significantly improve code maintainability and clarity.

Expressions

n Python, expressions are combinations of values, variables, operators, and function calls that
are evaluated to produce another value. Expressions are fundamental to any programming
language, as they form the building blocks of programs.

Types of Expressions

1. Arithmetic Expressions

Arithmetic expressions use arithmetic operators to perform mathematical calculations.

python
Copy code
# Addition
result = 5 + 3 # result is 8

# Subtraction
result = 10 - 4 # result is 6

# Multiplication
result = 7 * 6 # result is 42

# Division
result = 8 / 2 # result is 4.0

# Floor Division
result = 9 // 2 # result is 4

# Modulus
result = 10 % 3 # result is 1

# Exponentiation
result = 2 ** 3 # result is 8
2. Comparison Expressions

Comparison expressions use comparison operators to compare two values and return a
boolean value (True or False).

python
Copy code
# Equal to
result = (5 == 5) # result is True

# Not equal to
result = (5 != 4) # result is True

# Greater than
result = (7 > 3) # result is True

# Less than
result = (3 < 7) # result is True

# Greater than or equal to


result = (5 >= 5) # result is True

# Less than or equal to


result = (3 <= 7) # result is True
3. Logical Expressions

Logical expressions use logical operators to combine multiple boolean expressions.

python
Copy code
# Logical AND
result = (5 > 3) and (7 > 5) # result is True

# Logical OR
result = (5 > 3) or (7 < 5) # result is True

# Logical NOT
result = not (5 > 3) # result is False
result = 5 << 1 # result is 10 (binary 101 << 1 is 1010)

Compound Expressions

Expressions can be combined to form more complex expressions.


python
Copy code
# Combined arithmetic and comparison expression
result = (5 + 3) * 2 > 10 # result is True

# Combined logical expression


result = (5 > 3) and (7 < 10) or (5 == 5) # result is True

Importance of Expressions

Expressions are essential for creating logic and functionality in programs. They are used in
assignments, conditionals, loops, function arguments, and many other constructs.
Understanding and effectively using expressions is key to writing efficient and readable
Python code.

Statements
In Python, statements are instructions that the Python interpreter can execute. Unlike
expressions, which evaluate to a value, statements perform actions. Here's an overview of the
different types of statements in Python:

Types of Statements

1. Assignment Statements

Assignment statements assign values to variables.

python
Copy code
x = 5
y = 10
name = "Alice"
2. Expression Statements

Expression statements evaluate expressions and then discard the result. They are often used to
call functions or methods.

python
Copy code
print("Hello, World!")
3. Conditional Statements

Conditional statements perform actions based on conditions. They include if, elif, and
else.

python
Copy code
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
4. Loop Statements

Loop statements repeatedly execute a block of code. They include for and while loops.

 For Loop

python
Copy code
for i in range(5):
print(i)

 While Loop

python
Copy code
count = 0
while count < 5:
print(count)
count += 1
5. Break, Continue, and Pass Statements

 Break: Exits the nearest enclosing loop.

python
Copy code
for i in range(10):
if i == 5:
break
print(i) # Output: 0, 1, 2, 3, 4

 Continue: Skips the rest of the current loop iteration and continues with the next
iteration.

python
Copy code
for i in range(10):
if i % 2 == 0:
continue
print(i) # Output: 1, 3, 5, 7, 9

Function definition statements define a function using the def keyword.

python
Copy code
def greet(name):
print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!


Return Statements

Return statements are used in functions to return a value to the caller.

python
Copy code
def add(a, b):
return a + b

result = add(5, 3) # result is 8


8. Import Statements

Import statements are used to import modules and make their functions and classes available
in your code.

python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0

from math import pi


print(pi) # Output: 3.141592653589793

Importance of Statements

Statements are the building blocks of Python programs. They control the flow of execution,
perform actions, and define the structure of the code. Understanding and using statements
effectively is crucial for writing functional and efficient Python programs.

Precedence of Operators

In Python, operator precedence determines the order in which operations are performed in an
expression. Operators with higher precedence are evaluated before operators with lower
precedence. If operators have the same precedence, their associativity determines the order of
evaluation.

Operator Precedence Table

Here's a table of Python operators, listed from highest precedence to lowest precedence:

1. Parentheses: ()
2. Exponentiation: **
3. Unary plus, minus, and bitwise NOT: +x, -x, ~x
4. Multiplication, division, floor division, and modulus: *, /, //, %
5. Addition and subtraction: +, -
6. Bitwise shifts: <<, >>
7. Bitwise AND: &
8. Bitwise XOR: ^
9. Bitwise OR: |
10. Comparison operators: ==, !=, >, >=, <, <=, is, is not, in, not in
11. Boolean NOT: not x
12. Boolean AND: and
13. Boolean OR: or
14. Assignment operators: =, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, >>=, <<=
15. Conditional expressions: if elser
16. Lambda expressions: lambda

Comments in Python

In Python, comments are used to annotate code with explanations, notes, or reminders.
Comments are ignored by the Python interpreter during execution and are purely for human
readers. They help improve code readability, document functionality, and explain complex
logic.

Types of Comments

1. Single-Line Comments

Single-line comments begin with the # character and continue until the end of the line. They
are typically used for short comments or annotations.

python
Copy code
# This is a single-line comment
x = 5 # Assigning the value 5 to variable x
2. Multi-Line Comments

Python does not have a built-in syntax specifically for multi-line comments like some other
programming languages. However, you can use triple quotes (""" or ''') to create multi-line
string literals, which Python treats as comments if not assigned to a variable or used in an
expression.

python
Copy code
"""
This is a multi-line comment.
It can span multiple lines.
"""
3. Docstrings

Docstrings are similar to multi-line comments but are used to document functions, classes,
methods, and modules. They are enclosed in triple quotes and can span multiple lines. Unlike
regular comments, docstrings are accessible via Python's __doc__ attribute and are used by
documentation generation tools.

python
Copy code
def add(a, b):
"""
This function adds two numbers.

Parameters:
a (int or float): First number
b (int or float): Second number

Returns:
int or float: Sum of a and b
"""
return a + b

Best Practices for Using Comments

 Use Comments Sparingly: Code should be self-explanatory as much as


possible. Use comments to explain why, not what.
 Be Clear and Concise: Write clear and concise comments that add value
to understanding the code.
 Update Comments: Keep comments updated with changes to the code
to avoid misleading information.
 Use Docstrings: Document functions, classes, methods, and modules
with meaningful docstrings.
 Avoid Obvious Comments: Avoid comments that simply restate the
code. Focus on explaining logic or intentions.

Example Usage
python
Copy code
# Calculate the area of a rectangle
length = 10 # Length of the rectangle
width = 5 # Width of the rectangle

# Using a formula to calculate area


area = length * width

"""
This block of code is used to calculate the area
of a rectangle. It multiplies the length and width
variables to get the area. It then stores the result
in the area variable.
"""

def greet(name):
"""
This function greets a person by printing a message.

Parameters:
name (str): The name of the person to greet.

Returns:
None
"""
print(f"Hello, {name}!")

# Calling the greet function


greet("Alice") # Output: Hello, Alice!

Summary
Comments in Python are invaluable for documenting code, explaining logic, and improving
readability. By using comments effectively, you can make your code easier to understand for
both yourself and others who may read or maintain it in the future.

Modules in Python

Modules are files containing Python code. They can define functions, classes, and variables.
Python modules are saved with the extension .py.

 Importing a Module: You can use the import statement to bring a module into your
script.

python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0

 Importing Specific Functions/Variables: You can also import specific parts of a


module.

from math import pi, sqrt


print(pi) # Output: 3.141592653589793
print(sqrt(16)) # Output: 4.0

 Creating Your Own Module: Simply create a .py file with your functions and
classes.

# my_module.py
def add(a, b):
return a + b

# main.py
import my_module
print(my_module.add(2, 3)) # Output: 5

Functions in Python

Functions are blocks of reusable code that perform a specific task. They help in organizing
code into manageable sections.

Function Definition and Use

 Defining a Function:

def greet(name):
"""This function greets a person with their name."""
print(f"Hello, {name}!")

 Using a Function (Calling a Function):

greet("Alice") # Output: Hello, Alice!


Flow of Execution

The flow of execution refers to the order in which statements are executed in a script. For
functions, the flow of execution is as follows:

1. Python starts execution from the top of the script.


2. When it encounters a function definition, it remembers the function name
but doesn't execute the function body.
3. When the function is called, Python jumps to the function body, executes
it, and then returns to the point where the function was called.

Example:

def print_message():
print("Hello, World!")

print("Before function call")


print_message() # This is where the function is called
print("After function call")

Output:

r
Copy code
Before function call
Hello, World!
After function call
Parameters and Arguments

 Parameters are the variables listed inside the parentheses in the function definition.

def add(a, b): # a and b are parameters


return a + b

 Arguments are the values passed to the function when it is called.

result = add(3, 4) # 3 and 4 are arguments


print(result) # Output: 7

Types of Arguments

1. Positional Arguments:
o Arguments passed to a function in the correct positional order.

def subtract(a, b):


return a - b

print(subtract(10, 3)) # Output: 7

2. Keyword Arguments:
o Arguments passed to a function by explicitly stating the parameter
name.

def divide(a, b):


return a / b

print(divide(a=10, b=2)) # Output: 5.0

3. Default Arguments:
o Parameters that assume a default value if no argument is provided.

def greet(name, msg="Good morning!"):


print(f"Hello, {name}, {msg}")

greet("Bob") # Output: Hello, Bob, Good morning!


greet("Alice", "How are you?") # Output: Hello, Alice, How are
you?

These concepts form the foundation of Python programming, enabling you to write modular,
reusable, and organized code.

Strings
Strings are Arrays

a = "Hello, World!"
print(a[1])

for x in "banana":
print(x)

a = "Hello, World!"
print(len(a))

txt = "The best things in life are free!"


print("free" in txt)

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

b = "Hello, World!"
print(b[2:5])

b = "Hello, World!"
print(b[2:])

b = "Hello, World!"
print(b[-5:-2])

1. String Slices

String slicing in Python allows you to access a part of a string. The syntax for slicing is:

python
Copy code
string[start:end:step]

 start: The starting index of the slice.


 end: The ending index (non-inclusive).
 step: The step size or the interval between indices.

Examples:

python
Copy code
s = "Hello, World!"
print(s[0:5]) # Output: Hello
print(s[7:]) # Output: World!
print(s[:5]) # Output: Hello
print(s[::2]) # Output: Hlo ol!
print(s[::-1]) # Output: !dlroW ,olleH

2. Immutability

In Python, strings are immutable. This means that once a string is created, it cannot be
changed. Any operation that modifies a string will create a new string.

Examples:

python
Copy code
s = "Hello"
s[0] = 'h' # This will raise a TypeError

Instead, you can create a new string:

python
Copy code
s = "Hello"
s = 'h' + s[1:] # Output: 'hello'

3. String Functions and Methods

Python provides various built-in methods to work with strings. Here are some commonly
used string methods:

 str.upper(): Converts all characters to uppercase.


 str.lower(): Converts all characters to lowercase.
 str.capitalize(): Capitalizes the first character of the string.
 str.title(): Capitalizes the first character of each word.
 str.strip(): Removes leading and trailing whitespaces.
 str.split(separator): Splits the string into a list based on the separator.
 str.join(iterable): Joins elements of an iterable with the string as a separator.
 str.find(substring): Returns the index of the first occurrence of the substring.
 str.replace(old, new): Replaces occurrences of a substring with another
substring.
Examples:

python
Copy code
s = " Hello, World! "
print(s.upper()) # Output: " HELLO, WORLD! "
print(s.lower()) # Output: " hello, world! "
print(s.strip()) # Output: "Hello, World!"
print(s.split(',')) # Output: [' Hello', ' World! ']
print("-".join(['a', 'b', 'c'])) # Output: "a-b-c"
print(s.find("World")) # Output: 10
print(s.replace("World", "Universe")) # Output: " Hello, Universe! "

4. String Module

The string module in Python provides additional functions and constants to work with
strings. Some commonly used constants include:

 string.ascii_letters: Concatenation of ascii_lowercase and


ascii_uppercase.
 string.ascii_lowercase: String of lowercase letters.
 string.ascii_uppercase: String of uppercase letters.
 string.digits: String of digits (0-9).
 string.punctuation: String of punctuation characters.

Examples:

python
Copy code
import string

print(string.ascii_letters) # Output:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(string.digits) # Output: '0123456789'
print(string.punctuation) # Output: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

These aspects of strings in Python allow for versatile and powerful manipulation and usage of
string data. If you have any specific questions or need further details on any of these topics,
feel free to ask!

You might also like