Skip to main content
Engineering LibreTexts

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{\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}}\)

    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

    7.10: Python Examples is shared under a CC BY-SA 4.0 license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?