先上問題:input BIF
看下面這段代碼,無論怎麼測試都退不出循環,很鬱悶
print('=-------------閏年計算器-------------=')
print('注意:輸入查詢的年份,格式:XXXX,如2014')
temp = 1
while temp != 110:
temp = input('請輸入查詢的年份: ')
while temp.isdigit() != 1:
temp = input('對不起,輸入格式爲正數!重新輸入:')
year = int(temp)
if year / 400 == int(year / 400):
print('公元', temp, '年是閏年!')
else:
if (year / 4 == int(year / 4)) and (year / 100 == int(year / 100)):
print('公元', temp, '年是閏年!')
else:
print('公元', temp, '年是平年!')
print('GameOver')
爲了方便測試,簡化一下代碼
temp = 0
while temp != 520:
temp = input('enter a number:')
print(temp)
結果是這樣的:
enter a number:520
520
enter a number:520
520
enter a number:520
520
enter a number:
想辦法解決,查看 while 和 input 兩個BIF
>>> help(input)
Help on built-in function input in module builtins:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.The prompt string, if given, is printed to standard output without a trailing newline before reading input.
哎呀我去,input-read a string from standard input
update code
temp = 0
while temp != '520':
temp = input('enter a number:')
print(temp)
print('=-------------閏年計算器-------------=')
print('注意:輸入查詢的年份,格式:XXXX,如2014')
temp = 1
while temp != '110':
temp = input('請輸入查詢的年份: ')
while temp.isdigit() != 1:
temp = input('對不起,輸入格式爲正數!重新輸入:')
year = int(temp)
if year / 400 == int(year / 400):
print('公元', temp, '年是閏年!')
else:
if (year / 4 == int(year / 4)) and (year / 100 == int(year / 100)):
print('公元', temp, '年是閏年!')
else:
print('公元', temp, '年是平年!')
print('GameOver')
總結:BIF使用時,一定要注意