7.10: Python Examples
- Page ID
- 10697
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\ket}[1]{\left| #1 \right>}\)
\(\newcommand{\bra}[1]{\left< #1 \right|}\)
\(\newcommand{\braket}[2]{\left< #1 \vphantom{#2} \right| \left. #2 \vphantom{#1} \right>}\)
\(\newcommand{\braopket}[3]{\left< #1 \vphantom{#2}\vphantom{#3} \right| #2 \vphantom{#1}\vphantom{#3} \left| #3 \vphantom{#1}\vphantom{#2} \right>}\)
\(\newcommand{\qmvec}[1]{\mathbf{\vec{#1}}}\)
\(\newcommand{\op}[1]{\hat{\mathbf{#1}}}\)
\(\newcommand{\expect}[1]{\langle #1 \rangle}\)
\(\newcommand{\dfn}[1]{\emph{\textbf{#1}}}\)
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:
file = open(filename, "w")
file.write("Celsius,Fahrenheit\n")
for celsius in range(0, 51):
fahrenheit = calculate_fahrenheit(celsius)
file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit))
file.close()
except:
print("Error creating", filename)
print(sys.exc_info()[1])
def read_file(filename):
try:
file = open(filename, "r")
for line in file:
line = line.strip()
print(line)
file.close()
print()
except:
print("Error reading", filename)
print(sys.exc_info()[1])
def append_file(filename):
try:
file = open(filename, "a")
for celsius in range(51, 101):
fahrenheit = calculate_fahrenheit(celsius)
file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit))
file.close()
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
References
- Wikiversity: Computer Programming

