Question

Consider the following python script mt_q2.py, which defines the function called now(): #!/usr/bin/env python3 # program:...

Consider the following python script mt_q2.py, which defines the function called now():

#!/usr/bin/env python3
# program: mt_q2.py
import os

def now():
    p = os.popen('date +%Y%m%d')
    today = p.read().strip()
    return today

if __name__ == '__main__':
    print(now())

Asnwer the following questions:
(a) What type of object will be returned by the now() function?

(b) If you run the above Python script "python3 mt_q2.py" on a system with real-time clock on Oct 16, 2019 at 10:00 am,
what will be the output?

(c) What is the purpose of calling the strip() method in the pythone statement 'today = p.read().strip()'?

(d) What is the purpose or effect of the "if __name__ == '__main__':" statement?

(e) There is one important statement missing in the now() function which will cause problem to the system
    resource if the function is called multiple time in the same script. What is it?

Homework Answers

Answer #1

a).

The now() function returns a string.

p.read() is used to store the date as a string in "today" variable and it is returned.

b).

The function returns the date in the fomat %Y%m%d, which represents year, month and day respectively.

If the real-time clock is on Oct 16, 2019 at 10:00 am, the returned value would be "20191016"

c).

If strip() method is called without an argument, it removes any white spaces in the beginning or the end of the string. In the above example, p.read() string contains a new line character(\n) at the end. strip() is used to delete that new line character

d).

The statement if __name__ == '__main__': is a basic python 'if' statement that checks if the '__name__ ' of the program being executed is '__main__' .

Python interpretor sets __name__ as __main__ only when the code is run independently (i.e python example.py) and __name__ becomes __example__ if the code is imported into a new module (i.e import example).

Therefore, the statement is used when we need certain part of code to run only when the code is run separately and not inside a module.

e).

If the now() function is called repeatedly, it generates a lot of opened files handeled by the python handler "p". The statement missing is the statement to close these files Ex: p.close(). Without this statement, the opened files adds more pressure on the system's resource.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT