Date & Time, Functions, Modules and File I/O

Objective : What I want you to learn?

ABC

Rationale : Why this is useful to you?

ABC

Learning Outcomes : What I want you to do after completing this topic?

ABC

Contents

Time Tuple, Getting Current Time, Getting Calendar for a Month

What is TimeTuple?

In Python, a time tuple is a named tuple that represents a specific time and date. 

It is a 9-element tuple that contains the following information: 

(year, month, day, hour, minute, second, microsecond, weekday, isdst) 

Getting the Current Time

You can format any time as per your requirement, but a simple method to get time in a readable format is asctime() 

Getting Calendar for a Month

The calendar module gives a wide range of methods to play with yearly and monthly calendars. Here, we print a calendar for a given month (Jan 2024)

The time Module

time module available in Python, which provides functions for working with times and for converting between representations. 

time.asctime([tupletime]) 

Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'

time.clock( ) 

Returns the current CPU time as a floating-point number of seconds. To measure computational costs of different approaches, the value of time.clock is more useful than that of time.time()

time.ctime([secs])  

Like asctime(localtime(secs)) and without arguments is like asctime( ) 

time.time( )   

Returns the current time instant, a floating-point number of seconds since the epoch. 

The calendar Module

The calendar module supplies calendar-related functions, including functions to print a text calendar for a given month or year. 

calendar.firstweekday( ) 

Returns the current setting for the weekday that starts each week. By default, when calendar is first imported, this is 0, meaning Monday. 

calendar.isleap(year) 

Returns True if year is a leap year; otherwise, False. 

calendar.isleap(year) 

Returns True if year is a leap year; otherwise, False. 

Defining a Function, Calling a Function, Pass by reference vs value

Functions

A Python function is a block of organised, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. 


Types of Python Functions


Defining a Function in Python

def functionname( parameters ):

   "function_docstring"

   function_suite

   return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. 

Calling a Function

Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt. 

Call by Value v/s Calling by Reference Mechanism :

C/C++ functions are said to be called by value. When a function in C/C++ is called, the value of actual arguments is copied to the variables representing the formal arguments. If the function modifies the value of the formal argument, it doesn't reflect the variable that was passed to it.

Python uses a pass-by-reference mechanism. As a variable in Python is a label or reference to the object in the memory, both the variables used as actual arguments as well as formal arguments really refer to the same object in the memory. We can verify this fact by checking the id() of the passed variable before and after passing.

Default Arguments:

Python allows to define a function with default value assigned to one or more formal arguments. Python uses the default value for such an argument if no value is passed to it. If any value is passed, the default value is overridden with the actual value passed. 

The Anonymous Functions (Lambda Functions)

Anonymous functions, also known as lambda functions, are small, unnamed functions defined using the lambda keyword in Python. They are typically used for simple, one-line operations that don't warrant the creation of a full-fledged function. 

lambda arguments: expression 

Example : 

square = lambda x: x * x

result = square(5)

print(result)  # Output: 25 

When to use lambda functions:

The return Statement

The import Statement, The from .. ..import Statement, 

The return statement is a fundamental element of Python programming, used to exit a function and send a value back to the caller. It terminates the execution of the function and returns a specified value to the code that called it. 

Purpose:

Returning a Sum:

def add_numbers(a, b):

    return a + b


result = add_numbers(5, 3)

print(result)  # Output: 8 

Returning Boolean Value:

def is_even(number):

    return number % 2 == 0


even_number = 10

print(is_even(even_number))  # Output: True 

Early Return:

def check_input(value):

    if value < 0:

        return "Invalid input: Value cannot be negative"

    else:

        return "Valid input: Value is positive" 

Considerations:

Printing to the Screen, Reading keyboard Input, The input Function

Python uses built-in input() and print() functions to perform standard input/output operations. Python program interacts with these IO devices through standard stream objects stdin and stdout defined in sys module.

The input() function reads bytes from a standard input stream device i.e. keyboard. Hence both the following statements read input from the user.

name = input()

#is equivalent to

import sys

name = sys.stdin.readline() 

The print() function on the other hand, sends the data towards standard output stream device, i.e., the display monitor. It is a convenience function emulating write() method of stdout object. 

print (name)


#is equivalent to

import sys

sys.stdout.write(name) 

Any object that interacts with input and output steam is called File object. Python's built-in function open() returns a file object. 

The open() Function

This function creates a file object, which would be utilized to call other support methods associated with it.

Syntax

file object = open(file_name [, access_mode][, buffering]) 

Opening and Closing Files, Reading and Writing Files

Opening and Closing:

Reading Files:

Writing Files:

Bonus Tip: