Bca sem 4 Python
Bca sem 4 Python
Python: Module I
Introduction to python
Features of Python
Python is a high-level, interpreted programming language that is known for
its simplicity, readability, and ease of use. Some of its key features include:
2. Easy to code
Python is a high-level programming language. Python is very easy to
learn the language as compared to other languages like C, C#, Java-script,
Java, etc. It is very easy to code in the Python language and anybody can
learn Python basics in a few hours or days. It is also a developer-friendly
language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established,
Python’s syntax is really straightforward. The code block is defined by the
indentations rather than by semicolons or brackets.
4. Object-Oriented Language
Python: Module I 1
One of the key features of Python is Object-Oriented programming.
Python supports object-oriented language and concepts of classes, object
encapsulation, etc.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do
not need to remember the system architecture, nor do we need to manage
the memory.
7. Extensible feature
Python is an Extensible language. We can write some Python code into C
or C++ language and also we can compile that code in C/C++ language.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify
and correct the majority of your program’s issues once you understand how
to interpret Python’s error traces. Simply by glancing at the code, you can
determine what it is designed to perform.
Python: Module I 2
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by
line at a time. like other languages C, C++, Java, etc. there is no need to
compile Python code this makes it easier to debug our code. The source
code of Python is converted into an immediate form called byte-code.
Identifiers
In Python, an identifier is a name that is used to identify variables, functions,
classes, modules, or other objects in a program. An identifier can consist of
Python: Module I 3
letters, numbers, and underscores, but it cannot start with a number. It is
also case-sensitive, meaning that myVariable and myvariable are considered
different identifiers.
Good naming conventions for identifiers include using descriptive names that
indicate the purpose or function of the object they identify. Additionally, it is
recommended to use lowercase letters for variable and function names, and
uppercase letters for class names.
Reserved keywords
Python has a set of keywords that are reserved words that cannot be used
as variable names, function names, or any other identifiers:
Keyword Description
as To create an alias
Python: Module I 4
Keyword Description
or A logical operator
Variables
Variable is a name that is used to refer to memory location. Python variable
is also known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a
infer language and smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to
begin with a letter or an underscore.
Identifier Naming
Python: Module I 5
Variables are the example of identifiers. An Identifier is used to identify the
literals used in the program. The rules to name an identifier are given below.
All the characters except the first character may be an alphabet of lower-
case(a-z), upper-case (A-Z), underscore, or digit (0-9).
Identifier name must not contain any white-space, or special character (!,
@, #, %, ^, &, *).
x = <value>
Eg:
x = 55
y ="hello"
Python: Module I 6
Comments
Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program. Comments enhance the
readability of the code and help the programmers to understand the code
very carefully. There are three types of comments in Python –
Multiline Comments
Python does not provide the option for multiline comments. However,
there are different ways through which we can write multiline comments.
Python: Module I 7
'This will be ignored by Python'
Docstring Comments
Python docstring is the string literals with triple quotes that are
appeared right after the function. It is used to associate documentation
that has been written with Python modules, functions, classes, and
methods. It is added right below the functions, modules, or classes to
describe what they do. In Python, the docstring is then made available
via the __doc__ attribute.
input()
Python input() function is used to get input from the user. It prompts the user
to input and reads a line. After reading data, it converts it into a string and
returns that. It throws an error EOF Error if EOF is read.
Python: Module I 8
input ([prompt])
Example:
Print()
In Python, we can simply use the print() function to print output.
print('Python is powerful')
Here, the print() function displays the string enclosed inside the single
quotation.
Syntax of print()
In the above code, the print() function is taking a single parameter.
Python: Module I 9
However, the actual syntax of the print function accepts 5 parameters
Here,
end (optional) - allows us to add add specific values like new line "\n" ,
tab "\t"
file (optional) - where the values are printed. It's default value
is sys.stdout (screen)
Import function
In Python, import is a keyword that is used to bring code from external
modules or packages into your current script or program. This allows you to
reuse code that has already been written, instead of having to write
everything from scratch.
There are a few different ways to use the import keyword in Python,
including:
1. import module_name - This imports an entire module and makes all of its
functions, classes, and variables available in your script using the
module_name.function_name syntax.
3. from module_name import * - This imports all functions and variables from a
module, but this is generally not recommended as it can lead to naming
conflicts and make your code harder to read.
Python: Module I 10
Eg :
import math
x = 16
y = math.sqrt(x)
x = 16
y = sqrt(x)
eg:
x = 5
print(type(x)) # Output: <class 'int'>
float
float :A float is a number with a fractional component. For example, 3.14
and -2.5 are both floats. In Python, floating-point numbers have limited
precision, so you should be careful when performing arithmetic operations
on them.
Python: Module I 11
eg:
x = 3.14
print(type(x)) # Output: <class 'float'>
Complex
complex :A complex number is a number with both a real and imaginary
component. It is defined as a + bj , where a and b are both floats, and j is
the imaginary unit. For example, 2 + 3j is a complex number with a real
component of 2 and an imaginary component of 3 .
eg:
x = 2 + 3j
print(type(x)) # Output: <class 'complex'>
Strings
A string is a built-in data type that represents a sequence of characters. A
string can be defined using either single quotes ( ' ) or double quotes ( " ).
Eg:
x = "Hello, World!"
print(x) # Output: Hello, World!
Python: Module I 12
x = "Hello, "
y = "World!"
z = x + y
print(z) # Output: Hello, World!
x = "Hello, World!"
print(x[0]) # Output: H
print(x[7:12]) # Output: World
name = "Alice"
age = 25
message = "My name is {} and I am {} years old".format(name, age)
print(message) # Output: My name is Alice and I am 25 years old
name = "Alice"
Python: Module I 13
age = 25
message = f"My name is {name} and I am {age} years old"
print(message) # Output: My name is Alice and I am 25 years old
List
A list is a built-in data type that represents a collection of items. Lists are
created by enclosing a sequence of comma-separated items in square
brackets [] .
Eg:
Lists can contain items of different types, including numbers, strings, and
other objects. You can access individual items in a list using indexing, which
starts at 0.
Operations on Lists
1. Indexing: You can access individual items in a list using indexing
Eg:
2. Slicing: You can access a subset of items in a list using slicing. Slicing
is done using the square bracket notation ( [] ).
Python: Module I 14
Eg:
3. Appending: You can add an item to the end of a list using the append()
method.
Eg:
operator.
Eg:
list1 = [1, 2, 3]
list2 = ["four", 5.0]
list3 = list1 + list2
print(list3) # Output: [1, 2, 3, 'four', 5.0]
Set
Sets are used to store multiple items in a single variable.
Python: Module I 15
Dictionary
A dictionary is a built-in data type that represents a collection of key-value
pairs. Dictionaries are created by enclosing a comma-separated list of key-
value pairs in curly braces {} .
Eg:
In this example, "name" , "age" , and "city" are the keys, and "Alice" , 25 ,
and "New York" are the corresponding values.
You can access the value associated with a key in a dictionary using square
bracket notation [] . For example:
2. Updating a value:
Python: Module I 16
3. Removing a key-value pair:
a = 5
b = a
a = a + 1
print(a) # Output: 6
print(b) # Output: 5
Mutable
A mutable object is an object whose state can be changed after it is
created. Examples of mutable objects in Python include lists, dictionaries,
and sets. If you modify a mutable object, the original object is modified
instead of creating a new object. For example:
a = [1, 2, 3]
b = a
a.append(4)
Python: Module I 17
print(a) # Output: [1, 2, 3, 4]
print(b) # Output: [1, 2, 3, 4]
In this example, the append() method modifies the original a list, and the
value of b also changes because both a and b refer to the same list
object.
Immutable objects are useful for situations where you want to ensure that
the state of an object cannot be changed accidentally, while mutable
objects are useful for situations where you want to modify the state of an
object over time.
a = int(3.5)
b = int("42")
print(a) # Output: 3
print(b) # Output: 42
a = float(3)
b = float("3.14")
print(a) # Output: 3.0
print(b) # Output: 3.14
Python: Module I 18
3. str() : Converts a value to a string data type. If the value is an integer or
float, it is converted to a string. For example:
a = str(42)
b = str(3.14)
print(a) # Output: "42"
print(b) # Output: "3.14"
a = list((1, 2, 3))
b = list("hello")
print(a) # Output: [1, 2, 3]
print(b) # Output: ['h', 'e', 'l', 'l', 'o']
a = tuple([1, 2, 3])
b = tuple("hello")
print(a) # Output: (1, 2, 3)
print(b) # Output: ('h', 'e', 'l', 'l', 'o')
Flow Control
Decision Making
Decision-making is done using conditional statements, which allow the
program to execute different blocks of code depending on whether a certain
Python: Module I 19
condition is true or false. The three main conditional statements used for
decision-making in Python are if , else , and elif .
x = 5
if x > 0:
print("x is positive")
x = -5
if x > 0:
print("x is positive")
else:
print("x is not positive")
x = 0
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
Python: Module I 20
In this example, the if statement tests whether x is greater than 0, but
because x is actually equal to 0, that condition is false. The program
then moves on to the elif statement, which tests whether x is less
than 0, and since that condition is also false, the program executes the
block of code under the else statement, which prints "x is zero".
Loops
For
loops are used to execute a block of code repeatedly. There are two main
types of loops in Python: for loops and while loops.
In this example, the for loop will iterate over the list of fruits and print
each one. The variable fruit takes on the value of each element in the
list, one at a time, and the code in the loop body executes for each
element.
Range
The range() function is often used in for loops to generate a sequence
of numbers to iterate over. The range() function takes one, two, or three
arguments, depending on how you want to use it:
for i in range(5):
print(i)
Python: Module I 21
#This will print the numbers 0, 1, 2, 3, and 4.
While
A while loop is used to execute a block of code repeatedly as long as a
certain condition is true. The basic syntax of a while loop is as follows:
while condition:
# code to execute while condition is true
Python: Module I 22
i = 0
while i < 5:
print(i)
i += 1
while True:
print("Hello, world!")
In this case, the condition is always True , so the loop will never exit. To
avoid this, make sure that the condition will eventually become False .
The break statement can be used inside both for and while loops.
Here's an example of using break in a for loop:
Python: Module I 23
break
print(fruit)
In this example, the for loop iterates over the list of fruits. If the current
fruit is a banana, the break statement is executed, and the loop
terminates early. Otherwise, the program prints the name of the current
fruit.
i = 0
while i < 5:
if i == 3:
break
print(i)
i += 1
Continue
The continue statement is used to skip over the remaining statements in
the current iteration of a loop and continue with the next iteration. When
the continue statement is encountered inside a loop, the program
immediately goes back to the beginning of the loop and evaluates the
loop condition again.
The continue statement can be used inside both for and while loops.
Here's an example of using continue in a for loop:
Python: Module I 24
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "banana":
continue
print(fruit)
#Ouput => apple cherry
In this example, the for loop iterates over the list of fruits. If the current
fruit is a banana, the continue statement is executed, and the program
skips over the remaining statements in the loop body for this iteration.
The loop then continues with the next item on the list. Otherwise, the
program prints the name of the current fruit.
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
Pass
The pass statement is a placeholder statement that does nothing. It is
used in situations where you need a statement syntactically, but you don't
Python: Module I 25
want to execute any code.
def my_function():
pass
if x > 5:
pass
else:
# code to handle case where x is less than or equal to 5
while True:
# code to handle current iteration
if done:
break
else:
pass # placeholder for future loop iteration
In summary, the pass statement is a statement that does nothing, but it's
useful as a placeholder when you need a statement syntactically, but you
don't want to execute any code.
Python: Module I 26