Sunday 26 November 2023

Functions and Files in python

Function is used to run a block of code

Syntax:
def function_name(arguments):
        statements
        return

def - declaration of the function
function_name: it refers to the name of the function
arguments: values passed to the function
statement - block of code to run program
return - it is used to return the value. It is sometimes used and sometimes not used

Note: once return is executed, it is end of the function

Function call: We can call the function by using function name. once the function is called the execution takes place to the definition of the function.

Syntax: def greet()

def greet():
    statements

#calling the function
greet()

Example: 
def add_numbers(a=8, b=6):
        sum = a+b
        print(sum)

#call the function
add_numbers(2,3)

Ouput:
5

Files in Python
There are different operations on file
1. creating a file:          fp = open('file.txt', 'w')  or  
fp = open('file.txt', 'a')
2. opening a file :         
fp = open('file.txt', 'w')  or  fp = open('file.txt', 'a') or fp = open('file.txt', 'r')
3. reading                     
fp = open('file.txt', 'r')
4. writing to file           
fp = open('file.txt', 'w')
5. closing the file          fp.close()
6. appending to a file    
fp = open('file.txt', 'a')


No comments:

Post a Comment