Search code examples
pythonpseudocode

Pseudocode for this code


import os.path

#The model of the phone initialised to empty
strModel = ""

#Ask the user for their make
strModel = input("What is the make?")

#if the length of their input is too small ask them to input again
while len(strModel) <= 4:
    #Promot the user to input again
    strModel = input("Not enough characters. What is the make?")

#check if the file exists for specified phone    
if os.path.isfile(strModel + ".txt") == True:
    #open the file
    f = open(strModel + ".txt", "r")
    #turn contents of file into an array of strings for each line
    lineArray = f.readlines()

    #loop through the array to ask and answer questions
    for line in lineArray:
        #check if the line we are on is a question
        if lineArray.index(line) % 2 == 0 or lineArray.index(line) == 0:
            question = line
            #ask the question and wait for reply
            userAnswer = input(question)
            #yes means the user has that problem so print the relevant answer
            if(userAnswer == "yes"):
               print(lineArray[lineArray.index(line)+1])
else:
    print("Your model does not exist in our database.")

I'm a beginner at Python. How would I write pseudo code for this code. This is the code to ask the user about their phone. Could I be more efficient with this code as well, if I can then in what way?


Solution

  • I will tell you how I do it; my main reason for doing it this way is that I'm not a compiler. Also... In programming class I skipped that week because I wanted to write "real code".

    Normally, you write pseudo code to plan the writing of the real code. But, languages like python IMO have made it not necessary.

    Anyways; I think of the algorithm or the workflow of whatever it is that I'm doing; maybe it's a function; if it's a function I think of what I need to execute that function, and then a quick way to represent it (pseudo-code) that I then transform to real code. Of course, I don't do it like this.... Unless it's a job interview (because, again I'm not a compiler/interpreter/etc); and most interviewers don't care about working code, they want to see that you know data structures, etc.

    For your code, I'd think of it in pseudo-code like so:

    strModel <= input
    
    while strModel <= 4:
        prompt
    
    if path_is_valid:
        fd = open file
    
        for each line in file:
             if this or that:
                 prompt user
    
                 if answer is yes:
                     do that