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 a Calendar for a month
The time Module, The calendar Module
Defining a Function, Calling a Function, Pass by reference vs value
The Anonymous Functions, The return Statement, The import Statement, The from ... import Statement
Printing to the screen, Reading keyboard Input, The input Function
Opening and Closing Files, Reading and Writing Files
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
Built-in functions
Functions defined in built-in modules
User-defined functions
Defining a Function in Python
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement; the documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
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:
Simple tasks: Lambda functions are suitable for simple, one-line operations that don't require complex logic or multiple statements.
Higher-order functions: Lambda functions are particularly useful when working with higher-order functions that take functions as arguments or return functions as results.
Temporary functions: Lambda functions are convenient for ad-hoc or temporary functions that are only needed within a specific context.
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:
Send Data Back: The return statement allows a function to send data back to the code that called it. This enables functions to perform computations or retrieve information and then share the results with the caller.
Control Execution Flow: The return statement can be used to control the execution flow within a function. It can be used to exit the function early, modify the return value based on certain conditions, or simplify function structure.
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:
Return Value: The return statement can optionally include an expression that specifies the value to be returned. If no expression is provided, the function returns None.
Function Termination: Once a function encounters a return statement, it immediately exits and returns the specified value. Any statements following the return statement are not executed.
Multiple Return Statements: A function can have multiple return statements, allowing for conditional returns based on different conditions.
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])
file_name − The file_name argument is a string value that contains the name of the file that you want to access.
access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r).
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default (default behavior).
Opening and Closing Files, Reading and Writing Files
Opening and Closing:
Imagine a vault door. The open() function is your key. It takes two arguments: the file path and a mode (like "r" for reading or "w" for writing).
Example: file = open("myfile.txt", "r"). Now file is your handle, the open door to your file's secrets.
Remember to close the vault door when you're done! Use file.close() to avoid resource leaks and data corruption.
Reading Files:
Once the door is open, time to explore the riches within. Reading functions like file.read() or file.readline() come to your aid.
file.read() grabs the entire file's content as a string. Perfect for short files or when you want everything.
file.readline() reads one line at a time, useful for long files or processing line by line.
Don't forget to close the file after reading!
Writing Files:
Feeling creative? Unleash your inner author with writing functions like file.write() and file.writelines().
file.write("This is awesome!") scribbles your message to the file.
file.writelines(["Line 1", "Line 2"]) adds multiple lines at once.
Remember, existing content gets overwritten by default. Use "a" in open mode to append to the end.
Bonus Tip:
Context managers like with open(...) as file: automatically handle opening and closing, making your code cleaner and safer.