Python 1st Unit Notes (Introducation To Python Programming)
Python 1st Unit Notes (Introducation To Python Programming)
Unit-1
INTRODUCTION TO PYTHON PROGRAMMING
Python interpreter is a program that allows you to execute Python code. It reads the code line by line, interprets it, and executes
the instructions. The Python interpreter can be run in two modes: interactive mode and script mode.
1. Interactive mode:
Interactive mode is a convenient way to experiment with Python code, try out small snippets, and get immediate
results. When you run the Python interpreter without providing a script file as an argument, it starts in interactive mode.
In interactive mode, you can type Python code directly into the interpreter prompt, and it will execute the code
immediately. You can see the output of your code immediately after hitting the Enter key. It is a useful mode for testing and
exploring Python features.
To start the Python interpreter in interactive mode, open your command prompt or terminal and type ‘python’ or
‘python3’ ,depending on your Python installation. This will launch the interpreter, and you can start typing Python code.
You can now start entering Python code and see the results immediately.
Python Programming
2. Script mode:
Script mode is used when you have a Python script saved in a file with a ‘.py’ extension, and you want to execute the
entire script from start to finish. In script mode, the Python interpreter reads the code from the script file, executes it line by line, and
produces the output.
To run a Python script in script mode, you need to provide the script file as an argument to the Python interpreter. Open
your command prompt or terminal, navigate to the directory where your Python script is located, and type the following command:
Replace `script.py` with the actual name of your Python script file. The interpreter will execute the code in the script and
display the output or perform any other actions specified in the script.
For example, if you have a script file named `hello.py` with the following code:
Running `python hello.py` in the terminal will execute the script and print "Hello, World!" as the output.
Both interactive mode and script mode are useful in different scenarios. Interactive mode allows you to quickly test code snippets and
interactively explore Python features, while script mode is used for running larger programs and executing Python scripts stored in files.
Python Programming
✓ Values and types variables, expressions, statements, tuple assignment, Order of operations, comments,
debugging
In Python, variables are used to store values that can be of different types. The types of variables in Python include:
1.Numeric types:
a. int (integer): represents whole numbers, e.g., 5, -3, 0.
b. float (floating-point): represents decimal numbers, e.g., 3.14, -0.5, 2.0.
2.String type:
a. str (string): represents a sequence of characters enclosed in quotes, e.g., "Hello", 'Python’.
3.Boolean type:
a. bool (boolean): represents either True or False, useful for conditions and logical operations.
Python Programming
Expressions
Expressions in Python are combinations of values, variables, and operators that evaluate to a single value.
For example:
Statements
Statements are lines of code that perform an action or assignment. In Python, each statement typically ends with a newline character.
For example:
Tuple assignment
Tuple assignment is a way to assign multiple values to multiple variables simultaneously. It allows you to unpack a tuple into individual
variables.
For example:
Python Programming
Order of operations
Order of operations refers to the rules that dictate the sequence in which mathematical expressions should be evaluated. Python
follows the standard mathematical order of operations.
For example, multiplication and division are performed before addition and subtraction.
Comments
Comments are used to add explanatory notes or to disable certain lines of code. In Python, comments start with the ‘#’ character
and continue until the end of the line.
For example:
Debugging
Debugging in Python involves finding and fixing errors or bugs in the code. Common debugging techniques include using print statements
to check the values of variables, using a debugger, and using exception handling to catch and handle errors. Python provides various tools
and libraries for debugging, such as pdb (Python debugger) and integrated development environments (IDEs) like PyCharm and Visual
Studio Code, which offer debugging capabilities.
Python Programming
✓ Modules and functions: function Calls, adding new functions, Definitions and Uses, flow of execution,
parameters and arguments, Fruitful functions.
Modules and Functions
In Python, modules are files that contain Python code, which can include function definitions, variable declarations, and
classes. Modules allow you to organize and reuse code in a modular manner. You can import modules into your Python script to
access their functions and variables.
Functions are blocks of reusable code that perform a specific task. They help in organizing code, improving code
reusability, and promoting modular programming. You can define your own functions and use built-in functions provided by Python
or other modules.
Function Calls:
To execute a function, you make a function call. A function call consists of the function name followed by parentheses. If
the function takes any arguments, you pass them within the parentheses.
For example:
Python Programming
You can define your own functions using the ‘def’ keyword followed by the function name, parentheses, and a colon. The
function body is indented and contains the code that executes when the function is called.
For example:
Functions are defined using the ‘def’ keyword, and their code is executed when they are called. You can call a function
multiple times throughout your code.
For example:
Python Programming
Flow of Execution:
The flow of execution refers to the order in which statements are executed in a program. When a function is called, the
program jumps to the function's code, executes it, and then returns to the point where the function was called.
For example:
Output:
Python Programming
Parameters are variables defined in the function's definition, while arguments are the values passed to the function when
it is called. Parameters allow functions to accept input values and perform operations on them.
For example:
Fruitful Functions:
A fruitful function is a function that returns a value. It uses the ‘return’ statement to send a value back to the caller. The
returned value can be assigned to a variable or used in an expression.
For example:
By defining and using functions, you can modularize your code, improve code readability, and make your code more maintainable
and reusable.
Python Programming
✓ Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional
(if-elif-else)
Conditionals
Conditionals in Python allow you to control the flow of execution based on certain conditions. They rely on Boolean
values and operators to determine whether a condition is true or false.
Boolean values in Python are either `True` or `False`. They are used to represent the truth or falsity of an expression
or condition.
For example:
Python Programming
Python provides several comparison operators to compare values and evaluate conditions. Some common comparison
operators include:
Example:
Python Programming
It allows you to execute one block of code if a condition is true and another block if the condition is false.
Example:
Python Programming
It allows you to check multiple conditions one by one and execute the corresponding block of code based on the first true
condition.
Example:
These conditionals provide a way to make decisions and control the flow of your code based on different conditions and Boolean
values.
Python Programming
Iteration State
Iteration is the process of repeating a set of instructions or a block of code multiple times. Python provides several
constructs for performing iteration.
while loop:
The `while` loop repeatedly executes a block of code as long as a specified condition is true.
Example:
Python Programming
for loop
The ‘for’ loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects. It
executes a block of code for each item in the sequence.
Example:
Python Programming
range() function:
The range() function generates a sequence of numbers that can be used for iteration. It is often used with for loops.
Example:
Output:
Python Programming
Break statement:
The ‘break’ statement is used to exit a loop prematurely, regardless of the loop's condition. It is typically used
within a loop when a certain condition is met.
Example:
Continue statement:
The ‘continue’ statement is used to skip the remaining code in a loop iteration and move to the next iteration. It is
typically used within a loop when you want to skip some specific conditions.
Example:
Output:
Python Programming
Pass statement:
The pass statement is a placeholder statement that does nothing. It is used when a statement is required syntactically,
but no action is needed. It is often used as a placeholder in empty code blocks or to temporarily ignore code.
Example:
These iteration constructs provide flexibility in repeating code and performing tasks multiple times based on specific
conditions or sequences
Python Programming
✓ Recursion
Recursion is a programming technique where a function calls itself to solve a problem by breaking it down into smaller,
similar subproblems. It is a powerful concept that allows solving complex problems by reducing them to simpler cases.
1) Define a base case: A base case is the simplest case of the problem that can be directly solved without further recursion. It
serves as the stopping condition for the recursive calls.
2) Define a recursive case: The recursive case involves breaking down the problem into smaller subproblems that are closer to the
base case. The function calls itself with the smaller subproblem as input.
3) Handle the combination of results: If needed, you can combine the results of the recursive calls to solve the original problem.
Python Programming
In this example, the `factorial()` function calls itself with a smaller value (`n - 1`) until it reaches the base case (`n == 0`). The
results of the recursive calls are combined by multiplying `n` with the factorial of `n - 1`.
Recursion can be a powerful and elegant solution for certain problems, but it's important to design recursive functions
carefully to avoid infinite recursion or excessive memory usage. It's also worth noting that some problems can be solved more
efficiently using iterative approaches rather than recursion.
Python Programming
✓ Strings: string slices, immutability, string functions and methods, string module
Strings:
Strings in Python are sequences of characters enclosed in quotes (either single or double).
String Slices:
String slices allow you to extract a portion of a string by specifying the start and end indices. The syntax for string
slicing is `string[start:end]`, where `start` is the index of the first character to include, and `end` is the index of the first
character to exclude.
For example:
Immutability:
Strings in Python are immutable, which means that you cannot change individual characters in a string once it is created.
Instead, you need to create a new string with the desired changes.
For example:
Python Programming
Python provides many built-in functions and methods to manipulate strings. Some common string functions include `len()`,
`str()`, `upper()`, `lower()`, `split()`, `join()`, and `format()`.
String Module:
Python's `string` module provides constants and functions related to string operations. Some commonly used constants
include `string.ascii_letters`, `string.digits`, `string.punctuation`, etc. The module also provides functions like `string.capwords()` for
capitalizing words in a string and `string.Template()` for string templating.
These are just a few examples of what you can do with strings in Python. Python's string manipulation capabilities
are extensive, and you can find more functions and methods in the Python documentation.
Python Programming
✓ Lists as arrays
In Python, lists can be used as arrays to store a collection of values. Lists are versatile and allow you to store elements of
different data types, including numbers, strings, and even other lists. Here are some concepts related to using lists as arrays:
Creating a List:
You can create a list by enclosing elements in square brackets (`[]`) and separating them with commas.
For example:
Accessing Elements:
Elements in a list are indexed starting from 0. You can access individual elements by specifying their index in square brackets.
For example:
Python Programming
Modifying Elements:
Lists are mutable, meaning you can change the value of individual elements. You can assign a new value to an
element by using its index.
For example:
List Operations:
Lists support various operations such as concatenation (`+`), repetition (`*`), and membership (`in` and `not in`).
For example:
Python Programming
List Methods:
Python provides several built-in methods to manipulate lists. Some commonly used methods include `append()`,
`insert()`, `remove()`, `pop()`, `sort()`, and `reverse()`.
For example:
Lists in Python provide a flexible and powerful way to store and manipulate collections of values. They can be
used as arrays to store and access elements, and their mutability allows you to modify and rearrange the elements as
needed.
Python Programming
Thank you