这里的代码极端初学者。阅读John V. Guttag撰写的“使用Python进行计算和编程简介”。最初的问题之一是:
“编写一个检查三个变量-x,y和z-的程序 并打印其中最大的奇数。如果它们都不是奇数,那就是 应该打印一条消息。“
我提出的代码在第5,7和9行有一个语法错误。由于我是一个完全的初学者,我无法弄明白。建议欢迎!
FirstNumber=int(input("Enter First Number:"))
SecondNumber=int(input("Enter Second Number:"))
ThirdNumber=int(input("Enter Third Number:"))
if (FirstNumber%2!=0:) and (FirstNumber > SecondNumber and FirstNumber > ThirdNumber)
print 'First Number is largest odd -> '+str(FirstNumber)
elif (SecondNumber%2!=0:) and (SecondNumber > FirstNumber and SecondNumber > ThirdNumber)
print 'Second Number is largest odd -> '+str(SecondNumber)
elif (ThirdNumber%2!=0:) and (ThirdNumber > FirstNumber and ThirdNumber > SecondNumber)
print 'Third Number is largest odd -> '+str(ThirdNumber)
else:
print 'None are odd -> '+str(FirstNumber), str(SecondNumber), str(ThirdNumber)
答案 0 :(得分:1)
如评论中所述,您的代码在每个if
和elif
语句的末尾都缺少冒号。此外,您的代码在第一个条件测试中具有无关冒号(即(FirstNumber%2!=0:)
。
另外,正如您所说,您是初学者,有一些关于简化代码或提高可读性的建议......
firstNum = int(input("Enter First Number: "))
secondNum = int(input("Enter Second Number: "))
thirdNum = int(input("Enter Third Number: "))
# In this case, we don't need the parenthesis. (Sometimes parens are
# required to ensure that the logic works correctly, but in this case,
# we don't.) Python short circuits, meaning it will stop the If
# statement mid-way as soon as a conditional statement equivocates to False.
if firstNum % 2 != 0 and firstNum > secondNum and firstNum > thirdNum:
print 'First Number is largest odd -> ' + str(firsthirdNum)
elif secondNum % 2 != 0 and secondNum > firstNum and secondNum > thirdNum:
print 'Second Number is largest odd -> ' + str(secondNum)
elif thirdNum % 2 != 0 and thirdNum > firstNum and thirdNum > secondNum:
print 'Third Number is largest odd -> ' + str(thirdNum)
else:
print 'None are odd -> ' + str(firstNum), str(secondNum), str(thirdNum)
答案 1 :(得分:0)
答案 2 :(得分:0)
在:
中的每个条件结束时,您需要冒号(if-statement
)(而不是每个组成部分的结尾)。这只是你需要知道的语法;没什么特别的。
另外两个不必要的事情是你应该添加一些空格以使操作更清晰,并且可以删除!= 0
检查,因为任何整数都不是0
评估为True
所以会达到同样的效果。最后,不需要括号。
所以这里是更正后的代码:
FirstNumber = int(input("Enter First Number:"))
SecondNumber = int(input("Enter Second Number:"))
ThirdNumber = int(input("Enter Third Number:"))
if FirstNumber % 2 and FirstNumber>SecondNumber and FirstNumber>ThirdNumber:
print 'First Number is largest odd -> '+str(FirstNumber)
elif SecondNumber % 2 and SecondNumber>FirstNumber and SecondNumber>ThirdNumber:
print 'Second Number is largest odd -> '+str(SecondNumber)
elif ThirdNumber % 2 and ThirdNumber>FirstNumber and ThirdNumber>SecondNumber:
print 'Third Number is largest odd -> ' + str(ThirdNumber)
else:
print 'None are odd -> ' + str(FirstNumber), str(SecondNumber), str(ThirdNumber)