繁体   English   中英

为什么我的代码对else语句不起作用?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM