Python Examples
Dave Braunschweig
Strings
# This program demonstrates string functions. def main(): string = "Hello" print("string: " + string) print("string.lower(): " + string.lower()) print("string.upper(): " + string.upper()) print("string.find('e'): " + str(string.find('e'))) print("len(string): " + str(len(string))) print("string.replace('H', 'j'): " + string.replace('H', 'j')) print("string[::-1]: " + string[::-1]) print("string[2:4]: " + string[2:4]) print("string.strip('H'): " + string.strip('H')) name = "Bob" value = 123.456 print("string.format(): {0} earned ${1:.2f}".format(name, value)) main()
Output
string: Hello string.lower(): hello string.upper(): HELLO string.find('e'): 1 len(string): 5 string.replace('H', 'j'): jello string[::-1]: olleH string[2:4]: ll string.strip('H'): ello string.format(): Bob earned $123.46
Files
# This program creates a file, adds data to the file, displays the file, # appends more data to the file, displays the file, and then deletes the file. # It will not run if the file already exists. # # References: # https://www.mathsisfun.com/temperature-conversion.html # https://en.wikibooks.org/wiki/Python_Programming import os import sys def calculate_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit def create_file(filename): try: with open(filename, "w") as file: file.write("Celsius,Fahrenheit\n") for celsius in range(0, 51): fahrenheit = calculate_fahrenheit(celsius) file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit)) except: print("Error creating", filename) print(sys.exc_info()[1]) def read_file(filename): try: with open(filename, "r") as file: for line in file: line = line.strip() print(line) print() except: print("Error reading", filename) print(sys.exc_info()[1]) def append_file(filename): try: with open(filename, "a") as file: for celsius in range(51, 101): fahrenheit = calculate_fahrenheit(celsius) file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit)) except: print("Error appending to", filename) print(sys.exc_info()[1]) def delete_file(filename): try: os.remove(filename) except: print("Error deleting", filename) print(sys.exc_info()[1]) def main(): filename = "~file.txt" if os.path.isfile(filename): print("File already exists.") else: create_file(filename) read_file(filename) append_file(filename) read_file(filename) delete_file(filename) main()
Output
Celsius,Fahrenheit 0.0,32.0 1.0,33.8 2.0,35.6 3.0,37.4 ... 98.0,208.4 99.0,210.2 100.0,212.0