1

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?

Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
Mayor
  • 13
  • 1
  • 1
  • 4

2 Answers2

5

The problem is, you are using input() instead of raw_input().

raw_input() is gone in Python 3.

In order to fix your problem,

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

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

Okay but for a bit of an explantion:

raw_input() takes exactly what the user typed and passes it back as a string.

input() first takes the raw_input() and then performs an eval() on it as well.

So if you do (in Python 2) eval(str(0700), it will return 448

Will
  • 4,942
  • 2
  • 22
  • 47
5

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 should not allow the user to 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

Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78