Python Internal 1
Python Internal 1
Features of Python
Python's syntax is straightforward and readable, making it an excellent choice for beginners
and experienced developers alike.
Python is open-source, with an active and vast community contributing to its growth and
libraries.
Interpreted Language
Python executes code line-by-line, allowing easier debugging and dynamic coding.
Cross-Platform Compatibility
Python runs seamlessly on various operating systems, including Windows, macOS, and
Linux.
Versatile Applications
Python is used in web development, data science, artificial intelligence, machine learning,
automation, game development, and more.
Python’s ecosystem provides tools for almost every domain, making it a one-stop solution
for development.
History of Python
Creation
Python was created by Guido van Rossum in 1989 during his time at Centrum Wiskunde &
Informatica (CWI) in the Netherlands.
Design Philosophy
Guido named it after the comedy series Monty Python's Flying Circus. Python's design
emphasizes readability, simplicity, and explicitness.
Milestones
Python 1.0 (1994): Included core features like exception handling, functions, and modules.
Python 2.0 (2000): Introduced list comprehensions and garbage collection with reference
counting.
Growth
Over the years, Python gained widespread adoption due to its versatility, simplicity, and
applicability in emerging technologies like AI and machine learning.
Future of Python
Python is expected to maintain its lead as the go-to language for data analysis, machine
learning, and AI applications.
Improved Performance: Efforts like PyPy (a faster Python interpreter) and Just-In-Time (JIT)
compilation aim to enhance Python's execution speed.
IoT development.
Python frameworks are evolving for better support in web and mobile applications, with
tools like BeeWare gaining traction.
1. Download Python
Visit Python's official website and download the latest version for your operating
system.
2. Install Python
Follow the installation wizard. Ensure to check the box “Add Python to PATH” during
installation.
3. Save the file with the extension .py. For example, hello.py.
1. Open a terminal.
2. Navigate to the directory where the file is saved:
cd path/to/your/file
python hello.py
Steps to Execute
python add_numbers.py
3. Output:
A constant in Python is a value that is meant to remain unchanged throughout the program.
While Python does not have built-in support for constants, developers use conventions to
define them
Output:
The area of the circle is: 78.53975
The weight of the object is: 98.0 N
Variables in Python
A variable is a name used to store data that can be changed during the program's execution.
It acts as a container for storing values. In Python, variables are created when you assign a
value to them.
1. Single Assignment:
python
Copy code
x = 5 # Integer
name = "Alice" # String
pi = 3.14 # Float
2. Multiple Assignments:
python
Copy code
a, b, c = 1, 2, 3 # Assigning multiple values
x = y = z = 10 # Same value to multiple variables
Types of Variables
Python is dynamically typed, so you don't need to declare the type of a variable. It
determines the type based on the value assigned.
1. Integer:
python
Copy code
age = 25
2. Float:
python
Copy code
height = 5.9
3. String:
python
Copy code
name = "Alice"
4. Boolean:
python
Copy code
is_active = True
5. List:
python
Copy code
numbers = [1, 2, 3]
Example Program
# Define variables
name = "John" # String
age = 30 # Integer
height = 5.9 # Float
is_student = False # Boolean
Output:
Name: John
Age: 30
Height: 5.9
Is a student: False
Updated Age: 31
Identifiers:
Identifiers are the names used to identify variables, functions, classes, or other objects in
Python. They follow specific rules to ensure clarity and consistency in the code.
Valid Invalid
Example:
name = "Alice"
age = 25
_student_id = 101
PI = 3.14159
print("Name:", name)
print("Age:", age)
In Python, data types define the kind of value a variable can hold. They can be categorized
into primitive and non-primitive data types.
These are the basic, built-in data types in Python. They represent single values and are
immutable (cannot be changed after creation).
# Float
height = 5.9
print(type(height)) # Output: <class 'float'>
# Complex
num = 3 + 4j
print(type(num)) # Output: <class 'complex'>
# Boolean
is_active = True
print(type(is_active)) # Output: <class 'bool'>
# String
name = "Alice"
print(type(name)) # Output: <class 'str'>
These are more complex data types and can hold multiple values or elements.
set Unordered, mutable collection of unique elements {1, 2, 3}, {"a", "b", "c"}
# Tuple
coordinates = (10, 20, 30)
print(type(coordinates)) # Output: <class 'tuple'>
# Set
unique_numbers = {1, 2, 3, 4}
print(type(unique_numbers)) # Output: <class 'set'>
# Dictionary
person = {"name": "Alice", "age": 25}
print(type(person)) # Output: <class 'dict'>
# NoneType
value = None
print(type(value)) # Output: <class 'NoneType'>
Key Differences Between Primitive and Non-Primitive Data Types
In Python, the input() function is used to take user input from the console.
Example:
input() returns a string by default. You can convert the input to another data type
using functions like int(), float(), etc.
In the example above, age is converted to an integer using int().
Comments in Python
Comments are used to explain the code or make it more readable. They are ignored during
execution. In Python, comments are created using:
Example:
Reserved words are predefined words that cannot be used as variable names, function
names, or identifiers because they have special meanings in Python. These are also known
as keywords.
import keyword
print(keyword.kwlist)
if, else, for, while, break, continue, def, class, try, except, import, from, and, or, not,
None, True, False, etc.
Example:
Indentation is the use of spaces (or tabs) at the beginning of a line of code to define the
scope of loops, functions, conditionals, etc. In Python, indentation is crucial because it
defines the block of code that belongs to a particular statement.
Python uses indentation to differentiate between code blocks, instead of using curly braces
{} like in other programming languages.
Example:
# Correct indentation
greet("Alice")
Indentation level: Each block of code (like the code inside a function or an if block)
must be indented. Python uses 4 spaces per indentation level, but tabs are also
allowed, although spaces are preferred.
Operators in Python
Operators are symbols that perform operations on variables and values. Python has several
types of operators:
a. Arithmetic Operators
These operators are used to perform basic mathematical operations like addition,
subtraction, etc.
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
// Floor Division a // b
% Modulus (Remainder) a % b
** Exponentiation a ** b
Example:
a = 10
b=3
# Addition
print(a + b) # Output: 13
# Subtraction
print(a - b) # Output: 7
# Multiplication
print(a * b) # Output: 30
# Division
print(a / b) # Output: 3.3333...
# Floor Division
print(a // b) # Output: 3
# Modulus (Remainder)
print(a % b) # Output: 1
# Exponentiation
print(a ** b) # Output: 1000
== Equal to a == b
!= Not equal to a != b
Example:
a = 10
b=3
# Equal to
print(a == b) # Output: False
# Not equal to
print(a != b) # Output: True
# Greater than
print(a > b) # Output: True
# Less than
print(a < b) # Output: False
c. Logical Operators
and Returns True if both conditions are true a > 10 and b < 5
not Reverses the result (True becomes False, False becomes True) not(a > 10)
Example:
a = 10
b=3
# AND operator
print(a > 5 and b < 5) # Output: True
# OR operator
print(a > 15 or b < 5) # Output: True
# NOT operator
print(not(a > 10)) # Output: False
d. Assignment Operators
= Assign value a = 10
a = 10
# Add and assign
a += 5 # a = a + 5
print(a) # Output: 15
e. Bitwise Operators
` Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
Example:
a = 10 # 1010 in binary
b = 4 # 0100 in binary
# Bitwise AND
print(a & b) # Output: 0 (0000 in binary)
# Bitwise OR
print(a | b) # Output: 14 (1110 in binary)
# Bitwise XOR
print(a ^ b) # Output: 14 (1110 in binary)
# Bitwise NOT
print(~a) # Output: -11 (inverts all bits)
# Left shift
print(a << 2) # Output: 40 (101000 in binary)
# Right shift
print(a >> 2) # Output: 2 (0010 in binary)
Expressions in Python
Examples of Expressions:
1. Simple Expressions:
x = 10
y=5
result = x + y # expression is x + y
print(result) # Output: 15
2. Compound Expressions:
x = 10
y=5
z=2
result = (x + y) * z # expression is (x + y) * z
print(result) # Output: 30
x = 10
y=5
result = add(x, y) # expression is add(x, y)
print(result) # Output: 15
Operations on strings:
In Python, strings are sequences of characters, and they support a variety of operations.
Below are the most common operations on strings in Python, along with examples.
1. String Concatenation
Concatenation means joining two or more strings together using the + operator.
Example:
str1 = "Hello"
str2 = "World"
2. Concatenating strings
result = str1 + " " + str2 # Adds a space between the two strings
print(result) # Output: Hello World
2. String Repetition
str1 = "Hello"
result = str1 * 3 # Repeats the string 3 times
print(result) # Output: HelloHelloHello
3. String Indexing
You can access individual characters in a string using indexing. Indexing starts from 0.
Example:
str1 = "Hello"
# Accessing individual characters
print(str1[0]) # Output: H (First character)
print(str1[1]) # Output: e (Second character)
Negative indexing can be used to start counting from the end of the string.
4. String Slicing
Slicing is used to extract a substring from the string. You can specify a start, end, and step.
Example:
5. String Length
The len() function is used to get the length (number of characters) of a string.
Example:
You can convert the case of the string using several built-in methods:
Example:
# Convert to uppercase
print(str1.upper()) # Output: HELLO, WORLD!
# Convert to lowercase
print(str1.lower()) # Output: hello, world!
7. String Searching
Example:
# Using `in`
print("World" in str1) # Output: True
# Using `find()`
print(str1.find("World")) # Output: 7 (index of the substring)
8. String Replacement
Example:
str1 = "Hello, World!"
# Replacing "World" with "Python"
result = str1.replace("World", "Python")
print(result) # Output: Hello, Python!
You can remove leading and trailing whitespace from a string using:
Example:
You can split a string into a list of substrings using the split() method. By default, it splits by
spaces.
Example:
# Splitting by a comma
result = str1.split(",")
print(result) # Output: ['Hello', ' World!']
In Python, type conversion refers to converting one data type into another. There are two
types of type conversions:
x=5 # Integer
y = 2.5 # Float
Explicit type conversion, also known as type casting, is performed manually by the user
using built-in Python functions. Python provides several functions to explicitly convert one
type into another.
num2 = 5
result2 = float(num2) # Converts integer to float
print(result2) # Output: 5.0
num3 = 100
result3 = str(num3) # Converts integer to string
print(result3) # Output: "100"
str_num = "42"
result4 = int(str_num) # Converts string to integer
print(result4) # Output: 42
Converting to Boolean Example:
num = 0
result = bool(num) # 0 is considered as False
print(result) # Output: False
str_value = "Hello"
result2 = bool(str_value) # Non-empty string is considered as True
print(result2) # Output: True
Decision control statements in Python allow the program to take different actions based on
certain conditions. The primary types of decision control statements are:
1. Selection Statements
2. Loop Structures
3. Nested Loops
4. break, continue, pass statements
5. else Statements
1. Selection Statements
Selection statements are used to make decisions in the program. These statements execute
certain blocks of code depending on whether a condition is True or False.
if Statement
The if statement is used to check a condition and execute the code block if the condition is
True.
# Example of if statement
num = 10
if num > 5:
print("Number is greater than 5") # Output: Number is greater than 5
Explanation:
Here, the condition num > 5 is True, so the block of code inside the if statement is executed.
if-else Statement
The if-else statement allows you to specify two branches: one if the condition is True, and
the other if the condition is False.
if num > 5:
print("Number is greater than 5")
else:
print("Number is less than or equal to 5") # Output: Number is less than or equal to 5
Explanation:
Since the condition num > 5 is False, the code inside the else block is executed.
if-elif-else Statement
Explanation:
Here, the condition num == 5 is True, so the block inside the elif is executed.
2. Loop Structures
Loops are used to repeat a block of code multiple times. Python provides two main types of
loops: for and while.
for Loop
The for loop is used for iterating over a sequence (like a list, tuple, or string).
while Loop
Explanation:
The while loop runs as long as num <= 4. After each iteration, num is incremented by 1.
3.Nested Loops
A nested loop is a loop inside another loop. In this case, the inner loop runs for each
iteration of the outer loop.
Output:
css
Copy code
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
Explanation:
The outer loop runs for two values of i (1 and 2). For each value of i, the inner loop runs for
two values of j (1 and 2).
These are control flow statements used within loops to modify their behavior.
break Statement
Explanation:
When i equals 4, the break statement terminates the loop.
continue Statement
The continue statement is used to skip the current iteration and move to the next iteration
in a loop.
pass Statement
The pass statement is used as a placeholder for code that will be implemented later. It does
nothing when executed.
Explanation:
When i equals 2, the pass statement is executed, but it does nothing. The loop continues as
usual.
5. else Statement
The else statement can be used in loops to execute a block of code after the loop has
completed, but only if the loop was not terminated by a break.
Explanation:
The else block is executed after the loop finishes, because the loop was not interrupted by a
break.
Explanation:
Since the loop is terminated by the break statement, the else block is not executed.
UNIT -2 FUNCTIONS,MODULES,DATA STRUCTURES
Functions in Python
A function is a block of code that only runs when it is called. Functions allow us to organize
our code into reusable blocks.
1. Function Introduction
A function is defined using the def keyword in Python, followed by the function name and
parentheses ().
2. Function Definition
To define a function, we use the def keyword followed by the function name and a pair of
parentheses that may contain parameters.
# Function definition
def greet():
print("Hello, World!")
# Function call
greet() # Output: Hello, World!
Explanation:
In the above example, the function greet is defined without parameters. When we call
greet(), it prints "Hello, World!".
3. Function Call
A function call is used to invoke the function and execute its code.
# Function definition
def greet(name):
print(f"Hello, {name}!")
# Function call with argument
greet("Alice") # Output: Hello, Alice!
Explanation:
Here, the function greet accepts a parameter name. When we call greet("Alice"), it prints
the greeting with the name "Alice".
In Python, variables defined inside a function have local scope, meaning they are only
accessible within that function. Variables defined outside of any function have global scope
and can be accessed throughout the program.
# Global variable
x = 10
def my_function():
# Local variable
y = 20
print("Inside function, x =", x) # x is accessible as it is global
print("Inside function, y =", y) # y is accessible within this function
my_function()
# Output:
# Inside function, x = 10
# Inside function, y = 20
The variable x is global and can be accessed from anywhere in the program.
The variable y is local to my_function() and cannot be accessed outside it.
5. Return Statement
The return statement is used to exit a function and return a value to the caller.
Explanation:
The function add(a, b) returns the sum of a and b, and the result is printed outside the
function.
Functions can take parameters (inputs) which can be used inside the function.
Explanation:
The function multiply(a, b) takes two parameters and returns their product.
7. Lambda Functions (Anonymous Functions)
Lambda functions are small, unnamed functions defined using the lambda keyword. They
are often used for short, throwaway functions.
Explanation:
Here, lambda a, b: a + b is a lambda function that takes two arguments (a and b) and returns
their sum. The function is assigned to the variable add, which is then called with 2 and 3.
A docstring is a string literal that is used to describe a function, class, or module. It is placed
right after the def line.
9. Recursive Functions
A recursive function is a function that calls itself in order to solve a problem. Recursion is
typically used for problems that can be broken down into smaller, similar sub-problems.
result = factorial(5)
print(result) # Output: 120
Explanation:
The factorial() function calculates the factorial of a number by calling itself recursively until
it reaches the base case (n == 1). For factorial(5), it calculates 5 * 4 * 3 * 2 * 1, resulting in
120.
Arguments in Python can be classified based on how they are passed into functions. Python
provides different types of arguments to be passed into a function, which can be
categorized into Positional Arguments, Keyword Arguments, Default Arguments, Variable-
length Arguments, and Keyword-only Arguments.
1. Positional Arguments
Positional arguments are the most common type of arguments in Python. These arguments
are passed to a function in the order in which they appear in the function call.
Explanation:
In the above example, name and age are positional arguments. The values are passed to the
function in the order they appear in the function definition.
2. Keyword Arguments
Keyword arguments are arguments that are passed to a function by explicitly specifying the
parameter name along with the value.
Explanation:
In this case, we passed the arguments by specifying the parameter names (name and age)
along with their values. The order of the arguments doesn't matter when using keyword
arguments.
3. Default Arguments
Default arguments allow you to provide default values for parameters in case the caller does
not pass any value for those arguments. The default value is used if the argument is not
provided.
Explanation:
In the function greet(name, age=30), the parameter age has a default value of 30. If the
caller does not provide an age, the default value is used.
Definition:
*args allows a function to accept a variable number of non-keyword arguments. The
arguments are received as a tuple.
Example:
def print_numbers(*args):
for number in args:
print(number)
Output:
Copy code
1
2
3
4
Explanation:
In the function print_numbers(*args), the *args collects all the arguments passed into the
function as a tuple. In this example, the function prints each number passed to it (1, 2, 3, 4).