Python to Generate Random Word from List with Full Source Code For Beginners

This is a useful program that chooses a random word from a given list.


Code language: CSS (css)

Make sure you have a file in the same directory you wish to choose a random word from.

Source Code:

import sys import random # check if filename is supplied as a command line argument if sys.argv[1:]: filename = sys.argv[1] else: filename = input("What is the name of the file? (extension included): ") try: file = open(filename) except (FileNotFoundError, IOError): print("File doesn't exist!") exit() # handle exception # get number of lines num_lines = sum(1 for line in file if line.rstrip()) # generate a random number between possible interval random_line = random.randint(0, num_lines) # re-iterate from first line for i, line in enumerate(file): if i == random_line: print(line.rstrip()) # rstrip removes any trailing newlines :) break
Code language: PHP (php)

Leave a Comment