Factorial Of

def main(): n = eval(input(“Enter a nonnegative integer: “)) print(“Factorial of “, n, “is”, factorial(n)) # Return the factorial for the specified number def factorial(n): if n == 0: return 1 else: return n * factorial(n – 1) # recursive call main() # Call the main function

Dumping and Loading Objects Using Pickle

import pickle def main(): outfile = open(“pickle.dat”, “wb”) pickle.dump(45, outfile) pickle.dump(56.6, outfile) pickle.dump(“Programming is fun”, outfile) pickle.dump([1,2,3,4], outfile) outfile.close() infile = open(“pickle.dat”, “rb”) print(pickle.load(infile)) print(pickle.load(infile)) print(pickle.load(infile)) print(pickle.load(infile)) infile.close() main() detect end of file import pickle def main(): outfile = open(“numbers.dat”, “wb”) data = eval(input(“Enter an integer (the input exits of the input is 0):”)) while … Read moreDumping and Loading Objects Using Pickle

Exception Example

def main(): try: number1, number2 = eval(input(“Enter two numbers, seperate by a comma: “)) result = number1 / number2 print(“Result is”, result) except ZeroDivisionError: print(“Division by zero!”) except SyntaxError: print(“A comma may be missing in the input”) except: print(“Something wrong in the input”) else: print(“No exceptions”) finally: print(“The finally clause is executed”) main()

Write Read Numbers

from random import randint def main(): outfile = open(“Numbers.txt”, “w”) for i in range(10): outfile.write(str(randint(0, 9))+ ” “) outfile.close() infile = open(“Numbers.txt”, “r”) s = infile.read() numbers = [eval(x) for x in s.split()] for number in numbers: print(number, end= ” “) infile.close() main()