PYTHON PROGRAMMING
UNIT –I
Introduction to Python:
Python is a very powerful high-level, general-purpose, object-oriented programming language. Python is
very popular for developers and professionals because, it has a rich set of supporting libraries, and add-on
modules. It is a cross-platform (platform-independent) language and runs on all major operating systems
including Windows, Linux, and Macintosh. Python comes with a powerful and easy to-use graphical user
interface (GUI) toolkit that makes the task of developing GUI applications.
Features of Python:
Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is
straightforward. There is no use of the semicolon or curly-bracket, the indentation
defines the code block.
Expressive Language
Python can perform complex tasks using a few lines of code.
Interpreted Language
Python is an interpreted language; it means the Python program is executed one line
at a time. The interpreted language makes debugging easy and portable.
Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language.
Free and Open Source
Python is freely available for everyone. It is freely available on its official website www.python.org
Object-Oriented Language
Python supports object-oriented language. It supports object-oriented concepts
inheritance, polymorphism, encapsulation, etc.
Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning, web
Developing, and also for the scripting.
GUI Programming Support
Graphical User Interface is used for the developing Desktop applications and the web
applications.
Integrated
Python can be integrated with other languages, like C, C++, and java
Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When we assign
some value to the variable, it automatically allocates the memory to the variable at
run time.
----------------------------------------------------------------------------------------------------------------------------------------------------
Execution of Python:
A Python program's execution involves interpreting source code, compiling it into byte code, and then
running that byte code using the Python Virtual Machine. This process, facilitated by the Python
interpreter, allows the computer to understand and execute the instructions defined in the Python
code.
Here's a more detailed:
Writing Python Code: You write your program in a .py file using Python's syntax.
Interpretation and Compilation: The Python interpreter reads your code and, for efficiency,
compiles it into byte code, which is a lower-level, platform-independent representation of your
code.
Execution by the Python Virtual Machine (PVM): The PVM then takes this byte code and
executes it, translating it into machine code that the computer's processor can understand and
run.
Note:
Interactive Mode: Python can also be executed in interactive mode, where you type in commands and
the interpreter executes them immediately.
-------------------------------------------------------------------------------------------------------------------------------------------------------
Writing Our First Python Program:
To write our first Python program, we can either use the Python interactive shell or create a
Python file. In the interactive shell, you can type print ("Hello, World!") and press enter to see the
output. Alternatively, you can create a file (e.g., hello.py) with the same line of code and run it
using the Python interpreter.
Here's a breakdown of the process:
1. Using the Python Interactive Shell:
Open your terminal or command prompt.
Type python or python3 (depending on your system) and press Enter. This will start the
Python interpreter in interactive mode.
Type print ("Hello, World!") and press Enter. The output Hello, World! Will be
displayed.
2. Creating a Python File:
Open a text editor (like Notepad on Windows, or Text Edit on Mac, or any code editor
like VS Code or Sublime Text).
Type print ("Hello, World!") into the editor.
Save the file with a .py extension (e.g., hello.py).
Open your terminal or command prompt and navigate to the directory where you saved
the file.
Type python hello.py (or python3 hello.py) and press Enter to run the program. The
output Hello, World! Will be displayed.
-------------------------------------------------------------------------------------------------------------------------------------------
Python Interpreter and Interactive Mode:
The Python interpreter is a program that reads and executes Python code. It can operate in two
primary modes: script mode and interactive mode.
Interactive Mode:
Interactive mode provides a command-line shell where users can directly type Python statements
and receive immediate feedback. When the Python interpreter is launched in interactive mode, it
displays a primary prompt, typically >>>, indicating it is ready to accept input. Users can type
Python expressions or statements, and the interpreter evaluates them and displays the result or
executes the action.
This mode is particularly useful for:
Learning and experimentation: Quickly testing syntax, exploring library functions, and
understanding how different Python constructs behave.
Debugging: Isolating and testing small snippets of code to identify issues.
Quick calculations and data exploration: Performing on-the-fly computations or
inspecting variable values.
Example:
>>> 1 + 1
2
>>> print ("Hello, World!")
Hello, World!
>>> x = 10
>>> x * 2
20
-------------------------------------------------------------------------------------------------------------------------------------------------------
Values and Types:
In Python, a value is a fundamental piece of data that a program works with, such as a number, a
character, or a sequence of characters. Every value in Python has a specific type, which
determines the kind of data it represents and the operations that can be performed on it.
Here are some of the common built-in data types in Python:
1. Numeric Types:
Int (Integers): Whole numbers, positive or negative, without a decimal point.
x = 10
y = -5
Float (Floating-point numbers): Numbers with a decimal point.
Pi = 3.14
Temperature = -2.5
Complex (Complex numbers): Numbers with a real and an imaginary part, represented
as a + bj.
z = 3 + 4j
2. Text Type:
str (Strings): Sequences of characters enclosed in single or double quotes.
name = "Alice"
message = 'Hello, World!'
3. Sequence Types:
List: Ordered, mutable collections of items, enclosed in square brackets. Items can be of
different types.
my_list = [1, "apple", 3.14]
tuple: Ordered, immutable collections of items, enclosed in parentheses.
my_tuple = (1, "banana", 2.71)
Range: Represents an immutable sequence of numbers, often used in loops.
numbers = range (5) # Generates numbers from 0 to 4
4. Mapping Type:
dict (Dictionaries): Unordered collections of key-value pairs, enclosed in curly
braces. Keys must be unique and immutable.
my_dict = {"name": "Bob", "age": 30}
5. Set Types:
Set: Unordered collections of unique, immutable items, enclosed in curly braces.
Python
my_set = {1, 2, 3, 2} # Result: {1, 2, 3}
6. Boolean Type:
bool (Booleans): Represents truth values, either True or False.
Python
is_active = True
is_empty = False
7. None Type:
NoneType: Represents the absence of a value.
result = None
You can determine the type of a value or variable using the built-in type() function:
print(type(10)) # Output: <class 'int'>
print(type("hello")) # Output: <class 'str'>
-------------------------------------------------------------------------------------------------------------------------------------------------------
Expressions:
In Python, an expression is a combination of values, variables, operators, and function calls that
the Python interpreter evaluates to produce a single value. Expressions are fundamental
building blocks of Python programs, enabling computations, data manipulation, and logical
operations.
Here are some common types of expressions in Python:
Arithmetic Expressions: These involve numerical values and arithmetic operators
(e.g., +, -, *, /, ** for exponentiation, % for modulo).
result = 5 + 3 * 2 # Evaluates to 11
Relational (Comparison) Expressions: These compare two values and evaluate to a
Boolean (True or False) result. Operators include == (equal to), != (not equal to), < (less
than), > (greater than), <= (less than or equal to), >= (greater than or equal to).
is_greater = 10 > 5 # Evaluates to True
Logical Expressions: These combine Boolean values using logical operators
(and, or, not).
condition = (x > 0) and (y < 10) # Evaluates based on x and y
String Expressions: These involve string literals and operators like + for concatenation
or * for repetition.
full_name = "John" + " " + "Doe" # Evaluates to "John Doe"
Function Call Expressions: Calling a function with arguments evaluates to the return
value of that function.
length = len("Python") # Evaluates to 6
Conditional Expressions (Ternary Operator): A concise way to write an if-
else statement within a single expression.
status = "Adult" if age >= 18 else "Minor"
Generator Expressions: Similar to list comprehensions but create generator objects that
yield values on demand, saving memory.
squares = (x**2 for x in range(5)) # Creates a generator
NOTE: Expressions are distinct from statements in Python; while statements perform actions (like
assignments or control flow), expressions always evaluate to a value.
--------------------------------------------------------------------------------------------------------------------------------------------------------
Statements:
In Python, a statement is an instruction that the Python interpreter can execute. It represents a
complete unit of action or a command that tells the program to do something. Statements typically
end with a newline character, meaning each line in a Python script often constitutes a statement.
Common types of statements in Python include:
Assignment Statements: Used to assign a value to a variable.
x = 10
name = "Alice"
Print Statements: Used to display output to the console. In Python 3, print is a function.
print("Hello, World!")
print(x)
Conditional Statements (if, elif, else): Used to execute blocks of code based on whether
certain conditions are true or false.
if x > 5:
1. print("x is greater than 5")
elif x == 5:
2. print("x is equal to 5")
else:
print("x is less than 5")
Looping Statements (for, while): Used to repeatedly execute a block of code.
for i in range(5):
print(i)
count = 0
while count < 3:
print("Looping...")
count += 1
Control Flow Statements (break, continue, pass): Used within loops to alter their
execution flow.
1. break: Exits the loop entirely.
2. continue: Skips the rest of the current iteration and proceeds to the next.
3. pass: A null operation; used as a placeholder where a statement is
syntactically required but no action is desired.
Function Definition Statements (def): Used to define functions.
def greet (name):
print (f"Hello, {name}!")
Import Statements: Used to import modules or specific objects from modules.
import math
Tuple Assignment:
Tuple assignment in Python, also known as tuple unpacking, allows the simultaneous assignment
of multiple values to multiple variables in a single line of code. This feature is particularly useful
for concisely handling assignments and performing operations like variable swapping.
Key aspects of tuple assignment:
Multiple Assignment: You can assign multiple values from an iterable (like a tuple or list)
on the right-hand side of an assignment operator (=) to a corresponding number of
variables on the left-hand side. The number of variables and values must match.
a, b, c = (10, 20, 30)
print(a) # Output: 10
print(b) # Output: 20
print(c) # Output: 30
Parentheses Omission: While the values on the right-hand side conceptually form a tuple,
the parentheses can often be omitted, relying on comma separation for tuple creation.
x, y = "hello", "world"
print(x) # Output: hello
print(y) # Output: world
Variable Swapping: Tuple assignment provides a concise way to swap the values of two or
more variables without needing a temporary variable.
var1 = 5
var2 = 10
var1, var2 = var2, var1 # Swaps the values
print(var1) # Output: 10
print(var2) # Output: 5
Unpacking in Loops: Tuple unpacking is commonly used in for loops when iterating over
sequences of tuples (e.g., a list of (key, value) pairs from a dictionary's items() method).
my_dict = {"apple": 1, "banana": 2}
for fruit, count in my_dict.items():
print(f"{fruit}: {count}")
# Output:
# apple: 1
# banana: 2
Important Note: The number of variables on the left-hand side of the assignment must exactly match
the number of elements in the tuple or iterable on the right-hand side. A Value Error will occur if
there is a mismatch.
--------------------------------------------------------------------------------------------------------------------------
Precedence of Operator:
In Python, operator precedence dictates the order in which operations are performed within an
expression containing multiple operators. Operators with higher precedence are evaluated before
those with lower precedence. When operators have the same precedence, their associativity
(typically left-to-right, except for exponentiation) determines the order of evaluation.
The general order of precedence, from highest to lowest, is:
Parentheses (): Expressions within parentheses are always evaluated first.
Exponentiation `: `**: The power operator.
Unary operators +x, -x, ~x: Unary plus, unary minus, and bitwise NOT.
Multiplicative operators *, /, //, %: Multiplication, division, floor division, and
modulus. These are evaluated from left to right.
Additive operators +, -: Addition and subtraction. These are evaluated from left to
right.
Bitwise shift operators <<, >>: Bitwise left and right shifts.
Bitwise AND &.
Bitwise XOR ^.
Bitwise OR |.
Comparison operators ==, !=, >, >=, <, <=, is, is not, in, not in: Equality, inequality,
greater than, greater than or equal to, less than, less than or equal to, identity, and
membership operators. These are evaluated from left to right.
Logical NOT not.
Logical AND and.
Logical OR or.
Example:
result = 2 + 3 * 4 ** 2 – 1
In this expression:
4 ** 2 (exponentiation) is evaluated first: 16.
3 * 16 (multiplication) is evaluated next: 48.
2 + 48 (addition) is evaluated: 50.
50 - 1 (subtraction) is evaluated last: 49.
------------------------------------------------------------------------------------------------------------------------------------------------------
Comments:
Comments in Python are lines within the code that are ignored by the Python interpreter
during program execution. Their primary purpose is to enhance code readability and provide
explanations or notes for developers.
Types of Comments in Python:
Single-line comments: These begin with a hash symbol (#). Anything written after
the # on the same line is considered a comment and is not executed.
Multi-line comments (using multiple single-line comments): While Python does not
have a dedicated syntax for multi-line comments like some other languages; you can
achieve this by placing # at the beginning of each line you wish to comment out.
Multi-line comments (using triple quotes): You can also use triple single quotes
('''Comment content''') or triple double quotes ("""Comment content""") to create what
effectively acts as a multi-line comment. These are technically multi-line string literals
that are not assigned to a variable, and therefore, they are ignored by the interpreter at
runtime.
Note: Be cautious when using triple-quoted strings as comments, especially directly after
function or class definitions, as they can be interpreted as doc strings, which have a specific
function in Python for documentation
------------------------------------------------------------------------------------------------------------------------------------------------------
Modules:
In Python, a module is a single file containing Python code, saved with a .py extension. Modules
serve as fundamental building blocks for organizing and reusing code within Python
programs. They can define functions, classes, variables, and constants, and can also include
runnable code.
Key characteristics of Python modules:
Code Organization:
Reusability:
.Namespace:
Import Mechanism:
Types of Modules:
Built-in Modules: Modules included with the Python interpreter (e.g., sys, os).
Standard Library Modules: Modules that are part of the Python standard library but
need to be imported (e.g., datetime, json).
Third-party Modules: Modules developed and maintained by external communities,
requiring separate installation (e.g., NumPy, Flask).
User-defined/Local Modules: Modules created by users within their own projects to
organize their code.
----------------------------------------------------------------------------------------------------------------------------------------------------
Functions:
Functions in Python are named blocks of organized, reusable code designed to perform specific
tasks. They are fundamental building blocks that promote modularity, reusability, and
maintainability in a program.
Defining a Function:
Functions are defined using the def keyword, followed by the function name, parentheses
(which can contain parameters), and a colon. The function body is indented below the
definition.
The syntax to declare a function is:
Def functionname(parameters):
Statements
return
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python function
definition by using def keyword.
def greet(name):
print(f"Hello, {name}!")
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function. Below is the
example for calling def function Python.
greet("Alice") # Calls the greet function with "Alice" as an argument
Parameters and Arguments:
Parameters are placeholders in the function definition, while arguments are the actual values
passed during a function call.
Types of Python Function Arguments:
Python supports various types of arguments that can be passed at the time of the function call. In
Python, we have the following function argument types in Python:
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments:
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments to write
functions in Python.
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)
Keyword Arguments:
The idea is to allow the caller to specify the argument name with values so that the caller does not
need to remember the order of parameters.
def student(fname, lname):
print(fname, lname)
student(fname='Geeks', lname='Practice')
student(lname='Practice', fname='Geeks')
Positional Arguments:
We used the Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the values can be used in the wrong places, as
shown in the Case-2 example below, where 27 is assigned to the name and Suraj is assigned to
the age.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
print("Case-1:")
nameAge("Suraj", 27)
print("\nCase-2:")
nameAge(27, "Suraj")
Arbitrary Keyword Arguments:
In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
*args in Python (Non-Keyword Arguments)
**kwargs in Python (Keyword Arguments)
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
----------------------------------------------------------------------------------------------------------------------------------------------------
Flow of Execution:
The flow of execution in Python functions describes the order in which statements are processed during
program execution, particularly when functions are involved.
Sequential Execution:
Program execution typically begins at the first statement and proceeds sequentially, one statement
at a time, from top to bottom.
Function Definition:
When the interpreter encounters a function definition (def function_name():), it does not
immediately execute the statements within the function's body. Instead, it "remembers" the
function's code and associates it with the given name. The flow of execution continues to the next
statement after the function definition.
Function Call:
The flow of execution changes when a function is called (function_name()). Instead of proceeding to
the next line of code in the current scope, the control flow "jumps" to the first line of the called
functions body.
Function Body Execution:
All statements within the called function's body are then executed sequentially, from top to bottom.
Return from Function:
When the function completes its execution (either by reaching the end of its body or encountering
a return statement), the control flow "returns" to the point where the function was called. Execution
then resumes from the statement immediately following the function call.
Nested Function Calls:
If a function calls another function within its body, the same principles apply. The control flow jumps to
the nested function, executes its statements, returns, and then the outer function continues its
execution.
---------------------------------@@@@@@@@@-----------------------------------------------