Posts

Showing posts with the label cbse computer science

Recursion in Python

Recursion is an approach to solve a problem which involves a function calling itself either directly or indirectly. Such a function is known as a recursive function. Every recursive method must have a base case which would stop calling the function again and again indefinitely, because the function stack has a limit, which is platform dependent. A Python program to print a string backwards using a recursive function. def reverse(s, n):     if n > 0:         print(s[n], end = '')         reverse(s, n - 1)     elif n == 0:         print(s[0]) s = input('Enter the string: ') reverse(s, len(s) - 1) A Python program to calculate a b using a recursive function. def power(a, b):     if b == 0:         return 1     else:         return a * power(a, b - 1) a = int(input('a = ')) b = int(input('b = ')) p = power(a, b) print('a to the power b: ' + str(p)...

File Handling in Python

Data Files There are two types of data files: 1. Text file: Stores data in ASCII or Unicode encoding. Each line ends with a special EOL (End Of Line) character. 2. Binary file: Stores data in the same format without encoding. The lines of data are not delimited with any EOL character. Opening Files The open() function is used to open a file. By default, the file is opened in "read" mode. myfile = open("details.txt") However, you can also mention the "read" mode while opening a file. myfile = open("details.txt", "r") In the above code, "myfile" is the file object or file handle. To open a file from a specific location: myfile = open("c:\\Users\\details.txt", "r") Double backslashes are provided because it is an escape sequence for representing a single backslash. If you want to use single backslash, then use a raw string. myfile = open(r"c:\users\details.txt", "r") When the path of the fi...