![](/img/trans.png)
[英]Trying to write a code in Python 3 that asks for how many steps to draw the stairs
[英]How to write a code that asks for 10 numbers
大家好,我正在尝试编写一个代码,要求用户输入 10 个整数并打印出其中最大的一个。 这是我到目前为止:
n = [int(input('Enter a number: ')) for i in range(10)]
largestodd = None
i = 0
for largestodd in n:
if n % 2 == 1:
if largestodd == None or n > largest:
largestodd = n
i = i + 1
但是,我不断收到“ if n % 2 == 1: TypeError: unsupported operand type(s) for %: 'list' and 'int'” 谁能帮我解决这个问题?
您在此处编写的代码有很多问题:
for
循环遍历列表,因此无需事先定义将用于遍历列表的变量。 这在while
循环中通常是必需的前任:
l = [1, 2, 3]
for i in l:
print(i)
输出:
1
2
3
如果你想用一个 while 循环来做到这一点,代码看起来像:
l = [1, 2, 3]
i = 0
while i < len(l):
print(l[i])
i += 1
很明显,for 循环使用起来更加方便和优雅。
largest
没有定义l = [int(input('Enter a number: ')) for i in range(10)]
print(max(l))
Python 有一个内置方法max()
可以在不需要for
循环的情况下实现这一点。
另一种方法是使用.sort()
方法对列表进行排序,然后打印出列表的最后一位数字:
l = [int(input('Enter a number: ')) for i in range(10)]
l.sort()
print(l[-1])
要以相反的顺序排序:
l = [int(input('Enter a number: ')) for i in range(10)]
l.sort(reverse=True)
print(l[0])
如果你想使用逻辑来做到这一点,你可以通过对列表进行排序然后打印出列表的最后一位(这将是最大的)来做到这一点,如下所示:
l = [int(input('Enter a number: ')) for i in range(10)]
for i in range(len(l) - 1):
for j in range(len(l) - i - 1):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
print(l[-1])
上面的代码使用冒泡排序对列表进行排序。 还有其他方法可以对列表进行排序,但这是最容易理解的。 您可以在互联网上了解更多相关信息,例如此处。
你的代码在说
largestodd = None
for None in n:
你可以用它做你想做的事
n = [int(input('Enter a number: ')) for i in range(10)]`
print(max(n))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.