0% found this document useful (0 votes)
2 views61 pages

Unit1 Python

The document provides an introduction to Python, detailing its characteristics as an interpreted, object-oriented, general-purpose programming language. It covers Python's history, features, applications, and data types, along with installation instructions and code execution methods. Additionally, it explains the differences between various data types such as numbers, strings, lists, tuples, and sets.

Uploaded by

veena more
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)
2 views61 pages

Unit1 Python

The document provides an introduction to Python, detailing its characteristics as an interpreted, object-oriented, general-purpose programming language. It covers Python's history, features, applications, and data types, along with installation instructions and code execution methods. Additionally, it explains the differences between various data types such as numbers, strings, lists, tuples, and sets.

Uploaded by

veena more
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

UNIT1 INTRODUCTION TO PYTHON 1

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 2

What is PYTHON?
Python is a Interpreted, Object oriented, General purpose, high level
programming language.
• Interpreted- Python code is executed line by line by an interpreter
at runtime, rather than being compiled into machine code.
• Object oriented- Python is built around the concept of objects and
classes, which allows you to organize code in a reusable and
modular way.
• General purpose means it can be used for multiple application
such as data science, machine learning, desktop application, web
application, scripts etc.
• High level programming language means human understandable
language i.e Human readable.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 3

History of PYTHON
 It was created by Guido Van Rossum, and released in 1989.
 Guido Van Rossum is fan of ‘MONTY PYTHON’S FLYING
CIRCUS’, this is a famous tv show in Netherlands.
 Named after Monty Python.
 Open source can be downloaded from [Link]
 First version of python released in 1991.
 In 1994, python 1.0 was released with new feature which map, filter,
lambda.
 Python 2.X also add some more feature like comprehensions, garbage
collection system.
 After python 2.X, python 3.X released in 2008.

Why PYTHON ?
• Python works on different platforms (windows, mac, linux, raspberry pi,
etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written.

Applications of PYTHON
 Network Programming
 Data Analysis
 Robotics
 Website & Application development
 Desktop Application
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 4

 Games development
 Data visualization
 Scientific calculation
 Machine Language & Artificial Intelligence
 3D Application Development
 Audio & Video software development
 Google, Netflix, NASA, Quora, Facebook
Features of PYTHON
1) simple :
 Python is a simple programming language.
 When we read python program, we can feel like reading english
statements.
 It means more clarity and less stress on understanding the syntax of the
language.
2) easy to learn:
 Python uses very few keywords.
 Its programs use very simple structure.
 Developing programs in python is easy.
3) Open source:
 There is no need to pay for python software.
 Python can be freely downloaded from [Link] website.
 Its source code can be read, modified and can be used in programs as
desired by the programmers.
4) High level language:
 High level languages use english words.
 These are easy to learn and use. Like COBOL, PHP or java,
 Python also uses english words in its programs
5) Dynamically typed:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 5

 In python, we need not declare datatype for variables . whenever we are


assigning the value, based on value, type will be allocated automatically
 But java, c etc are statically typed languages because we have to provide
datatype at the beginning only.
6) Platform independent:
 When a python program is compiled using a python compiler, it generates
byte code.
 Python’s byte code represents a fixed set of instructions that run on all
operating systems and hardware.
 We can use python on almost all operating systems like UNIX, linux,
windows etc.
7) Portable:
once a python program is written, it can run on any computer system using python
virtual machine(pvm).
8) procedure and object oriented:
 Python is a procedure oriented as well as an object oriented
programming language.
 In procedure oriented programming languages(ex c and pascal), the
programs are built using functions and procedures.
 But in objected oriented languages(ex c++ and java), the programs uses
classes and objects
INSTALLATION OF PYTHON

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 6

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 7

IDLE python 3.11


Pythons integrated development and learning environment

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 8

Types
 Python shell
• Python shell is a command line tool that starts up the python
interpreter.
• You can test simple programs and also write some short
programs.
 Python editor
• More complexed python program you need an editor.
• Idle, on the other hand, has combined the above two needs and
bundled them as a package
<<< Python Prompt: It shows that python is ready to accept your
command or instruction.
• You can type python statements or expressions right after >>> and
press enter to execute them.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 9

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 10

Python IDLE
 Is a graphical user interface which is completely written in Python.
 An Integrated Development Environment (IDLE) is a bundled set of software
tools for program development.
 An editor for creating and modifying programs
 A translator for executing programs
 A program debugger provides a means of taking control of the execution of
a program to aid in finding program errors
 The Python Standard Library is a collection of modules, each providing
specific functionality beyond what is included in the core part of Python.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 11

WORKING WITH PYTHON


PYTHON CODE EXECUTION:
Python’s traditional runtime execution model: Source code you type is
translated to byte code, which is then run by the Python Virtual Machine (PVM).
Your code is automatically compiled, but then it is interpreted.

The image illustrates how Python code is executed, highlighting the


roles of source code, bytecode, and the Python Virtual Machine (PVM).
Here's a step-by-step explanation:
1. Source Code ([Link])
o You write your Python program in a file with the .py
extension.
o Example: [Link] might contain Python code like print("Hello").
2. Bytecode ([Link])
o When Python executes the source file, it first compiles it into an
intermediate form called bytecode.
o This compiled file has the .pyc extension.
o Bytecode is a lower-level, platform-independent representation of
your source code, optimized for execution.
3. Runtime Execution (PVM: Python Virtual Machine)
o The .pyc bytecode is executed by the Python Virtual Machine
(PVM).
o The PVM interprets the bytecode instructions and performs
the actual computations on the machine.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 12

There are two modes for using the Python interpreter:


• Interactive Mode
• Script Mode

Running Python in interactive mode:


Without passing python script file to the interpreter, directly execute code to
Python prompt.
Once you’re inside the python interpreter, then you can start.
>>> print("hello world")
hello world #output
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it.
[0, 1, 2] #output
>>> 2+3
5 #output

# To verify the type of any object in Python, use the type() function:
>>>type(10)
<class ‘int’> #output
>>>type(10.11)
<class ‘float’> #output
>>>type(“hello”)
<class ‘str’> #output
>>>type(‘h’)

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 13

<class ‘str’> #output

Running Python in script mode:


Programmers can store Python script source code in a file with the .py
extension, and use the interpreter to execute the contents of the file.
To execute the script by the interpreter, you have to tell the interpreter the name
of the file. Working with the interactive mode is better when Python
programmers deal with small pieces of code as you can type and execute the
immediately, but when the code is more than 2-4 lines, using the script for
coding can help to modify and use the code in future.

COMMENTS:
Single-line comments begins with a hash(#) symbol and is useful in
mentioning that the whole line should be considered as a comment until the end
of line.
A Multi line comment is useful when we need to comment on many lines. In
python, triple double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line
commenting.

DATATYPES IN PYTHON
• A datatype represents the type of data stored into a variable or memory
and determines what operations can be done on it.
• In Python, there is no limit for the size of an datatype.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 14

[Link]:
 Number data type stores Numerical Values.
 This data type is immutable [i.e. values/items cannot be changed].
 Python supports integers, floating point numbers and complex
numbers.
 They are defined as,

Example
a = 10
print(a) # Output: 10
print(type(a)) # Output: <class 'int'>

Example
b = 10.5
print(b) # Output: 10.5
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 15

print(type(b)) # Output: <class 'float'>

Example
c = 2 + 3j
print(c) # Output: (2+3j)
print(type(c)) # Output: <class 'complex'>

[Link]
In Python, Boolean (bool) is a data type that represents one of two
values:
 True
 False
Example
x = True
y = False
print(x) # Output: True
print(y) # Output: False
print(type(x)) # Output: <class 'bool'>

[Link]
 A sequence is an ordered collection of items, indexed by positive integers.
 It is a combination of mutable (value can be changed) and immutable
(values cannot be changed) data types.
 There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 16

 A String in Python consists of a series or sequence of characters


 Strings in python are surrounded by either single quotation marks, or
double quotation marks.
 'hello' is the same as "hello".
 Individual character in a string is accessed using a subscript (index).
 Characters can be accessed using indexing and slicing operations
 Strings are immutable i.e. the contents of the string cannot be changed
after it is created.
Example:
print("Hello")
print('Hello')
OUTPUT
Hello
Hello

OPERATIONS ON STRING
[Link]
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 17

Lists
 List is an ordered sequence of items. Values in the list are called elements
/ items.
 It can be written as a list of comma-separated items (values) between
square brackets[ ].
 Items in the lists can be of different data types.
EXAMPLE
my_list = [10, 20, 30]
my_list[1] = 25 # Updating value
print(my_list) # Output: [10, 25, 30]
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion

EXAMPLE ON TUPLE

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 18

my_tuple = (10, 20, 30)


# my_tuple[1] = 25 → This will cause an error
print(my_tuple) # Output: (10, 20, 30)

iii)Tuple
 tuple is same as list, except that the set of elements is enclosed in
parentheses instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't
add elements to a tuple or remove elements from the tuple.
Benefit of Tuple:
 Tuples are faster than lists.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 19

 If the user wants to protect the data from accidental changes, tuple can
be used.
 Tuples can be used as keys in dictionaries, while lists can't.

Altering the tuple data type leads to error. Following error occurs when user
tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment

[Link]
 A set is an unordered collection of unique elements.
 It is mutable (can add or remove items).
 Duplicates are automatically removed.
EXAMPLE ON SETS
a = {1, 2, 3}
b = {3, 4, 5}
print([Link](b)) # {1, 2, 3, 4, 5}
print([Link](b)) # {3}
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 20

print([Link](b)) # {1, 2}

Method Example Output Description

Adds a single element to


add() a = {1,2}; [Link](3) {1, 2, 3}
the set

Removes specified
remove() a = {1,2,3}; [Link](2) {1, 3} element (Error if not
found)

Removes element if
discard() a = {1,2}; [Link](3) {1, 2} present (No error if
absent)

Random
Removes and returns a
pop() a = {1,2,3}; [Link]() element
random element
removed

Removes all elements


clear() a = {1,2}; [Link]() set()
from the set

Combines all elements


union() {1,2}.union({2,3}) {1, 2, 3}
from both sets

Returns common
intersection() {1,2}.intersection({2,3}) {2}
elements

Elements in first set but


difference() {1,2,3}.difference({2,3}) {1}
not in second

Checks if all elements of


issubset() {1,2}.issubset({1,2,3}) True
one set are in another

[Link]:
 Dictionaries fall under Mappings and are mutable
 Lists are ordered sets of objects, whereas dictionaries are unordered
sets.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 21

 Dictionary is created by using curly brackets. i,e. {}


 Dictionaries are accessed via keys and not via their position.
 The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value-pairs(The association of a key and a value is
called a key-value pair )
 Dictionaries don't support the sequence operation of the sequence data
types like strings, tuples and lists.

If you try to access a key which doesn't exist, you will get an error
message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
KeyError: 'car'

EXAMPLE ON DICTIONARY
# Creating a dictionary
student = {
"name": “Sowmya",
"age": 25,
"course": "BCA"

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 22

}
# Accessing values
print(student["name"]) # Output: Sowmya
print(student["age"]) # Output: 25
# Adding a new key-value pair
student["grade"] = "A"
print(student)
# Output: {'name': ‘Sowmya', 'age': 25, 'course': 'BCA', 'grade': 'A'}

VARIABLES, EXPRESSIONS AND STATEMENTS


VALUES AND TYPES
 A value is one of the basic things a program works with.
 It may be like 2, 10.5, “Hello” etc.
 Each value in Python has a type. Type of 2 is integer; type of 10.5 is floating
point number; “Hello” is string etc.
 The type of a value can be checked using type function as shown below
>>> type("hello")
<class 'str'>
>>> type(3)
<class 'int'>
>>> type(10.5)
<class 'float'>
>>> type("15")
<class 'str'>
 In the above four examples, one can make out various types str, int and
float.
 Observe the 4th example – it clearly indicates that whatever enclosed
within a double quote is a string.
Variables

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 23

• A variable which helps to store a value in the program.


• Variables may take value that can be modified wherever required
in the program.
• Note that, in python, a variable need not be declared with a specific type
before its usage.
• Whenever we want a variable, just use it. The type of it will be decided
by the value assigned to it.
• A value can be assigned to a variable using assignment operator (=).

Assigning value to variable:


• Value should be given on the right side of assignment operator(=)
and variable on left side.
Example: >>>Counter =45
Print(counter)
• Assigning a single value to several variables simultaneously:
Example:>>> a=b=c=100
• Assigning multiple values to multiple variables:
Example:>>> a,b,c=2,4,"ram" //Unpacking

RULES FOR PYTHON VARIABLES:


• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and
underscores (a-z, 0-9)
• which is usually used to combine variables with two words like
my_salary, student_name etc. no other special characters like @, $ etc.
are allowed.
• variable names are case-sensitive (age, Age and AGE are three
different variables)
• Keywords should not use as a variable name.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 24

Examples of illegal variable names


• 1var (starts with a digit)
• My-variable (contains a hyphen)
• My var (contains a space)
• Class (is a reserved keyword)
• @Count (contains a special character)

KEYWORDS
• Keywords are the reserved words in python.
• We cannot use a keyword as variable name, function name or any other
identifier.
• They are used to define the syntax and structure of the python language.
• Keywords are case sensitive

IDENTIFIERS
• Identifier is the name given to entities like class, functions,
variables etc. In python.
• Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (a to z) or digits (0 to 9) or an underscore (_).
• An identifier cannot start with a digit.
• Keywords cannot be used as identifiers.
• Cannot use special symbols like !, @, #, $, % etc. In our identifier.
• Identifier can be of any length.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 25

Statements
• A statement is a small unit of code that can be executed by the python
interpreter.
• It indicates some action to be carried out.
• In fact, a program is a sequence of such statements.
• Two kinds of statements are: print being an expression statement and
assignment statement
Following are the examples of statements –
>>> print("hello") #printing statement
hello
>>> x=5 #assignment statement
>>> print(x) #printing statement

Operators and Operands


• Special symbols used to indicate specific tasks are called as
operators.
• An operator may work on single operand (unary operator) or two
operands (binary operator).
• There are several types of operators like arithmetic operators,
relational operators, logical operators etc. in python.
• Arithmetic operators are used to perform basic operations as listed in
table:

Operator Meaning Example

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 26

+ Addition Sum= a+b

- Subtraction Diff= a-b

* Multiplication Pro= a*b

/ Division Q = a/b
X = 5/3
(X will get a value
1.666666667)

// Floor Division – returns only F = a//b


integral part after division
X= 5//3
(X will get a value 1)

% Modulus remainder after R = a %b


division
(Remainder after
dividing a by b)

** Exponent E = x** y (means x to


the power of y

• Relational or comparison operators are used to check the relationship


(like less than, greater than etc) between two operands.
• These operators return a boolean value – either true or false.

Assignment operators: apart from simple assignment operator = which


is used for assigning values to variables, python provides compound
assignment operators.
For example,
x=x+y can be written as x+=y
• Now, += is compound assignment operator.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 27

• Similarly, one can use most of the arithmetic and bitwise operators
(only binary operators, but not unary) like *, /, %, //, &, ^ etc. As
compound assignment operators.
Example:
>>> x=3
>>> y=5
>>> x+=y #x=x+y
>>> print(x)
8

Example:
>>> y//=2 #y=y//2
>>> print(y)
2 #ONLY INTEGER part will be printed

Expressions
• A combination of values, variables and operators is known as
expression.
• Following are few examples of expression –
x=5
y=x+10
z= x-y*3
• The python interpreter evaluates simple expressions and gives
results even without print().
For example,
>>> 5
5 #displayed as it is
>>> 1+2

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 28

3 #displayed the sum

ORDER OF OPERATIONS
• When an expression contains more than one operator, the evaluation of
operators depends on the precedence of operators.
• The python operators follow the precedence rule (which can be
remembered as pemdas) as given below –
 Parenthesis have the highest precedence in any expression.
 The operations within parenthesis will be evaluated first.
 For example, in the expression (a+b)*c, the addition has to be
done first and then the sum is multiplied with c.
 Exponentiation has the 2nd precedence.
 But, it is right associative. That is, if there are two exponentiation
operations continuously, it will be evaluated from right to left (unlike
most of other operators which are evaluated from left to right).
for example,
>>> print(2**3) #it is 23
8
>>> print(2**3**2) ie., 232
512

• Multiplication and Division are the next priority. out of these two
operations, whichever comes first in the expression is evaluated.
>>> print(5*2/4) #multiplication and then division 2.5
>>> print(5/4*2) #division and then multiplication 2.5
• Addition and Subtraction are the least priority. out of these two
operations, whichever appears first in the expression is evaluated i.e.,
they are evaluated from left to right

String Operations
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 29

• String concatenation can be done using + operator as shown


below –
>>> x="32"
>>> y="45"
>>> print(x+y)
3245
• observe the output: here, the value of y (a string “45”, but not a
number 45) is placed just in front of value of x( a string “32”).
Hence the result would be “3245” and its type would be string.
• Note: one can use single quotes to enclose a string value,
instead of double quotes.

ACCEPTING USER INPUT


• Python uses the built-in function input() to read the data from the
keyboard.
• When this function is invoked, the user-input is expected. The input is
read till the user presses enter- key.
For example:
>>> str1=input()
hello how are you? #User input
>>> print(“string is “,str1)
string is hello how are you? #Printing str1
• when input() function is used, the cursor will be blinking to receive
the data.
• For a better understanding, it is better to have a prompt message
for the user informing what needs to be entered as input.
• The input() function itself can be used to do so, as shown below –
>>> str1=input("enter a string: ")
enter a string: hello
>>> print("you have entered: ",str1)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 30

you have entered: hello


• One can use new-line character \n in the function input() to make
the cursor to appear in the next line of prompt message –
>>> str1=input("enter a string:\n")
enter a string:
hello #cursor is pushed here
• the key-board input received using input() function is always
treated as a string type.
• If you need an integer, you need to convert it using the function
int().
Observe the following example –
>>> x=input("enter x:")
enter x:10 #x takes the value “10”, but not 10
>>> type(x) #so, type of x would be str
<class 'str’>
>>> x=int(input("enter x:")) #use int()
enter x:10
>>> type(x) #now, type of x is int
<class 'int'>
• A function float() is used to convert a valid value enclosed within
quotes into float number as shown below –
>>> f=input("enter a float value:")
enter a float value: 3.5
>>> type(f)
<class 'str’> #f is actually a string “3.5”
>>> f=float(f) #converting “3.5” into float value 3.5
>>> type(f)
<class 'float’>

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 31

A function chr() is used to convert an integer input into equivalent ASCII


character.
>>> a=int(input("enter an integer:"))
enter an integer:65
>>> ch=chr(a)
>>> print("character equivalent of ", a, "is ",ch)
character equivalent of 65 is A

Choosing Mnemonic Variable Names


• Choosing an appropriate name for variables in the program is always at
stake.
• Consider the following examples –

 One can observe that both of these two examples are performing same
task.
 But, compared to Ex1, the variables in Ex2 are indicating what is being
calculated.
 That is, variable names in Ex2 are indicating the purpose for which they
are being used in the program. Such variable names are known as
mnemonic variable names.
 The word mnemonic means memory aid. The mnemonic variables are
created to help the programmer to remember the purpose for which they
have been created.
• Python can understand the set of reserved words (or keywords),
and hence it flashes an error when such words are used as
variable names by the programmer.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 32

• Moreover, most of the python editors have a mechanism to show


keywords in a different color. Hence, programmer can easily make
out the keyword immediately when he/she types that word.
Debugging
• Some of the common errors a beginner programmer may make are
syntax errors.
• Though python flashes the error with a message, sometimes it may
become hard to understand the cause of errors. Some of the examples
are given here –

As shown in above examples, the syntax errors will be alerted by Python. But,
programmer is responsible for logical errors or semantic errors. Because, if the
program does not yield into expected output, it is due to mistake done by the
programmer, about which Python is unaware of.

CONDITIONAL EXECUTION
• In general, the statements in a program will be executed sequentially.
• But, sometimes we need a set of statements to be executed based on
some conditions.
Boolean expressions
• A boolean expression is an expression which results in true or
false.
• The true and false are special values that belong to class bool.
check the following –
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 33

>>> type(true)
<class 'bool’>
>>> type(false)
<class 'bool'>

Boolean expression may be as below –


>>> 10==12
False
>>> x=10
>>> y=10
>>> x==y
True
various comparison operations are shown in table.

OPERATOR MEANING EXAMPLE

> Greater than a>b

< Less than a<b

>= Greater than or equal to a>=b

<= Less than or equal to a<=b

== Comparison a==b

!= Not equal to a !=b

is Is same as a is b

is not Is not same as a is not b

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 34

>>> a=10
>>> b=20
>>> x= a>b
>>> print(x)
false
>>> print(a==b)
false
>>> print("a<b is ", a<b)
a<b is true
>>> print("a!=b is", a!=b)
a!=b is true
>>> 10 is 20
false
>>> 10 is 10
true
NOTE: for a first look, the operators == and is look same.
 Similarly, the operators != and is not look the same.
 But, the operators == and != does the equality test.
 That is, they will compare the values stored in the variables.
 Whereas, the operators is and is not does the identity test.
 That is, they will compare whether two objects are same.
Usually, two objects are same when their memory locations are same

Logical Operators
There are 3 logical operators in python as shown in table

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 35

Operator Meaning Example

and Returns true, if both operands are true a and b

or Returns true, if any one of two operands is true a or b

not Return true, if the operand is false (it is a unary not a


operator)

NOTE:
1. Logical operators treat the operands as boolean (true or false).
2. Python treats any non-zero number as true and zero as false.
3. While using and operator, if the first operand is false, then the second
operand is not evaluated by python. Because false and’ed with anything is
false.
4. In case of or operator, if the first operand is true, the second operand is not
evaluated. Because true or’ed with anything is true.
INDENTATION
• Most of the programming languages like C, C++, java use braces { } to
define a block of code. But, python uses indentation.
• Blocks of code are denoted by line indentation.
• It is a space given to the block of codes for class and function definitions
or flow control.

Example 1 (with boolean operands):


>>> x= true
>>> y= false
>>> print('x and y is', x and y)
x and y is false
>>> print('x or y is', x or y)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 36

x or y is true
>>> print('complement of x is ', not x)
complement of x is false
Example 2 (with numeric operands):
>>> a=-3
>>> b=10
>>> print(a and b) #and operation
10 #a is true, hence b is evaluated and printed
>>> print(a or b) #or operation
-3 #a is true, hence b is not evaluated
>>> print(0 and 5) #0 is false, so printed
0

CONDITIONAL EXECUTION
• The basic level of conditional execution can be achieved in python
by using if statement.
• The syntax and flowcharts are as below –

 Observe the colon symbol after condition.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 37

 When the condition which is a boolean expression is true, the


Statement block will be executed.
 Otherwise, it is skipped.
 A set (block) of statements to be executed under if is decided by the
indentation (tab space) given.
Example:
age=35
if age >= 18:
print("Eligible to vote")
 Usually, the if conditions have a statement block.
 In any case, the programmer feels to do nothing when the
condition is true, the statement block can be skipped by just typing
pass statement as shown below –
Example
>>> if x<0:
pass #do nothing when x is negative

ALTERNATIVE EXECUTION
• A second form of if statement is alternative execution, in which there are two
possibilities based on condition evaluation.
• Here, when the condition is true, one set of statements will be executed and
when the condition is false, another set of statements will be executed.
• The syntax and flowchart are as given below –

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 38

• As the condition will be either true or false, only one among statement
block-1 and statement block-2 will be get executed. These two alternatives
are known as branches.
Example:
age=12
if age >= 18:
print(“Eligible for vote")
else:
print(“Not eligible for vote")

NESTED CONDITIONALS
• The conditional statements can be nested.
• That is, one set of conditional statements can be nested inside the
other.
• It can be done in multiple ways depending on programmer‟s
requirements.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 39

Example
if user == "admin":
if password == "1234":
print("access granted")
else:
print("wrong password")
else:
print("unknown user")
Example

 Here, the outer condition marks>=60 is checked first.


 If it is true, then there are two branches for the inner conditional. If the
outer condition is false, the above code does nothing.
Note:
 Nested conditionals make the code difficult to read, even though there
are proper indentations. Hence, it is advised to use logical operators like
and to simplify the nested conditionals.
 For example, the outer and inner conditions in ex above can be joined as
- if marks>=60 and marks<70:
#do something

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 40

Chained Conditionals
• Some of the programs require more than one possibility to be checked
for executing a set of statements.
• That means, we may have more than one branch. This is solved with the
help of chained conditionals.
• The syntax and flowchart is given below

• The conditions are checked one by one sequentially.


• If any condition is satisfied, the respective statement block will be
executed and further conditions are not checked.
• Note that, the last else block is not necessary always
Example:
if marks >= 90:
print("a grade")
elif marks >= 75:
print("b grade")
else:
print("c grade")

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 41

Catching Exceptions using try and except


• As discussed there is a chance of runtime error while doing some
program.
• One of the possible reasons is wrong input.
a=int(input("enter a:"))
b=int(input("enter b:"))
c=a/b
print(c)
• When you run the above code, one of the possible situations
would be –
Enter a:12
enter b:0
traceback (most recent call last):
c=a/b
zerodivisionerror: division by zero

 For the end-user, such type of system-generated error messages is


difficult to handle.
 So the code which is prone to runtime error must be executed
conditionally within try block.
 The try block contains the statements involving suspicious code and
the except block contains the possible remedy (or instructions to user
informing what went wrong and what could be the way to get out of it).
 If something goes wrong with the statements inside try block, the
except block will be executed.
 Otherwise, the except-block will be skipped.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 42

 Handling an exception using try is called as catching an exception.


 In general, catching an exception gives the programmer to fix the
probable problem, or to try again or at least to end the program
gracefully.

Short-Circuit Evaluation of Logical Expressions


• When a logical expression (expression involving operands and, or,
not) is being evaluated, it will be processed from left to right.
• For example, consider the statements –

• Here, the expression x<10 and x+y>25 involves the logical operator and.
• Now, x<10 is evaluated first, which results to be false.
• As there is an and operator, irrespective of the result of x+y>25, the whole
expression will be false.
• In such situations, python ignores the remaining part of the expression.
This is known as short-circuiting the evaluation.
• When the first part of logical expression results in true, then the second
part has to be evaluated to know the overall result.
• The short-circuiting not only saves the computational time, but it also
leads to a technique known as guardian pattern.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 43

• Here, when we executed the statement x>=10 and (x/y)>2, the first half
of logical expression itself was false and hence by applying short-circuit
rule, the remaining part was not executed at all.
• Whereas, in the statement x>=2 and (x/y)>2, the first half is true and the
second half is resulted in runtime-error. Thus, in the expression x>=10
and (x/y)>2, short-circuit rule acted as a guardian by preventing an error.

• One can construct the logical expression to strategically place a


guard evaluation just before the evaluation that might cause an
error as follows:
• Here, x>=2 results in true, but y!=0 evaluates to be false. Hence,
the expression (x/y)>2 is never reached and possible error is being
prevented from happening

Debugging
• One can observe from previous few examples that when a runtime error
occurs, it displays a term traceback followed by few indications about
errors.
• A traceback is a stack trace from the point of error-occurrence down to
the call-sequence till the point of call.
• This is helpful when we start using functions and when there is a
sequence of multiple function calls from one to other.
• Then, traceback will help the programmer to identify the exact position
where the error occurred.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 44

• Most useful part of error message in traceback are –


 what kind of error it is
 where it occurred
 Compared to runtime errors, syntax errors are easy to find, most of the
times. But, whitespace errors in syntax are quite tricky because spaces
and tabs are invisible.

• The error here is because of additional space given before y. As python


has a different meaning (separate block of code) for indentation, one
cannot give extra spaces as shown above.
• In general, error messages indicate where the problem has occurred. But,
the actual error may be before that point, or even in previous line of code.

ITERATION
• Computers are often used to automate repetitive tasks.
Repeating identical or similar tasks without making errors is
• Something that computers do well and people do poorly.
• Repeated execution of a set of statements is called iteration.
Updating variables
• A common pattern in assignment statements is an assignment
statement that updates a variable, where the new value of the
variable depends on the old.
x=x+1
• This means “get the current value of x, add 1, and then update
x with the new value.”
• If you try to update a variable that doesn’t exist, you get an error,
because python evaluates the right side before it assigns a value
to x:

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 45

>>> x = x + 1
• NameError: name 'x' is not defined
• Before you can update a variable, you have to initialize it, usually
with a simple assignment:
>>> x = 0
>>> x = x + 1
• Updating a variable by adding 1 is called an increment;
subtracting 1 is called a Decrement.

The While LOOP


While loop is used to execute a block of statements repeatedly until a given
condition is satisfied. When the condition becomes false, the line immediately
after the loop in the program is executed.
SYNTAX
while expression:
statement(s)

# Python example for while loop


count = 0
while (count < 3):
count = count + 1
print("Hello BCA")
OUTPUT
Hello BCA

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 46

Hello BCA
Hello BCA
The while loop will continue running the code block as long as the condition
evaluates to true. Each time the loop executes, the condition is checked again.
If it is true, the loop continues; if it is false, the loop terminates, and the
program moves to the next statement after the loop.
Here is the flow of execution for a while statement:
1. Evaluate the condition, yielding true or false.
2. If the condition is false, exit the while statement and continue
execution at The next statement.
3. If the condition is true, execute the body and then go back to step 1.

Infinite Loops
• The value of the condition is always true. Therefore, the body of
the loop is run infinite times until the memory is full.
• It is an infinite loop because there is No iteration variable telling
you how many times to execute the loop.
EXAMPLE
age = 28
# the test condition is always True
while age > 19:
print('Infinite Loop’)
OUTPUT
Infinite Loop
Infinite Loop
Infinite Loop
Infinite Loop

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 47

Finishing iterations with continue


The continue statement skips the current iteration and moves to the next
one, without executing the remaining code inside the loop for that
iteration.
SYNTAX:
while condition:
# code before continue
if some_condition:
continue
# code after continue (this will be skipped if continue runs)
EXAMPLE:
i=0
while i < 5:
i += 1
if i == 3:
continue
print(i)
OUTPUT:
1
2
4
5
 The loop runs while i < 5.
 When i == 3, the continue statement runs — so print(i) is skipped.
 All other values are printed.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 48

Definite loops using for


 Sometimes we want to loop through a set of things such as a list of
words, the lines In a file, or a list of numbers.
 When we have a list of things to loop through, we Can construct a
definite loop using a for statement.
 We call the while statement An indefinite loop because it simply
loops until some condition becomes false, Whereas the for loop is
looping through a known set of items so it runs through As many
iterations as there are items in the set.
SYNTAX
for variable in sequence:
# body of loop
• variable: a temporary name for each item in the sequence.
• sequence: a range, list, string, or other iterable.
Example 1: Print numbers from 1 to 5
for i in range(1, 6):
print(i)
OUTPUT
1
2
3
4
5
Example 2: Iterate through characters in a string
for ch in "Python":
print(ch)
OUTPUT
P
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 49

y
t
h
o
n
Example 3: Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
OUTPUT
apple
Banana
cherry

Loop patterns
Often we use a for or while loop to go through a list of items or the contents of
a file and we are looking for something such as the largest or smallest value of
the data we scan through.
These loops are generally constructed by:
• Initializing one or more variables before the loop starts
• Performing some computation on each item in the loop body, possibly
changing the variables in the body of the loop
• Looking at the resulting variables when the loop completes
We will use a list of numbers to demonstrate the concepts and construction of
these loop patterns.

a)counting and summing loops

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 50

In python, loops can be used to count items and calculate totals. These are
very common tasks when processing sequences like lists, ranges, or input
data.
Counting Loop
A counting loop increases a counter each time something happens — like
processing each item in a list.
numbers = [3, 5, 7, 2, 9]
count = 0
for num in numbers:
count += 1
print("Count:", count)
Output
Count: 5

Summing Loop
A summing loop adds up the numbers in a sequence.
numbers = [3, 5, 7, 2, 9]
total = 0
for num in numbers:
total += num
print("Sum:", total)
Output:
Sum: 26
b) maximum and minimum loops
EXAMPLE:
numbers = [10, 4, 23, 8, 17]
max_num = numbers[0] # Start with the first number
for num in numbers:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 51

if num > max_num:


max_num = num
print("Maximum:", max_num)
Output:
Maximum: 23
EXAMPLE:
numbers = [10, 4, 23, 8, 17]
min_num = numbers[0] # start with the first number
for num in numbers:
if num < min_num:
min_num = num
print("minimum:", min_num)
OUTPUT:
Minimum: 4

FUNCTIONS
• Functions are the building blocks of any programming language.
• A sequence of instructions intended to perform a specific independent
task is known as a function.
• Function is a sub program which consists of set of instructions used to
perform a specific task. A large program is divided into basic building
Blocks called function.
Need for function:
• when the program is too complex and large they are divided into parts.
Each part is separately coded and combined into single program. Each
subprogram is called as function.
• Debugging, testing and maintenance becomes easy when the program
is divided into subprograms.

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 52

• Functions are used to avoid rewriting same code again and again in a
program.
• Function provides code re-usability.
• The length of the program is reduced.

Function calls
• A function is a named sequence of instructions for performing a task.
• When we define a function we will give a valid name to it, and then
specify the instructions for performing required task.
• Later, whenever we want to do that task, a function is called by its name.
Consider an example:
>>> type(15)
<class 'int'>
• here type is a function name, 15 is the argument to a function and <class
'int'> is the result of the function.
• Usually, a function takes zero or more arguments and returns the result.
BUILT-IN FUNCTIONS
• Python provides a rich set of built-in functions for doing various tasks.
• The programmer/user need not know the internal working of these
functions; instead, they need to know only the purpose of such functions.
Some of the built in functions are given below –
• max(): this function is used to find maximum value among the
arguments. It can be used for numeric values or even to strings.
max(10, 20, 14, 12) #maximum of 4 integers
20
max("hello world")
‘w’ #character having
maximum ascii code
max(3.5, -2.1, 4.8, 15.3, 0.2)
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 53

15.3 #maximum of 5 floating


point values
• min(): as the name suggests, it is used to find minimum of arguments.
min(10, 20, 14, 12) #minimum of 4 integers
10
min("hello world")
‘ ‘ #space has least ascii code here
min(3.5, -2.1, 4.8, 15.3, 0.2)
-2.1 #minimum of 5 floating point values
• len(): this function takes a single argument and finds its length. the
argument can be a string, list, tuple etc.
len(“hello how are you?”)
18
Type Conversion Functions
• As we have seen earlier (while discussing input() function), the type of
the variable/value can be converted using functions int(), float(), str().
• Python provides built-in functions that convert values from one type to
another
consider following few examples –
The int function takes any value and converts it to an integer, if it can, or
Complains otherwise
 int('20’) #integer enclosed within single quotes
20 #converted to integer type
 int("20") #integer enclosed within double quotes
20
 int("hello") #actual string cannot be converted to int
Traceback (most recent call last):
file "<pyshell#23>", line 1, in <module> int("hello")
valueerror: invalid literal for int() with base 10: 'hello'
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 54

int can convert floating-point values to integers, but it doesn’t round off;
it chops Off the fraction part:
 int(3.8) #float value being converted to integer
3 #round-off will not happen, fraction
is ignored
 int(-5.6)
-5
Float converts integers and strings to floating-point numbers:
 float('3.5’) #float enclosed within single quotes
3.5 #converted to float type
 float(42) #integer is converted to float
42.0
Finally, str converts its argument to a string:
 str(4.5) #float converted to string
'4.5'
 str(21) #integer converted to string
'21'
Math functions
• python provides a rich set of mathematical functions through the module
math.
• To use these functions, the math module has to be imported in the code.
Some of the important functions available in math are given here under
 Sqrt(): this function takes one numeric argument and finds the square
root of that argument.
>>> [Link](34) #integer argument
5.830951894845301
>>> [Link](21.5) #floating point argument
4.636809247747852

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 55

 pi: the constant value pi can be used directly whenever we require.


>>>print ([Link])
3.141592653589793
 log10(): this function is used to find logarithm of the given argument, to
the base 10.
>>> math.log10(2)
0.3010299956639812
 log(): this is used to compute natural logarithm (base e) of a given
number.
>>> [Link](2)
0.6931471805599453
 sin(): as the name suggests, it is used to find sine value of a given
argument. Note that, the argument must be in radians (not degrees).
One can convert the number of degrees into radians by multiplying
pi/180 as shown below –
>>>[Link](90*[Link]/180) #sin(90) is 1
1.0
 cos(): used to find cosine value –
>>>[Link](45*[Link]/180)
0.7071067811865476
 tan(): function to find tangent of an angle, given as argument.
>>> [Link](45*[Link]/180)
0.9999999999999999
 pow(): this function takes two arguments x and y, then finds x to the
power of y.
>>> [Link](3,4)
81.0
Random numbers
• Most of the programs that we write are deterministic.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 56

• Given the same inputs, most computer programs generate the same
outputs every Time, so they are said to be deterministic.
• That is, the input (or range of inputs) to the program is pre-defined and
the output of the program is one of the expected values.
• But, for some of the real-time applications in science and technology, we
need randomly generated output. This will help in simulating certain
scenario.
• Random number generation has important applications in games, noise
detection in electronic communication, statistical sampling theory,
cryptography, political and business prediction etc. These applications
require the program to be nondeterministic.
• · There are several algorithms to generate random numbers. But, as
making a program completely nondeterministic is difficult and may lead
to several other consequences, we generate pseudo-random numbers.
• That is, the type (integer, float etc) and range (between 0 and 1, between
1 and 100 etc) of the random numbers are decided by the programmer,
but the actual numbers are unknown.
• Python has a module random for the generation of random numbers.
One has to import this module in the program. The function used is also
random().
• By default, this function generates a random number between 0.0 and
1.0 (excluding 1.0).
Example:
import random
num = [Link]()
print(num)
Example:
import random
print([Link](1,10))
Example:
import random
# prints a random value from the list
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 57

list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
# prints a random item from the string
string = “python"
print([Link](string))

RECURSION
• Imagine you want to know the name of a person in the queue that you
are standing in. You ask people to find out about it.
• They keep asking the next person until they find an answer. Once an
Answer is found, they send it back until it reaches you.
• The above examples depict a process in which a particular action is
repeated until a condition is met.
• A process in which a function calls itself is called recursion.
• This Process helps ease the method of solving problems by replacing
Iterative code with recursive statements.
• Recursion is used in python when problems can be broken into
simpler parts for easier computation and more readable code.
Recursive function in Python has two parts:
(a) Base Case -this helps us to terminate the recursive function. it is a simple
case that can be answered directly and doesn't use recursion. If satisfied, it
returns the final computable answer. if this is omitted, the function will run till
infinity.
• python interpreter limits the number of recursive calls for a function to
1000 by giving a recursion error.
b) General (Recursive) Case - this case uses recursion and is called unless
the base condition is satisfied.
Syntax:
def rec_func_name():
if(condition): # base case

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 58

simple statement without recursion


else # general case
statement calling rec_func_name()

Example of Recursive Function


def factorial(n):
if n == 0 or n == 1: # base case
return 1
else:
return n * factorial(n - 1) # recursive call
num = 5
result = factorial(num)
print(f"Factorial of {num} is {result}")
OUTPUT
120

factorial(5)
→ 5 * factorial(4)
→ 5 * (4 * factorial(3))
→ 5 * (4 * (3 * factorial(2)))
→ 5 * (4 * (3 * (2 * factorial(1))))
→ 5 * (4 * (3 * (2 * 1))) ← base case reached at factorial(1)

SCOPE: LOCAL AND GLOBAL VARIABLES


• The scope defines the accessibility of the python Object. To
access the particular variable in the code,
• The scope must be defined as it cannot be accessed From
anywhere in the program.
• A variable is only available from inside the region it Is created. This
is called scope.
Based on the scope, we can classify python variables into two types:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT1 INTRODUCTION TO PYTHON 59

1. Local variables
2. Global variables
1. local variables
• When we declare variables inside a function, these variables will
have a local scope (within the function). we cannot access them
outside the function.
• These types of variables are called local variables. for example,
def greet():
# local variable
message = 'hello’
print('local', message)
greet()
# try to access message variable
# outside greet() function
print(message)
Output
local hello
nameerror: name 'message' is not defined

2. Python Global Variables


• In python, a variable declared outside of the function or in global
scope Is known as a global variable.
• This means that a global variable can be accessed inside or
outside of the function.
# declare global variable
message = 'hello'
def greet():
# declare local variable

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 60

print('local', message)
greet()
print('global', message)
Output
local hello
global hello

MODULES
• A module is a file containing python definitions ,functions,
statements and instructions.
• Standard library of python is extended as modules.
• To use these modules in a program, programmer needs to
import the module.
• Once we import a module, we can reference or use to any of its
functions or variables in our code.
 There is large number of standard modules also available in
python.
 Standard modules can be imported the same way as we import
our user-defined modules.
 Every module contains many function.
 To access one of the function , you have to specify the name of the
module and The name of the function separated by dot . this
format is called dot notation.

Syntax:
import module_name
module_name.function_name(variable)

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme
UNIT1 INTRODUCTION TO PYTHON 61

Creating and importing modules, Importing all or specific classes


from module

[Link] College of Commerce (Autonomous), Vijayapur BCA


Programme

You might also like