【发布时间】:2015-01-16 07:08:57
【问题描述】:
我是编码新手,现在已经学习了几天。我用 Python 编写了这个程序,同时跟随了一些 MIT OpenCourseware 讲座和几本书。有没有更容易表达程序的方法?
手指练习:编写一个程序,要求用户输入 10 个整数,然后打印输入的最大奇数。如果没有输入奇数,它应该打印一条消息。
a = int(raw_input('Enter your first integer: '))
b = int(raw_input('Enter your second integer: '))
c = int(raw_input('Enter your third integer: '))
d = int(raw_input('Enter your fourth integer: '))
e = int(raw_input('Enter your fifth integer: '))
f = int(raw_input('Enter your sixth integer: '))
g = int(raw_input('Enter your seventh integer: '))
h = int(raw_input('Enter your eighth integer: '))
i = int(raw_input('Enter your ninth integer: '))
j = int(raw_input('Enter your tenth integer: '))
if a%2 ==0:
a = 0
else:
a = a
if b%2 ==0:
b = 0
else:
b = b
if c%2 ==0:
c = 0
else:
c = c
if d%2 ==0:
d = 0
else:
d = d
if e%2 ==0:
e = 0
else:
e = e
if f%2 ==0:
f = 0
else:
f = f
if g%2 ==0:
g = 0
else:
g = g
if h%2 ==0:
h = 0
else:
h = h
if i%2 ==0:
i = 0
else:
i = i
if j%2 ==0:
j = 0
else:
j = j
value = a, b, c, d, e, f, g, h, i, j
max = max(value)
if max ==0:
print 'There are no odd numbers.'
else:
print max, 'is the largest odd integer.'
【问题讨论】:
-
请忽略 a 和 b 的 if 语句中的间距。原始代码有适当的间距。
-
是的,非常重要;研究循环和列表。
-
基本上你想要做的是将输入读入一个数组,然后循环遍历它,在每次迭代中设置一个顶部变量,然后返回顶部。
-
你可以开始查找循环。
-
其他人关于循环和列表的cmets是正确的。此外,您在此处获得的代码实际上在某些输入上失败 - 如果我输入十个负数,其中至少一个偶数和一个奇数,最大值将为
0,但正确答案将是负赔率之一.
标签: python