Mayor Mayor - 11 days ago 6
Python Question

python in raspberry pi terminal not outputting what it should

I have a problem that i encounter in the raspberry pi terminal.

>>> alarm = input('Please input the time for the alarm in format HHMM: \n ')
>>> print(alarm)


I type 0700, press enter, but it prints out 448 instead of 0700.
When I tried it in IDLE it put out 0700. Why won't it put out 0700 in the raspberry pi terminal? And how can I get the terminal to put 0700 out?

Answer

The input() function will take your input and convert it into a string.

0070 is considered as an octal number. It is first converted to a decimal number and then converted to string.

print str(0070)
>>> 56

import time
alarm = str(raw_input('Please input the time for the alarm in format HHMM: \n '))
print alarm

>>> Input: 0080
>>> Output: 0080

You should validate the time the user enters. For example you cannot enter a time like 4012. You can validate the time using datetime module as follows:

import datetime
try:
    a = datetime.datetime.strptime(raw_input('specify time in HHMM format: '), "%H%M")
    print a.strftime("%H%M")
except:
    print "Please enter correct time in HHMM format"

There are other advantages of using datetime object. You can perform various operations on your time. For eg. Add time to it, subtract time from it, convert it to various formats, etc. Read this for more info: https://docs.python.org/2/library/datetime.html

Comments