0% found this document useful (0 votes)
3 views26 pages

Bca sem 4 Python

This document provides an introduction to Python, outlining its key features such as being free and open-source, easy to code, and supporting object-oriented programming. It covers various aspects of Python including identifiers, variable declaration, comments, input/output functions, data types, and operations. Additionally, it explains the use of reserved keywords and the import functionality in Python.

Uploaded by

hermonie546
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

Bca sem 4 Python

This document provides an introduction to Python, outlining its key features such as being free and open-source, easy to code, and supporting object-oriented programming. It covers various aspects of Python including identifiers, variable declaration, comments, input/output functions, data types, and operations. Additionally, it explains the use of reserved keywords and the import functionality in Python.

Uploaded by

hermonie546
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

󾠮

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:

1. Free and Open Source


Python language is freely available at the official website and you can
download it from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means
that source code is also available to the public. So you can download it, use
it as well as share it.

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.

5. GUI Programming Support


Graphical User interfaces can be made using a module such as PyQt5,
PyQt4, wxPython, or Tk in python. PyQt5 is the most popular option for
creating graphical apps with Python.

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.

9. Python is a Portable language


Python language is also a portable language. For example, if we have
Python code for windows and if we want to run this code on other platforms
such as Linux, Unix, and Mac then we do not need to change it, we can run
this code on any platform.

10. Python is an Integrated language


Python is also an Integrated language because we can easily integrate
Python with other languages like C, C++, etc.

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.

12. Large Standard Library


Python has a large standard library that provides a rich set of modules and
functions so you do not have to write your own code for every single thing.
There are many libraries present in Python such as regular
expressions, unit-testing, web browsers, etc.

13. Dynamically Typed Language


Python is a dynamically-typed language. That means the type (for example-
int, double, long, etc.) for a variable is decided at run time not in advance
because of this feature we don’t need to specify the type of variable.

14. Front-end and back-end development


With a new project py script, you can run and write Python codes in HTML
with the help of some simple tags <py-script>, <py-env>, etc. This will help
you do front-end development work in Python like java-script. Back-end is
the strong forte of Python it’s extensively used for this work cause of its
frameworks like Django and Flask.

15. Allocating Memory Dynamically


In Python, the variable data type does not need to be specified. The memory
is automatically allocated to a variable at runtime when it is given a value.
Developers do not need to write int y = 18 if the integer value 15 is set to y.
You may just type y=18.

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

and A logical operator

as To create an alias

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

Used with exceptions, a block of code that will be executed no


finally
matter if there is an exception or not
for To create a for loop

from To import specific parts of a module

global To declare a global variable

Python: Module I 4
Keyword Description

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To end a function, returns a generator

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.

The first character of the variable must be an alphabet or underscore ( _


).

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 (!,
@, #, %, ^, &, *).

Identifier name must not be similar to any keyword defined in the


language.

Identifier names are case sensitive; for example, my name, and


MyName is not the same.

Examples of valid identifiers: a123, _n, n_9, etc.

Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values


Python does not bind us to declare a variable before using it in the
application. It allows us to create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any
value to the variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

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 –

Single line Comments


Python single-line comment starts with the hashtag symbol (#) with no
white spaces and lasts till the end of the line. If the comment exceeds
one line then put a hashtag on the next line and continue the comment.
Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions

# Print “Hello !” to console


print("Hello !")

Multiline Comments
Python does not provide the option for multiline comments. However,
there are different ways through which we can write multiline comments.

Using Multiple Hashtags (#)


We can multiple hashtags (#) to write multiline comments in Python. Each
and every line will be considered as a single-line comment.

# Python program to demonstrate


# multiline comments
print("Multiline comments")

Using String Literals


Python ignores the string literals that are not assigned to a variable so we
can use these string literals as a comment.

Python: Module I 7
'This will be ignored by Python'

Multiline comments using string literals

""" Python program to demonstrate


multiline comments"""
print("Multiline comments")

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.

def multiply(a, b):


"""Multiplies the value of a and b"""
return a*b

# Print the docstring of multiply function


print(multiply.__doc__)

Input and output function


Q. How to take input from the user?

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:

# Python input() function example


# Calling function
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)

Q. How to Write output to the Console?

Print()
In Python, we can simply use the print() function to print output.

print('Python is powerful')

# Output: 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

print(object= separator= end= file= flush= )

Here,

object - value(s) to be printed

sep (optional) - allows us to separate multiple objects inside print() .

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)

flush (optional) - boolean specifying if the output is flushed or buffered.


Default: False

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.

2. - This imports a specific function


from module_name import function_name

from a module, making it available directly in your script without having


to use the module_name. prefix.

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)

print(y) # Output: 4.0

from math import sqrt

x = 16
y = sqrt(x)

print(y) # Output: 4.0

Data Types and Operations


int
: An int is a whole number with no fractional component. For
int

example, 5 and -3 are both integers. In Python, integers have unlimited


precision, so you can perform arithmetic operations on very large or very
small integers

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 Strings are immutable, meaning you cannot change individual


characters in a string once it has been defined. However, you can create a
new string by concatenating or slicing the original string.

Operations performed on String


1. Concatenation: You can concatenate two or more strings using the +

operator. For example:

Python: Module I 12
x = "Hello, "
y = "World!"
z = x + y
print(z) # Output: Hello, World!

2. Slicing: You can access individual characters or sub-strings within a


string using slicing. Slicing is done using the square bracket notation
( [] ). For example:

x = "Hello, World!"
print(x[0]) # Output: H
print(x[7:12]) # Output: World

3. Formatting: You can format strings using the format() method or f-


strings. The format() method replaces placeholders {} with values
passed as arguments. For example:

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

Alternatively, you can use f-strings (formatted string literals), which


allow you to embed expressions inside string literals. F-strings start with
an f prefix and use curly braces {} to enclose expressions. For
example:

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:

my_list = [1, 2, 3, "four", 5.0]


print(my_list) # Output: [1, 2, 3, 'four', 5.0]

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:

my_list = [1, 2, 3, "four", 5.0]


print(my_list[0]) # Output: 1
print(my_list[3]) # Output: 'four'

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:

my_list = [1, 2, 3, "four", 5.0]


print(my_list[1:3]) # Output: [2, 3]

3. Appending: You can add an item to the end of a list using the append()

method.
Eg:

my_list = [1, 2, 3, "four", 5.0]


my_list.append(6)
print(my_list) # Output: [1, 2, 3, 'four', 5.0, 6]

4. Concatenation : You can concatenate two or more lists using the +

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.

thisset = {"apple", "banana", "cherry"}


print(thisset)

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:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

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:

my_dict = {"name": "Alice", "age": 25}


my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Basic Operations in Dictionary


1. Adding a key-value pair:

my_dict = {"name": "Alice", "age": 25}


my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

2. Updating a value:

my_dict = {"name": "Alice", "age": 25}


my_dict["age"] = 30
print(my_dict) # Output: {'name': 'Alice', 'age': 30}

Python: Module I 16
3. Removing a key-value pair:

my_dict = {"name": "Alice", "age": 25, "city": "New York"}


del my_dict["city"]
print(my_dict) # Output: {'name': 'Alice', 'age': 25}

Mutable and Immutable Objects


Immutable
An immutable object is an object whose state cannot be changed once it
is created. Examples of immutable objects in Python include integers,
floats, strings, and tuples. If you modify an immutable object, a new
object is created instead of modifying the original object. For example:

a = 5
b = a
a = a + 1
print(a) # Output: 6
print(b) # Output: 5

In this example, the value of a is incremented, but the value of b

remains the same. This is because integers are immutable objects in


Python, and a + 1 creates a new integer object instead of modifying the
original a object.

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.

Data Type Conversion


It is possible to convert one data type to another in Python using type
conversion functions.

The functions are :

1. int() : Converts a value to an integer data type. If the value is a float,


the decimal part is truncated. If the value is a string, it must contain only
digits and an optional sign. For example:

a = int(3.5)
b = int("42")
print(a) # Output: 3
print(b) # Output: 42

2. float() : Converts a value to a float data type. If the value is an integer, it


is converted to a float. If the value is a string, it must contain only digits,
an optional sign, and an optional decimal point. For example:

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"

4. list() : Converts a sequence (e.g., a tuple or a string) to a list data type.


For example

a = list((1, 2, 3))
b = list("hello")
print(a) # Output: [1, 2, 3]
print(b) # Output: ['h', 'e', 'l', 'l', 'o']

5. tuple() : Converts a sequence to a tuple data type. For example:

a = tuple([1, 2, 3])
b = tuple("hello")
print(a) # Output: (1, 2, 3)
print(b) # Output: ('h', 'e', 'l', 'l', 'o')

6. dict() : Converts a sequence of key-value pairs (e.g., a list of tuples) to


a dictionary data type. For example:

a = dict([(1, "one"), (2, "two"), (3, "three")])


print(a) # Output: {1: 'one', 2: 'two', 3: 'three'}

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 .

The if statement is used to test a single condition and execute a block


of code only if that condition is true. Here's an example:

x = 5
if x > 0:
print("x is positive")

In this example, the if statement tests whether x is greater than 0, and


if it is, it executes the block of code that prints "x is positive".

The else statement is used in conjunction with an if statement to


execute a block of code if the if condition is false. Here's an example:

x = -5
if x > 0:
print("x is positive")
else:
print("x is not positive")

In this example, because x is not greater than 0, the if condition is


false and the program executes the block of code under the else
statement, which prints "x is not positive".

The elif statement is used to test additional conditions after an if

statement and execute different blocks of code depending on which


condition is true. Here's an example:

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.

A for loop is used to iterate over a sequence of elements, such as a list


or a range of numbers. Here's an example:

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

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:

1. range(stop) : This generates a sequence of numbers from 0 up to (but


not including) stop . For example:

for i in range(5):
print(i)

Python: Module I 21
#This will print the numbers 0, 1, 2, 3, and 4.

2. range(start, stop) : This generates a sequence of numbers starting


from start up to (but not including) stop . For example:

for i in range(2, 7):


print(i)
#This will print the numbers 2, 3, 4, 5, and 6.

3. range(start, stop, step): This generates a sequence of numbers


starting from start , up to (but not including) stop , incrementing by
step each time. For example:

for i in range(0, 10, 2):


print(i)
#This will print the numbers 0, 2, 4, 6, and 8.

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

The condition is a Boolean expression that is evaluated before each


iteration of the loop. If the condition is True , the code inside the loop
body will execute. This process will continue until the condition becomes
False .
For example, here's a while loop that prints the numbers 0 to 4:

Python: Module I 22
i = 0
while i < 5:
print(i)
i += 1

In this example, the variable i is initialized to 0. The while loop


continues to execute as long as i is less than 5. Inside the loop, the
value of i is printed and then incremented by 1 using the += operator.
This process continues until i is no longer less than 5.
It's important to be careful when using while loops, as it's possible to
create an infinite loop if the condition is never False . For example, the
following code will create an infinite loop:

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 .

Loop Control Statements


Break
The break statement is used to exit a loop prematurely. When the break

statement is encountered inside a loop, the loop is immediately


terminated, and the program continues with the next statement after the
loop.

The break statement can be used inside both for and while loops.
Here's an example of using break in a for loop:

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
if fruit == "banana":

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.

Here's an example of using break in a while loop:

i = 0
while i < 5:
if i == 3:
break
print(i)
i += 1

In this example, the while loop continues to execute as long as i is less


than 5. If the value of i is equal to 3, the break statement is executed,
and the loop terminates early. Otherwise, the program prints the value of
i and increments it by 1.
The break statement can be a useful tool for controlling the flow of a
loop, but it should be used sparingly. In general, it's better to use
conditional statements and other control flow constructs to create loops
that terminate naturally when a certain condition is met.

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.

Here's an example of using continue in a while loop:

i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)

In this example, the while loop continues to execute as long as i is less


than 5. If the value of i is equal to 3, 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
iteration. Otherwise, the program prints the value of i .
The continue statement can be a useful tool for controlling the flow of a
loop and skipping over certain iterations based on a certain condition.
However, it should be used with care to avoid creating confusing and
hard-to-understand code.

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.

The pass statement can be used in a variety of situations, such as:

Defining a new function or class that you haven't implemented yet:

def my_function():
pass

Creating a placeholder for a conditional statement that you haven't


written yet:

if x > 5:
pass
else:
# code to handle case where x is less than or equal to 5

Creating a placeholder for a loop that you haven't written yet:

while True:
# code to handle current iteration
if done:
break
else:
pass # placeholder for future loop iteration

The pass statement is especially useful when you're working on code


incrementally, and you want to create a placeholder for a block of code
that you'll fill in later. It allows you to create syntactically correct code
without having to worry about the implementation details at the moment.

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

You might also like