私はこのクラスを作成しようとしていますが、私は小さな問題があります。私はいつもループに問題があるようです!尋ねられたとおりに日付を入力するとプログラムが機能しますが、入力が間違っている場合は、日付を再度尋ねることはできません。 True/Falseブール値を作成しましたが、うまくいかないようです。特定の日付モジュールをインポートして変換する方法を学習していないので、月を手動で変換しています。Pythonユーザ入力と日付変換
説明:
A.ユーザーから数値形式で日付を入力します。 mm/dd/yy。
B.ユーザーが入力した月を調べます。 12より大きい場合、または1より小さい場合はエラーメッセージを出し、入力を再度要求します。
C.同様の日付と年の検証テストを実行します。年は とする必要があります(他の年は無効です)。さらに、年は2桁でなければなりません。
D.すべての入力が検証されたら、長い日付形式で文字列を出力します。したがって06/01/15に入力された文字列は、6月1日、2015として出力
def main():
try_again = True
while try_again == True:
date_string = input("Please enter a date in the format 'mm/dd/yy': ")
date_list = date_string.split('/')
month = date_list[0]
day = date_list[1]
year = date_list[2]
if month > "12" or month < "01":
print('Error, please re-enter the date!')
if year != '13':
print('Error! The year must be 2013')
if len(year) > 2:
print('Error! The year can only be 2 digits long!')
else:
print_date(month, day, year)
try_again = False
def print_date(month, day, year):
# Convert to 2013 because 2013 is the only valid year
# for this program.
if year == '13':
year = '2013'
# Convert the number values to the actual month.
if month == '01':
month = 'January'
if month == '02':
month = 'February'
if month == '03':
month = 'March'
if month == '04':
month = 'April'
if month =='05':
month = 'May'
if month == '06':
month = 'June'
if month == '07':
month = 'July'
if month == '08':
month = 'August'
if month == '09':
month = 'September'
if month =='10':
month = 'October'
if month == '11':
month = 'November'
if month == '12':
month = 'December'
# Print the date in the correct format
print(month + " " + day + ',' + " " + year)
main()
余分な 'if'ステートメントの代わりに、' elif'ステートメントを使いませんか? – jcfollower
ちょうど警告:「月」と文字列「01」と「12」を比較すると、それが有効な入力であることが保証されません:「01」<「0asb」< '12' ==>真 ' –
'month.isdigit()と1 <= int(month)<= 12)' –