[英]Why my code doesn't work the else statement?
有人可以幫我做我的代碼嗎? 我寫了一個小程序只是為了學習一些功能以及正在發生的事情。 讓我向您展示我的代碼。
print "Hello student need help multiplying by any mutiplicaton"
student = raw_input("If so then tell me which ones? => ").lower()
for i in range(0, 11):
if student == str(0):
i_num = 0 * i
print "0 times %d equals %d" % (i,i_num)
elif student == str(10):
i_num = 1 * 1
print "1 times %d equals %d" % (i,i_num)
else:
print "Try this program when you can't figure it out your multiplications."
如果學生輸入的內容與if語句無關,則將打印else。 但是,如果學生輸入str(1),它將打印乘法,也將打印else,這就是我不想發生的代碼問題。 誰能幫我。 我只是想學習if和elif以及所有這些功能。
將else
設置為在成功完成for
循環時運行,請看縮進。 如果將其移動到循環中,則一切正常。 您的代碼確實包含一些語法錯誤。
程序的固定版本:
print "Hello student need help multiplying by any mutiplicaton"
student = raw_input("If so then tell me which ones? => ") # no need for lower()
for i in range(0, 11):
if student == '0':
i_num = 0 * i
print "0 times %d equals %d" % (i,i_num)
elif student == '1':
i_num = 1 * 1
print "1 times %d equals %d" % (i,i_num)
else:
print "Try this program when you can't figure it out your multiplications."
但是乘法很容易,所以為什么不這樣做:
print "Hello student need help multiplying by any mutiplicaton"
num = int(raw_input("If so then tell me which ones? => "))
for i in range(0, 11):
print "%d times %d equals %d" % (num, i, i * num)
您在這里缺少):
elif student == str(10):
def isAnInt(s):
try:
int(s)
return True
except ValueError:
print "You must enter a number"
print "Hello student need help multiplying by any mutiplicaton"
student = raw_input("If so then tell me which ones? => ")
if(isAnInt(student)):
number_to_calc = int(student)
for i in range(0,11):
i_num = number_to_calc * i
print "%d times %d equals %d" % (number_to_calc, i, i_num)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.