I need help writing this Python program: All oranges sold in a grocery store hav
ID: 3690434 • Letter: I
Question
I need help writing this Python program:
All oranges sold in a grocery store have a 4-digit product code. If the rightmost digit is '4', the orange is from California. If the rightmost digit is '7', the orange is from Florida.
For example, an orange with product code '8124' is from California. An orange with product code '6547' is from Florida. Write a program to do the following:
(a) Ask the user to enter the 4-digit code of an orange.
(b) Strip all the leading and trailing whitespace characters from the code.
(c) Test whether the code consists of only numeric digits. If it is not, display an error message.
(d) Test whether the code has exactly 4 characters. If it has more or fewer than 4 characters, display an error message.
(e) Test the rightmost digit. If it is '4', display 'This orange is from California'. If it is '7', display 'This orange is from Florida'. If it is something else, display 'The last digit must be 4 or 7'.
The following are example outputs:
Enter product code: 12X45
Product code must consist of digits only.
Product code must not be longer or shorter than 4 characters.
The last digit must be 4 or 7
Another output example:
Enter product code: 0824
This orange is from California
Example output:
Enter a product code: 5237
This orange is from Florida
Explanation / Answer
inp = raw_input("ENter 4 digit code : ")
inp = inp.strip()
try:
number = int(inp)
except ValueError:
print "Product code must consist of digits only."
l = len(inp)
if l != 4 :
print "Product code must not be longer or shorter than 4 characters."
if int(inp[l-1]) != 4 and int(inp[l-1]) != 7 :
print "The last digit must be 4 or 7"
if int(inp[l-1]) == 4 :
print "This orange is from California"
elif int(inp[l-1]) == 7 :
print "This orange is from Florida"