0% found this document useful (0 votes)
14 views41 pages

CS (Unit 1) Complete

The document provides an overview of functions in Python, including user-defined functions, parameters, return values, and variable scope. It explains file handling, including types of files, operations, and examples of reading and writing files. Additionally, it covers standard input/output streams, absolute vs relative paths, and the mutable/immutable properties of data objects.

Uploaded by

kerpadenzeln
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)
14 views41 pages

CS (Unit 1) Complete

The document provides an overview of functions in Python, including user-defined functions, parameters, return values, and variable scope. It explains file handling, including types of files, operations, and examples of reading and writing files. Additionally, it covers standard input/output streams, absolute vs relative paths, and the mutable/immutable properties of data objects.

Uploaded by

kerpadenzeln
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/ 41

Computer Science

UNIT-1: Computational Thinking and Programming-2


Functions
A function is a block of code that is used to perform a specific task. Python has many built-in
functions like print(), input() etc. but we can also create our own functions. These functions
are called user-defined functions.
In Python a user-defined function is written using the def keyword.
Syntax:
def functionname():
block_of_code (body_of_function)
Example:
def my_function():
print("Hello World")

Calling a Function:
The code written inside the function runs only when it is called in main program (driver
code). To call a function in main program (driver code), use the function name followed by
parenthesis:
Example:
#function defintion
def my_function():
print("Hello World")

#main program (driver code)


my_function() #Calling a Function

Output:
Hello World

NOTE: Students, please keep always in mind that # is used in python for
single-line comment. These comments are used in notes to describe any
instruction or a piece of code.

1
Parameters (or Arguments):
We can pass data, known as parameters or arguments, into a function. The following example
has a function with one parameter. When the function is called, we pass along a first name,
which is used inside the function to print the full name:
Example:
def my_function(fname):
print(fname)

my_function("Ravi")
my_function("Amit")
my_function("Parul")

Output:
Ravi
Amit
Parul

2
Return Values:
A function can also return data as a result using return keyword:
Example:
#function
def my_function(x):
return 5*x

#main program
res= my_function(3)
print(res)
print(my_function(5)) # we can directly call a function inside print() function
print(my_function(9))

Output:
15
25
45

3
Default Parameters:
The following example shows how to use a default parameter value. If we call the function
without parameter, it uses the default value:
Example:
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil

Positional Parameters:
Positional arguments are arguments that need to be included in the proper position or order.
The first positional argument always needs to be listed first when the function is called. The
second positional argument needs to be listed second and the third positional argument listed
third, etc.
Example:
def abc(a,b,c=2):
return a+b+c
abc(7,9) #7 & 9 both are positional arguments whereas c is default a
Output: 18

4
Scope of Variables:
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a
particular variable. There are two basic scopes of variables in Python −

 Global variables
 Local variables
Global vs. Local variables:
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.

This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example −

total = 0 # This is global variable.

# Function definition is here

def sum( arg1, arg2 ):

# Add both the parameters and return them.

total = arg1 + arg2 # Here total is local variable.

print("Inside the function local total : ", total)

return total

# Now you can call sum function

sum(10, 20)

print("Outside the function global total : ", total)

When the above code is executed, it produces the following result −

Inside the function local total : 30


Outside the function global total : 0

5
global keyword in Python:
global keyword is a keyword that allows a programmer (user) to modify or use the value of a global
variable inside a function.

Rules of global keyword:


 If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local
unless explicitly declared as global.
 We Use global keyword to use a global variable inside a function.
 There is no need to use global keyword outside a function.

Example 1: To read(access) the value of a global variable inside a function there is no need to use
global keyword.
# a and b are global variables

a = 15
b = 10

# function to perform addition


def add():

c =a +b
print(c)

# calling a function

add()

Output:
25

Example 2 : To change the value of a global variable inside a function there is need to use global
keyword.
x = 15

def change():

global x

x =x +5

print("Value of x inside a function :", x)

change()
print("Value of x outside a function :", x)

Output:
Value of x inside a function : 20
Value of x outside a function : 20
In the above example, we first declare x as global keyword inside the function change(). The value of x
is then incremented by 5, ie. x=x+5 and hence we get the output as 20.
As we can see by changing the value inside the function change(), the change is also reflected outside
in the global x.

6
Advantages of using functions:
1. Program development made easy and fast: Work can be divided among project
members thus software development can be completed fast.
2. Program testing becomes easy: Easy to locate and isolate a faulty function for further
investigation.
3. Code sharing becomes possible: A function may be used later by many other programs
this means that a python programmer can use function written by others.
4. Code re-usability increases: A function can be used to keep away from rewriting the
same block of codes which we are going use two or more locations in a program.
5. Increases program readability: The length of the source program can be reduced by
using functions at appropriate places. Therefore, readability increases.

7
Mutable/immutable properties of data objects with respect to function:
Data types in Python can be either mutable or immutable. Mutable data types can be changed
after it is created, and an immutable data types can’t.
Mutable: list, dict, set, byte, array
Immutable: int, float, complex, string, tuple

Call(Pass) by reference-
def updateList(list1):
list1 += [10]

n = [50, 60]
updateList(n)
print(n)
OUTPUT
[50, 60, 10]

Call(Pass) by value-
def updateNumber(n):
n += 10

b=5
updateNumber(b)
print(b)
OUTPUT
5

8
Passing a List (array) as a Parameter:
You can send any data type as parameter to a function (string, number, list, dictionary etc.),
and it will be treated as the same data type inside the function. E.g. if you send a List as a
parameter, it will still be a List (array) when it reaches the function:

Example
def my_function(food):
for x in food:
print(x)

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

my_function(fruits)

9
Functions using libraries (modules)
Mathematical functions:
Mathematical functions are available under math module. To use mathematical functions
under this module, we have to import the module using import math.
For e.g.
To use sqrt() function we have to write statements like given below.
import math
r=math.sqrt(4)
print(r)
OUTPUT :
2.0
Functions available in Python Math Module

10
Python has a set of built-in methods that you can use on strings.

Note: All string methods returns new values. They do not change the original
string.

Method Description

capitalize() Converts the first character to upper case

count() Returns the number of times a specified value occurs in a


string

endswith() Returns true if the string ends with the specified value

find() Searches the string for a specified value and returns the
position of where it was found

isalnum() Returns True if all characters in the string are


alphanumeric

isalpha() Returns True if all characters in the string are in the


alphabet

isdigit() Returns True if all characters in the string are digits

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

11
isupper() Returns True if all characters in the string are upper case

lower() Converts a string into lower case

replace() Returns a string where a specified value is replaced with a


specified value

split() Splits the string at the specified separator, and returns a


list

startswith() Returns true if the string starts with the specified value

upper() Converts a string into upper case

12
File handling

Need for a data file:

• To Store data in organized manner


• To store data permanently
• To access data faster
• To Search data faster
• To easily modify data later on

File:

A file is a sequence of bytes stored on the disk/permanent storage. File is created for storing
data permanently. In programming, Sometimes, it is not enough to only display the data on
the screen. Those data are to be used later on, and then the concept of file handling comes.
File handling in Python enables us to create, update, read, and delete the files through our
python program. In Python, File Handling consists of following three steps:

 Open the file.


 Process file i.e perform read, write, or append operations.
 Close the file.

Types of File:
There are two types of files:
Text Files- A file whose contents can be viewed using a text editor is called a text file. A text
file is simply a sequence of ASCII or Unicode characters. Python programs, contents written
in text editors are some of the example of text files.e.g. .txt, .rtf, .csv etc.
Binary Files- Binary files are used to store binary data such as images, videos, audio etc. The
.exe files, mp3 file, word documents are also some of the examples of binary files. We can’t
read a binary file using text editors.

13
Operations on File:
We can perform following operations on python Data Files:

a) Creation of a new Data File and Opening of an existing Data File


b) Reading from file
c) Writing to Data File
d) Appending data (inserting Data at the end of the file)
e) Closing a file

List

The open() Function:


Before any reading or writing operation of any file, it must be opened first of all. Python
provide built in function open() for it. On calling of this function creates a file variable
(pointer or object) for file operations.

Syntax:
F_obj = open(<file_name>, <access_mode>)

Whereas,
F_obj: File variable or File pointer or File object.
<file_name> : name of the file, enclosed in double quotes.
<access_mode> : Determines the what kind of operations can be performed with file like
read, write etc.

14
There are following different modes for opening a file:

15
A basic python program to open, write and read a file:

f = open(“a.txt”, “w”)
line1 = “Welcome to python”
f.write(line1)
line2=“\nRegularly visit python”
f.write(line2)
f.close()
Note: Create a notepad file a.txt
f = open(“a.txt”, “r”)
before you run the program. Also
text = f.read()
remember, a.txt must be in the same
print(text)
folder where your program file (.py
f.close() file) exists.

OUTPUT
Welcome to python
Regularly visit python

A basic python program to append content to a File:


f = open(“a.txt”, “w”)
line = “Welcome to python \nRegularly visit python”
f.write(line)
f.close()
f = open(“a.txt”, “a”)
f.write(“\nThanks”)
f.close()
f = open(“a.txt”, “r”)
text = f.read()
print(text)
f.close()

OUTPUT
Welcome to python
Regularly visit python
Thanks

16
Let’s understand the read Operation in deep:
Consider a text file (notepad file namely as mydat.txt) given below:

17
Let’s understand the write Operation in deep:
Look at the following two Screen shots (1st is Showing Code whereas 2nd is showing
different outputs) where comparison among different type of write operations have shown.
Here you can find comparison between write() and writeline() functions.

In the above code we have created 4 different files namely Nw_File1.txt, Nw_File2.txt,
Nw_File3.txt, Nw_File4.txt.

18
19
Some more Programs-

Note: Create a notepad file a.txt


before you run the program. Also
remember, a.txt must be in the same
folder where your program file (.py
file) exists.

20
Note: Create a notepad file a.txt
before you run the program. Also
remember, a.txt must be in the same
folder where your program file (.py
file) exists.

21
22
Program
a. to count total number of words in a file
b. also to print words starting with character ‘t’ and whose length is less than five

#function Note: Create a notepad file


def DISPLAYWORDS(): STORY.TXT and type a paragraph in it
file=open('STORY.TXT','r') before you run the program. Also
remember, STORY.TXT must be in the
line = file.read() same folder where your program file
(.py file) exists.
word = line.split()
print("No of words=",len(word))
for w in word:
if len(w)<5 and w[0]=='t':
print( w)
file.close()

#main program
DISPLAYWORDS()

23
Program
a. to count total number of lines in a file
b. also to count Lines starting with character ‘A’

#function
def COUNTLINES():
Note: Create a notepad file
file=open('STORY.TXT','r')
STORY.TXT and type a paragraph in it
lines = file.readlines() before you run the program. Also
remember, STORY.TXT must be in the
print(lines) same folder where your program file
print("no of lines=",len(lines)) (.py file) exists.

count=0
for w in lines:
if w[0]=="A":
count=count+1
print("Total lines:",count)
file.close()

#Main program
COUNTLINES()

24
25
Standard input, output, and error streams in python:
We use standard I/O (input/output) Streams to get better performance from different I/O
devices.
Some Standard Streams in python are as follows –
– Standard input Stream sys.stdin
– Standard output Stream sys.stdout
– Standard error Stream sys.stderr
e.g.
import sys
a = sys.stdin.readline()
sys.stdout.write(a)
sys.stderr.write("custom error message")

Absolute Path vs Relative Path:


The absolute path is the full path to some file or place on your computer. The relative path is
the path to some file with respect to your current working directory (PWD). For example:
If we want to know the absolute path of file staff.txt then Absolute path will be:
C:/users/admin/docs/staff.txt
If PWD (Present Working Directory) is C:/users/admin/, then the relative path to staff.txt
would be: docs/staff.txt
Note, PWD + relative path = absolute path
C:/users/admin/ + docs/staff.txt = C:/users/admin/docs/staff.txt
If we want to know the Present/Current Working Directory, we have OS module (Operating
System module) which provides many such functions which can be used to work with files
and directories and a function getcwd( ) can be used to identify the current working directory
like this : (this program is written in interactive mode)
>>> import os
>>>curr_dir=os.getcwd()
>>> print(curr_dir)

26
Binary Files:
Binary files store data after converting it into binary language (0s and 1s), there is no EOL
(End Of Line) character. This file type returns bytes. This is the file to be used when dealing
with non-text files such as images or exe.
To write data into a binary file, we need to import Pickle module. Pickling means converting
structure (data types) into byte stream before writing the data into file. Pickle module has two
main functions:

27
28
Program to append record in a binary file:

29
Program to search record in a binary file:

30
Program to update record in a binary file:

31
CSV FILE (Comma separated value):
CSV (Comma Separated Values) is a file format for data storage which looks like a text file.
The information is organized with one record on each line and each field is separated by
comma.
CSV File Characteristics:
• One line for each record
• Comma separated fields
• Space-characters adjacent to commas are ignored
• Fields with in-built commas are separated by double quote characters.

32
Using Python libraries (modules): creating and importing Python libraries (modules)
A module in python is a code library. Practically, it is a file which contains python
functions/global variables etc. It is just .py file which has python executable code/statement.
For example: Let’s create a file mymodule.py
def hello_message(user_name):
return “Hello ” + user_name
Now we can import mymodule.py module either in another py file or in python interpreter.
#another file in which we are importing mymodule.py
import mymodule
print(mymodule.hello_message(“India"))
print(mymodule.hello_message(“World"))

Output:
Hello India
Hello World

How to import modules in Python?


Python module can be accessed in any of following way.
1. Python import statement
import math
print(“2 to the power 3 is ", math.pow(2,3))
Just similar to math module, user defined module can be accessed using import statement
2. Import with renaming
import math as mt
print(“2 to the power 3 is ", mt.pow(2,3))
3. Python from...import statement
from math import pow
print(“2 to the power 3 is ", pow(2,3))
4. Import all names
from math import *
print(“2 to the power 3 is ", pow(2,3))

33
Data-structures: lists, stacks, queues
Data-structure:

34
35
the end of the list

NOTE: List was also taught in Class 11th, so whatever was taught in class 11th would also be
included in class 12th. Read that also.

36
37
38
39
40
41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy