Python Programming Course Materials
Python Programming Course Materials
MODULE 2
Features:
1. Easy to learn: Python has a simple and intuitive syntax that makes it easy to
learn for beginners, as well as for experienced programmers.
2. Object-oriented: Python supports object-oriented programming (OOP)
concepts such as classes, objects, inheritance, and polymorphism.
3. Interpreted: Python is an interpreted language, which means that there is no
need to compile the code before running it.
4. Dynamic: Python is a dynamically-typed language, which means that variables
are not required to be declared before use.
5. Extensive libraries: Python has a large collection of libraries that offer a wide
range of functionality, including data analysis, machine learning, web
development, and more.
6. Cross-platform: Python can be run on different operating systems such as
Windows, macOS, and Linux.
Applications:
1. Web development: Python is widely used for web development, thanks to its
popular web frameworks such as Django and Flask.
2. Data analysis and visualization: Python has powerful libraries such as NumPy,
Pandas, and Matplotlib that are widely used for data analysis, processing, and
visualization.
3. Machine learning: Python has a rich ecosystem of machine learning libraries
such as scikit-learn, TensorFlow, and PyTorch that are used for building and
training machine learning models.
4. Scripting: Python is often used for scripting tasks such as automation, file
handling, and system administration.
5. Game development: Python can be used to develop games using popular
game engines such as Pygame and Panda3D.
6. Scientific computing: Python is widely used for scientific computing and
research in fields such as physics, chemistry, and biology.
Python Versions
Python is an evolving language with different versions, each with its unique features
and improvements. Here are the most commonly used versions of Python:
1. Python 2.x: This version was the first major release of Python, and it has been
around for over a decade. Python 2.x was the standard version until Python 3.x
was introduced. However, Python 2.x is no longer supported and has reached
its end of life.
2. Python 3.x: Python 3.x was introduced in 2008, and it's the current standard
version of Python. It comes with several improvements and new features
compared to Python 2.x, including better Unicode support, improved print
function, and better syntax for exceptions. Python 3.x is backward-
incompatible with Python 2.x, meaning that the code written in Python 2.x
may need to be modified to run on Python 3.x.
3. Python 3.10: Python 3.10 is the latest major version of Python, released in
October 2021. It comes with new features, including structural pattern
matching, improved error messages, and improved time zone handling.
4. Other Versions: In addition to the above, there are other versions of Python,
including Jython, IronPython, and PyPy. Jython is an implementation of Python
that runs on the Java Virtual Machine (JVM), IronPython runs on the .NET
framework, while PyPy is a faster implementation of Python that uses just-in-
time compilation (JIT).
It's worth noting that different versions of Python may have different syntax and
functionalities. Therefore, it's essential to choose the appropriate version for your
project and ensure compatibility with other libraries and frameworks that you may be
using.
Installation of python
To install Python, you can follow these steps:
Alternatively, you can use a package manager like Homebrew (for Mac) or apt-get
(for Linux) to install Python. In that case, you can simply type the appropriate
command in the terminal to install Python.
1. Command Line Mode: The Python command-line mode, also known as the
interactive mode, allows you to write and execute Python code line by line in
the terminal or command prompt. To access the Python command-line mode,
simply open the terminal or command prompt and type "python" or
"python3" (depending on the version you have installed). You will see the
Python prompt (>>>) indicating that you are in the interactive mode. You can
then start writing Python code and see the output immediately after pressing
the Enter key.
2. IDEs: Integrated development environments (IDEs) provide a more
comprehensive and user-friendly environment for developing and running
Python code. Some popular Python IDEs include PyCharm, Visual Studio Code,
Spyder, and IDLE. IDEs provide features such as code completion, debugging,
syntax highlighting, and easy access to documentation and libraries. IDEs are
also useful for managing large projects that consist of multiple files and
require complex dependencies.
Both the command-line mode and IDEs have their advantages and disadvantages,
and the choice depends on personal preference and the nature of the project. For
simple and quick Python code execution, the command-line mode may be sufficient,
while IDEs are more suitable for large and complex projects that require more
advanced features and tools.
Certainly! Here's a simple Python program that asks the user for their name and
greets them:
Python code
name = input("What is your name? ")
print("Hello, " + name + "!")
When you run this program, it will prompt the user to enter their name. Once the
user enters their name and hits enter, the program will print out a personalized
greeting.
Identifiers in python
In Python, an identifier is a name that is used to identify a variable, function, class,
module, or other object in a Python program. Identifiers follow some basic rules:
1. An identifier can only contain alphanumeric characters (a-z, A-Z, 0-9) and
underscores (_).
2. An identifier cannot start with a digit.
3. Python identifiers are case sensitive. This means that "hello" and "Hello" are
two different identifiers.
4. There are some reserved words that cannot be used as identifiers, such as if,
else, for, and while.
Valid Identifiers:
o my_variable
o myVariable
o MY_VARIABLE
o my_function
o myClass
Invalid Identifiers:
o 1myvariable
o my-variable
o my variable
o if
o else
It's important to choose meaningful and descriptive names for identifiers to make your code
easier to understand and maintain.
Keywords in python
In Python, keywords are reserved words that have special meanings and purposes in
the language. These words cannot be used as identifiers (variable names, function
names, etc.) because they are already used for specific programming tasks.
You can see that these words are used for a variety of tasks, such as creating and
defining functions and classes, controlling program flow with conditional statements
(if, else, and elif), and looping with for and while loops.
It's important to avoid using these keywords as variable names or other identifiers in
your program, because doing so can cause errors or unexpected behaviour.
An expression, on the other hand, is a piece of code that returns a value. It can be a
single value, a variable, or a combination of values and operators. Expressions can be
used within statements, but they are not statements themselves. Examples of
expressions in Python include arithmetic operations such as addition and subtraction,
function calls, and variable references.
Statements:
if x > 0: # if statement
print("Positive number")
print(i)
Expressions:
len("hello") # function call expression that returns the length of the string "hello"
Variables in python
In Python, a variable is a name that refers to a value. Variables are used to store
values that can be used later in the program. Python is a dynamically-typed
language, which means that the data type of a variable is determined at runtime,
based on the value that is assigned to it.
In Python, you can assign a value to a variable using the equals sign (=). For example,
to assign the value 10 to a variable called "x", you would write:
x = 10
After this assignment, the variable "x" will refer to the value 10. You can then use the
variable "x" in expressions and statements throughout your program.
Variables in Python can have any name that is a valid identifier. An identifier is a
name that conforms to certain rules, such as not starting with a number and not
containing spaces. For example, the following are all valid variable names in Python:
age
name
my_var
x1
You can also assign different types of values to variables in Python, such as strings,
numbers, or Boolean values. The data type of the variable will be determined based
on the value that is assigned to it. For example, the following code creates three
variables of different data types:
x = 10 # x is an integer
y = "hello" # y is a string
You can also assign the same value to multiple variables at once by separating the variable
names with commas:
a, b, c = 1, 2, 3
After this assignment, the variable "a" will refer to the value 1, "b" will refer to the value 2,
and "c" will refer to the value 3.
6. Identity operators: These operators test whether two variables refer to the
same object in memory. Here are some examples:
➢ is # identity test
➢ is not # non-identity test
These are the main categories of operators in Python. Understanding how they work and
how to use them can help you write more powerful and expressive Python code.
In Python, operators have a precedence level, which determines the order in which
they are evaluated in an expression. Operators with a higher precedence level are
evaluated before operators with a lower precedence level. If two operators have the
same precedence level, the evaluation order is determined by their association.
The following table shows the precedence and association of operators in Python
(from highest to lowest):
9 or Logical OR Left-to-right
The order of evaluation is determined by the precedence and association of the operators.
First, the exponentiation operator (**) is evaluated, followed by the multiplication operator
(*), then the division operator (/), and finally the addition operator (+). Applying the
precedence and association rules, the expression is evaluated as follows:
2 + ((3 * (4 ** 2)) / 6)
2 + ((3 * 16) / 6)
2+8
10
In Python, every value has a specific data type. The data type determines the kind of
operations that can be performed on the value, as well as how the value is stored in
memory. Here are some of the most common data types in Python:
1. Numeric types: Numeric types are used to represent numbers. In Python, there
are three numeric types: integers, floating-point numbers, and complex
numbers.
2. Boolean type: The boolean type represents truth values, which can be either
True or False.
3. String type: The string type is used to represent text. Strings are sequences of
characters, and they can be enclosed in single or double quotes.
4. List type: The list type is used to represent sequences of values. Lists are
ordered collections of values, and they can contain values of different data
types.
5. Tuple type: Tuples are similar to lists, but they are immutable, meaning their
values cannot be changed once they are created.
6. Set type: The set type is used to represent collections of unique values. Sets
are unordered collections of values, and they can contain values of different
data types.
7. Dictionary type: The dictionary type is used to represent mappings between
keys and values. Dictionaries are unordered collections of key-value pairs, and
they can contain values of different data types.
➢ x=5 # integer
➢ y = 3.14 # floating-point number
➢ z = 2 + 3j # complex number
➢ b = True # boolean
➢ s = "hello" # string
➢ l = [1, 2, 3] # list
➢ t = (4, 5, 6) # tuple
➢ st = {1, 2, 3, 3, 3} # set
➢ d = {"a": 1, "b": 2} # dictionary
Indentation; in python
In Python, indentation is used to indicate the scope or block of code for control flow
statements, functions, classes, and other structures that require grouping of
statements. Indentation is not optional in Python; it is a fundamental part of the
language syntax.
The recommended standard for indentation in Python is to use four spaces for each
level of indentation. You can use tabs instead of spaces, but it's generally not
recommended because it can cause issues with different text editors or software that
interpret tabs differently.
# if statement
x=5
if x > 0:
print("x is positive") # indented block of code
# for loop
for i in range(5):
print(i) # indented block of code
# function definition
def my_function():
print("This is my function") # indented block of code
# class definition
class MyClass:
def __init__(self):
self.x = 0 # indented block of code
def my_method(self):
print("This is my method") # indented block of code
Note that the first line of a compound statement ends with a colon (:) and the
following line(s) are indented to indicate the block of code that belongs to that
statement.
Comments; in python
In Python, comments are used to document code and provide information to other
developers who may read your code. Comments are ignored by the Python
interpreter and have no effect on the program's execution.
1. Single-line comments: To write a single-line comment, start the line with the
hash character (#). Everything after the hash symbol on that line is treated as a
comment and is ignored by the Python interpreter.
"""
This is a multi-line comment.
It can span multiple lines and is enclosed in triple quotes.
Multi-line comments are typically used to provide a description of a function or class.
"""
It's a good practice to include comments in your code to explain what your code does, why
you made certain design decisions, or to provide instructions for other developers who may
use or modify your code in the future. However, it's important to avoid excessive
commenting that may make the code difficult to read.
1. Console Output: The most commonly used function for console output is
print(), which is used to print the specified text or variable values to the
console. The print() function can take one or more arguments separated by
commas, and it automatically adds a newline character at the end of the
printed text.
2. Console Input: The most commonly used function for console input is input(),
which is used to prompt the user to enter a value from the console. The
input() function takes an optional prompt string as an argument, which is
displayed to the user in the console before waiting for the user's input.
name = input("Enter your name: ") # prompts the user to enter a string value
age = int(input("Enter your age: ")) # prompts the user to enter an integer value
print("Your name is", name, "and you are", age, "years old.") # prints the user's input to the console
Note that the input() function always returns a string, even if the user enters a
number. If you want to convert the input to a specific data type, such as integer or
float, you can use the corresponding type casting function, such as int() or float(),
as shown in the example above.
These are the two basic functions for console input and console output in Python.
There are also many other built-in functions and libraries available in Python for
more advanced console input and output operations, such as formatting and
handling user input errors.
In Python, type conversion is the process of converting a value of one data type to
another data type. Python provides several built-in functions for type conversion,
including:
1. int(): This function is used to convert a value to an integer data type. It can
convert a string or a float value to an integer value.
3. str(): This function is used to convert a value to a string data type. It can
convert an integer, float, or any other data type to a string value.
4. bool(): This function is used to convert a value to a boolean data type. It can
convert any value to a boolean value, with some values (such as 0, empty
strings, and None) being considered as False, and all other values being
considered as True.
4. bool(): This function is used to convert a value to a boolean data type. It can
convert any value to a boolean value, with some values (such as 0, empty
strings, and None) being considered as False, and all other values being
considered as True.
Type conversion is a useful tool in Python, as it allows you to work with different types of
data and perform operations that require values of specific data types. However, it's
important to keep in mind that type conversion can sometimes result in data loss or errors,
so it's important to use it carefully and ensure that the resulting data is accurate and valid.
There are many other Python libraries available, depending on your needs and the
tasks you want to perform. When working on a project, it's often helpful to research
and identify the most appropriate libraries to use, as they can save time and simplify
complex tasks.
To import the entire library, you can use the import keyword, followed by the name of
the library. This makes all the functions and modules in the library available in your
code.
Example:
import math
To import a specific function or module from a library, you can use the from keyword,
followed by the name of the library and the name of the function or module.
Example:
today = [Link]()
print(today) # prints the current date in the format YYYY-MM-DD
In this example, the date module is imported from the datetime library, and the
today() function is used to get the current date.
You can use an alias to rename a library when importing it, using the as keyword.
Example:
import numpy as np
In this example, the numpy library is imported with the alias np, making it easier to
reference the library in the code.
If the library you want to use is located in a different directory, you can add the
directory to the Python path and then import the library as usual.
Example:
import sys
[Link]("/path/to/library/directory")
import mylibrary
result = [Link]()
print(result)
In this example, the sys module is used to add the directory containing the mylibrary
module to the Python path, and then the mylibrary module is imported and used in
the code.
These are just a few examples of how to import libraries in Python. There are many
other ways to import libraries, depending on your needs and the structure of your
code.
1. Hello World:
print("Hello, World!")
his program simply prints the string "Hello, World!" to the console.
2. Basic Arithmetic:
x=5
y=2
This program performs some basic arithmetic operations on two variables x and y,
and prints the results to the console.
3. Looping:
for i in range(10):
print(i)
This program uses a for loop to iterate over the numbers from 0 to 9, and prints each
number to the console.
4. Conditional Statements:
x = 10
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
5. String Manipulation:
s = "Hello, World!"
These are just a few examples of the types of programs that can be written in Python.
The language is very versatile and can be used for a wide range of applications, from
simple scripts to complex software systems.
MODULE 3
x=5
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
2. Loops (for/while): Loops are used to execute a block of code repeatedly. The
basic syntax is:
For loop:
Example:
for i in range(10):
print(i)
While loop syntax:
while condition:
# Code to execute as long as condition is True
Example:
i=0
while i < 10:
print(i)
i += 1
2. Loops: Loops are used to repeat a set of statements multiple times. In Python,
there are two types of loops: for loop and while loop.
3. Function Calls: Functions are reusable blocks of code that can be called
multiple times with different input parameters. In Python, you can define a
function using the def keyword.
if statement in python
In Python, the "if" statement is a conditional statement that allows you to execute code only
if a certain condition is met. The basic syntax of the "if" statement in Python is as follows:
if condition:
# code to execute if condition is True
Here's an example:
x = 10
if x > 5:
print("x is greater than 5")
In this example, the "if" statement checks if the value of "x" is greater than 5. Since the value
of "x" is 10, the condition is True and the code block under the "if" statement is executed,
which prints the message "x is greater than 5" to the console.
In Python, the "else" statement is used in conjunction with the "if" statement to specify code
that should be executed when the condition of the "if" statement is False. The basic syntax of
the "if-else" statement in Python is as follows:
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
In this syntax, if the "condition" of the "if" statement is True, the code block under
the "if" statement is executed. Otherwise, the code block under the "else" statement
is executed.
Here's an example:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
In this example, the "if" statement checks if the value of "x" is greater than 5. Since the value
of "x" is 3, the condition is False, and the code block under the "else" statement is executed,
which prints the message "x is less than or equal to 5" to the console.
In Python, the "elif" statement is short for "else if". It's used to add additional conditions to
the "if" statement. The basic syntax of the "if-elif-else" statement in Python is as follows:
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition1 is False and condition2 is True
else:
# code to execute if condition1 and condition2 are False
In this syntax, the "if" statement is followed by one or more "elif" statements, which
can test additional conditions. The "else" statement is optional, and if included, it
executes if all the conditions tested by the "if" and "elif" statements are False.
Here's an example:
x=7
if x < 5:
print("x is less than 5")
elif x < 10:
print("x is between 5 and 10")
else:
print("x is greater than or equal to 10")
In this example, the "if" statement checks if the value of "x" is less than 5. Since the value of
"x" is 7, the condition is False, and the code block under the first "elif" statement is executed,
which prints the message "x is between 5 and 10" to the console.
In Python, the "while" loop is a control flow statement that allows you to execute a
block of code repeatedly as long as a certain condition is True. The basic syntax of
the "while" loop in Python is as follows:
while condition:
# code to execute repeatedly while condition is True
Here's an example:
i=0
while i < 5:
print(i)
i += 1
In this example, the "while" loop repeatedly prints the value of "i" to the console as long as
it's less than 5. The loop starts with the value of "i" set to 0, and the condition "i < 5" is True.
The code block under the "while" statement is executed, which prints the value of "i" to the
console and increments the value of "i" by 1. This process continues until the value of "i" is 5,
at which point the condition "i < 5" is False, and the loop is exited.
Break in python
In Python, the "break" statement is a control flow statement that allows you to exit a
loop prematurely, before the condition that controls the loop has become False.
When a "break" statement is executed, the program immediately exits the loop and
continues with the next statement outside of the loop.
The "break" statement is typically used when you want to exit a loop under a certain
condition, for example, if you've found the value you're looking for in a list, or if a
certain computation has reached a certain threshold.
Here's an example:
In this example, the "for" loop iterates over the list of fruits, and the "fruit" variable
takes on the value of each fruit in turn. The "if" statement checks if the value of "fruit"
is equal to "date", and if it is, the "break" statement is executed, which immediately
exits the loop. As a result, only the values of "apple", "banana", and "cherry" are
printed to the console.
It's worth noting that "break" only exits the innermost loop that it's contained in. If
you have nested loops, and you want to exit the outer loop, you can use a labeled
"break" statement.
In Python, the "continue" statement is a control flow statement that allows you to
skip the current iteration of a loop and move on to the next iteration. When a
"continue" statement is executed, the program skips any remaining code in the
current iteration of the loop and immediately begins the next iteration.
The "continue" statement is typically used when you want to skip over certain values
in a sequence, or when you want to implement certain conditions for certain values.
Here's an example:
In this example, the "for" loop iterates over the list of fruits, and the "fruit" variable
takes on the value of each fruit in turn. The "if" statement checks if the length of the
current fruit is less than 6, and if it is, the "continue" statement is executed, which
skips the rest of the code block for the current iteration and immediately moves on
to the next iteration. As a result, only the values of "banana", "cherry", and
"elderberry" are printed to the console.
It's worth noting that "continue" only skips the remaining code in the current
iteration of the loop. The loop continues with the next iteration, and any remaining
iterations are executed as normal.
In Python, the "for" loop is a control flow statement that allows you to execute a block of
code repeatedly for each item in a sequence (such as a list, tuple, or string). The basic syntax
of the "for" loop in Python is as follows:
In this syntax, "item" is a variable that is assigned the value of each item in the
"sequence" in turn. The code block under the "for" statement is executed once for
each item in the sequence.
Here's an example:
In this example, the "for" loop iterates over the items in the list "fruits" and assigns
each item to the variable "fruit" in turn. The code block under the "for" statement is
executed once for each item in the list, which prints the value of the "fruit" variable to
the console.
You can also use the built-in "range" function to create a sequence of numbers to
iterate over:
for i in range(5):
print(i)
In this example, the "for" loop iterates over the numbers 0 through 4 and assigns each
number to the variable "i" in turn. The code block under the "for" statement is executed once
for each number in the sequence, which prints the value of the "i" variable to the console.
Here's an example:
In this example, the range() function generates a sequence of odd numbers from 1 to
9, incrementing by 2 at each step. The "for" loop iterates over this sequence, and the
"i" variable takes on the value of each number in turn. The code block under the "for"
statement is executed for each value of "i", which simply prints the value to the
console.
Here's an example:
import sys
if some_error_condition:
[Link](1)
In this example, the [Link]() function is used to terminate the program with an exit code
of 1 if the some_error_condition evaluates to True. This indicates that the program
terminated abnormally due to an error condition. Note that the sys module is imported to
use the exit() function.
Here are a few illustrative programs that demonstrate the use of control flow
statements in Python:
In this program, a while loop is used to calculate the factorial of the input number.
The loop continues as long as the value of "n" is greater than 1. In each iteration of
the loop, the value of "fact" is multiplied by the current value of "n", and "n" is
decremented by 1. After the loop has finished, the final value of "fact" is printed to
the console.
2. Program to check if a number is prime using a for loop and a break statement:
In this program, a for loop is used to check if the input number is prime. The loop
iterates over a range of numbers from 2 to the input number minus 1. In each
iteration of the loop, the current number is divided by the input number using the
modulo operator. If the remainder is 0, the input number is not prime, and the loop
is exited using a "break" statement. If the loop completes without finding a divisor,
the input number is prime, and the "else" block is executed.
3. Program to generate the first "n" Fibonacci numbers using a for loop:
n = int(input("Enter a number: "))
fib = [0, 1]
for i in range(2, n):
[Link](fib[i-1] + fib[i-2])
print("Fibonacci sequence:", fib)
In this program, a for loop is used to generate the first "n" Fibonacci numbers. The program
initializes a list with the first two numbers in the sequence (0 and 1), and then uses a loop to
generate the remaining numbers. In each iteration of the loop, the program appends the
sum of the previous two numbers in the sequence to the list. After the loop has finished, the
entire Fibonacci sequence is printed to the console.
MODULE 4
In Python, there are several types of functions that you can define and use in your
code:
1. Built-in functions: These are functions that are part of the Python language
itself and are always available to use. Examples include print(), len(), range(),
input(), abs(), and max().
2. User-defined functions: These are functions that you define yourself in your
code to perform specific tasks. You can define a function using the def
keyword, followed by the function name, parentheses, and a colon. The
function body is indented below the header. Here's an example of a simple
user-defined function:
def greet(name):
In Python, a function is a reusable block of code that performs a specific task. The basic
syntax for defining a function in Python is as follows:
def function_name(parameters):
"""docstring"""
statements
[return expression]
Here's an example of a function that takes two parameters and returns their sum:
Once defined, this function can be called from other parts of the program with the
appropriate arguments:
result = add_numbers(2, 3)
print(result) # Output: 5
In general, functions help to make code more modular and easier to read and maintain.
To call a function in Python, you simply need to use the function name followed by
parentheses, and any arguments that the function requires. Here's an example of calling a
built-in function:
print("Hello, world!")
In this example, the print() function is called with a string argument "Hello, world!".
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
add = lambda x, y: x + y
result = add(3, 5)
print(result)
In this example, the add lambda function is called with the arguments 3 and 5. The result is
assigned to a variable result and printed to the console.
In this example, name and message are the parameters of the function
greet. They are assigned the values "Alice" and "Hello" respectively
using keyword arguments.
3. Default Arguments: You can set default values for parameters in the function
definition. If the argument is not passed in the function call, the default value
is used instead.
Here's an example
In Python, the return statement is used to exit a function and return a value to the
caller. It can be used in both built-in and user-defined functions.
The syntax of the return statement is simple. It consists of the keyword return
followed by an expression or a variable whose value you want to return. Here's an
example:
return a + b
In this example, the add_numbers function takes two arguments a and b, adds them
together, and returns the result using the return statement.
def say_hello():
print("Hello, World!")
return
In this example, the say_hello function prints "Hello, World!" and returns None
because there is no expression or variable after the return keyword.
The return statement can also be used to return multiple values. In Python, you can
return multiple values as a tuple. Here's an example:
In Python, default parameters are used to define a default value for a function
parameter. When a function is called and a value is not passed for a parameter that
has a default value defined, the default value will be used.
In the above example, the greeting parameter has a default value of 'Hello'. When the
greet() function is called with only the name parameter, the default greeting of 'Hello'
is used. When the function is called with both name and greeting parameters, the value
of greeting provided by the caller is used.
Default parameters can also be defined with mutable objects like lists or dictionaries.
However, it is important to understand that if the mutable object is modified within
the function, the changes will persist in subsequent calls to the same function. Here's
an example:
In the above example, the add_item() function has a default parameter of an empty list [].
When the function is called with only the item parameter, the default list is used. However, if
the my_list parameter is not provided, the same default list is used across subsequent
function calls. In the second call, 'banana' is added to the list, and in the third call, 'orange' is
added to the same list, which already contains 'apple' and 'banana'
Command line arguments are values passed to a program when it is run from the
command line. In Python, you can access these arguments using the sys module,
which provides access to some variables used or maintained by the Python
interpreter.
Here's an example of a simple Python program that prints the command line
arguments passed to it:
import sys
In this example, we import the sys module and get the command line arguments
using the [Link] variable. This variable is a list that contains the name of the script
followed by any arguments passed to the script.
We then iterate over the args list and print each argument to the console.
To run this program with command line arguments, you would type something like
this:
This would pass three arguments (arg1, arg2, and arg3) to the [Link] script. The script
would then print each argument to the console.
In this example, the greet function takes two keyword arguments: name and message.
We call the function using the keyword arguments syntax, where we specify the
argument names and their values. This allows us to pass the arguments in any order.
return len(s)
This function takes a single parameter, s, which is a string, and returns its length. For
example:
MODULE 5
In Python, you can create a string by enclosing a sequence of characters in single quotes ( ')
or double quotes ("). Here are some examples:
In Python, single and double quotes can be used interchangeably to create strings. However,
if you need to include a quote character inside a string that is already enclosed in quotes of
the same type, you can use the other type of quote character to create the string. For
example:
In this example, single quotes are used to enclose the string because double quotes
are already used inside the string.
In addition to using single or double quotes to create a string, you can also use triple
quotes (''' or """) to create a multi-line string:
string5 = '''This is a
multi-line
string.'''
In this example, the string spans multiple lines and is enclosed in triple quotes. The
string includes newlines (\n) between each line of text.
Once you have created a string, you can manipulate it in various ways, such as slicing,
concatenating, and formatting.
In Python, you can sort a string using the sorted() function or the sort() method.
Both functions return a sorted list of the characters in the string.
In this example, we create a string "hello world" and pass it to the sorted() function.
The function returns a sorted list of the characters in the string, which we store in the
sorted_string variable. We then print the sorted list.
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
You can also use the sort() method to sort a string. Here's an example:
In this example, we convert the string to a list of characters using the list() function,
sort the list using the sort() method, and then join the sorted list back into a string
using the join() method. We then print the sorted string.
dehllloorw
In Python, you can access individual characters in a string using indexing. String
indexing is zero-based, which means that the first character of a string has an index
of 0, the second character has an index of 1, and so on.
Here's an example:
string = "hello"
In this example, we create a string "hello" and use indexing to access each character
in the string. We print each character using the print() function.
You can also use negative indexing to access characters from the end of the string.
The last character of a string has an index of -1, the second to last character has an
index of -2, and so on.
string = "hello"
In Python, the str() function is used to convert an object to a string. This function
takes an object as an argument and returns a string representation of the object.
Here's an example:
number = 42
string = str(number)
print(string) # Output: '42'
In this example, we create an integer variable number with a value of 42. We then pass this
variable to the str() function to convert it to a string. The resulting string is stored in the
string variable, which we then print using the print() function.
The str() function can be used to convert a wide range of objects to strings, including
numbers, booleans, lists, dictionaries, and more. Here are some examples:
In each of these examples, we use the str() function to convert an object to a string. The
resulting string is then printed using the print() function.
In Python, you can concatenate two or more strings using the + operator. This operation
combines two or more strings into a single string. Here's an example:
string1 = "hello"
string2 = "world"
result = string1 + " " + string2
print(result) # Output: 'hello world'
In this example, we create two strings string1 and string2 and concatenate them with a
space in between using the + operator. The resulting string is stored in the result variable,
which we then print using the print() function.
1. Equal to: the == operator can be used to check if two strings are equal:
string1 = "hello"
string2 = "world"
if string1 == "hello":
print("string1 is equal to 'hello'")
if string1 == string2:
print("string1 is equal to string2")
else:
print("string1 is not equal to string2")
OUTPUT
string1 is equal to 'hello'
string1 is not equal to string2
2. Not equal to: the != operator can be used to check if two strings are not
equal:
string1 = "hello"
string2 = "world"
if string1 != string2:
print("string1 is not equal to string2")
OUTPUT
string1 is not equal to string2
3. Greater than or less than: the > and < operators can be used to compare two
strings based on their lexicographical order:
string1 = "apple"
string2 = "banana"
if string1 > string2:
print("string1 comes after string2 in lexicographical order")
else:
print("string1 comes before string2 in lexicographical order")
OUTPUT
string1 comes before string2 in lexicographical order
Note that the comparison of strings is case sensitive, which means that the uppercase letters
have a different ASCII code than the lowercase letters and are considered greater in
lexicographical order.
Slicing and joining are two important string operations in Python. Slicing is used to
extract a part of a string, while joining is used to concatenate a list of strings into a
single string. Here's how you can use these operations in Python:
1. Slicing:
Slicing allows you to extract a range of characters from a string by specifying the
start and end indices. You can also use slicing to extract individual characters from a
string.
In this example, we have a string "Hello, World!" and we use slicing to extract
different parts of the string.
The first print() statement extracts the characters from index 0 to 5, which
corresponds to the substring "Hello".
The second print() statement extracts the characters from index 7 to the end of the
string, which corresponds to the substring "World!".
The third print() statement extracts the characters from the second-to-last character
to the fifth-to-last character, which corresponds to the substring "World". Note that
we use negative indexing to specify the start and end indices.
2. Joining:
Joining is used to concatenate a list of strings into a single string. You can use the
join() method to join a list of strings together.
In this example, we have a list of strings fruits and a separator string ", ". We use the
join() method to join the strings in the list together with the separator. The resulting string
is stored in the result variable, which we then print using the print() function. Note that the
separator is inserted between each pair of adjacent strings in the list.
Traversing; in python
Here's an example that demonstrates how to traverse a string using a for loop in
Python:
In this example, we have a string "Hello, World!" and we use a for loop to iterate
over each character in the string. The loop iterates once for each character in the
string, and the print() function is called on each iteration to output the character.
In Python, format specifiers are used to format strings by defining placeholders for
variables that are later filled in with values.
"{field_name:conversion_specifier}".format(value)
Here, field_name is the name of the field that is being filled in, and
conversion_specifier is the conversion specifier that defines how the value should be
formatted. The value argument is the actual value that will be substituted into the
string.
For example, to format an integer value, you could use the following code:
age = 30
print("I am %d years old." % age)
Escape sequences in Python are special characters that are used to represent non-
printable characters in a string or to insert special characters in a string. An escape
sequence is represented by a backslash followed by a character or a combination of
characters.
For example, to insert a new line character in a string, you could use the escape
sequence \n like this:
print("Hello\nworld")
To insert a single quote character in a string that is enclosed in single quotes, you
can use the escape sequence \' like this:
In Python, there are two types of string literals: raw strings and Unicode strings.
1. Raw Strings: A raw string is a string that is prefixed with an r character. It tells
Python to interpret backslashes (\) literally, rather than as escape characters.
This is useful when you want to include backslashes in your string, such as
when working with regular expressions or file paths.
path = r'C:\Users\JohnDoe\Documents'
print(path)
In this example, we have a string path that contains a file path. The string is prefixed
with an r character to indicate that it is a raw string. The backslashes in the string are
interpreted literally, so the resulting output includes the backslashes.
unicode_string = u'こんにちは'
print(unicode_string)
In this example, we have a string unicode_string that contains the Japanese greeting "
こんにちは". The string is prefixed with a u character to indicate that it is a Unicode
string. Because the Unicode standard supports Japanese characters, the string is
encoded correctly and the resulting output displays the Japanese characters.
Note that in Python 3, all strings are Unicode strings by default, so you don't need to
prefix them with a u character. However, you can still use the u prefix for backwards
compatibility with Python 2.
In Python, a string is a sequence of characters enclosed within either single quotes or double
quotes. Python provides a number of built-in methods for manipulating strings. Here are
some commonly used string methods in Python:
4. strip(): removes whitespace from the beginning and end of the string.
string = " Hello, World! "
print([Link]()) # output: Hello, World!
6. split(): splits the string into a list of substrings based on a specified delimiter.
string = "apple,banana,orange"
fruits = [Link](",")
print(fruits) # output: ['apple', 'banana', 'orange']
7. join(): joins a list of strings into a single string with a specified delimiter.
fruits = ['apple', 'banana', 'orange']
string = ",".join(fruits)
print(string) # output: apple,banana,orange
Here are some illustrative programs in Python that demonstrate various string
manipulations:
QUESTION BANK
Unit 2
1 Define Python
How do a you install python? & write a Simple Python Progam with eg.
OR
write a note on python IDE and how you write your first python program
DEfine keywords and write some of the keywords avaible in python language
________________________________________________________________________________
UNIT 3
1) IF
2) ELSE
3) ELIF
3) WHILE
4) BREAK
5) CONTINUE
4. Write a note on
1) range ()
2) exit()
additional questions
______________________________________________________________________________
UNIT 4
or
______________________________________________________________________________
UNIT 5
or
4. Write a note on
1) Concatentaion
2) Comparision
4) traversing