我的代码长度不断扩大。有没有一种方法可以简化它?

时间:2018-10-30 19:12:49

标签: python python-2.7 codeskulptor

这是我为学校编写的一些代码。问题是,如果我继续添加更多的“输入”功能,所使用的行和所使用的“和”功能的数量,那么它会在两个区域中变得非常长。太大了,以至于我的作业页面都滞后了。如果您想用7个或更多的数字来做,那将使我的页面滞后更多。 如何简化下面的代码?

分配:编写程序以输入6个数字。输入每个数字后,请打印到目前为止输入的最大数字。

lyst=[1,1,0,0,1]
k=3
pred = [int(sum(lyst[start:start+k]) >= k/2)
            for start in range(0, len(lyst)-k)]

2 个答案:

答案 0 :(得分:1)

只要您使用一个简单的循环运行正文六次,就可以在没有任何列表或特殊语法的情况下完成此操作:

largest = None
for _ in range(6):
    number = int(input('Enter a number: '))
    if largest is None or number > largest:
        largest = number
    print('Largest: {}\n'.format(largest))

如果由于某种原因不允许您使用循环,则可以通过手动展开循环来获得相同的结果:

largest = int(input('Enter a number: '))
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
    largest = number
print('Largest: {}\n'.format(largest))

答案 1 :(得分:0)

您可以仅将数字存储在变量中,并在用户输入较大的数字时覆盖它。

awesome_number = 0
while True: # Always loop unless we break the loop.
    userInput = int(input("Enter a number:")) # Your input phrase

    # Compare values, evaluates to True if the user input is greater
    if userInput > awesome_number: 
        awesome_number = userInput # Overwrite if compare evaluates to True
    # Print using the .format method to dynamically insert the greatest
    # number
    print("So far, the biggest number you've entered is {}".format(awesome_number))

如果要在n次输入后停止,可以添加一个简单的计数器来计算迭代次数。

awesome_number = 0
counter = 0
while True: # Always loop unless we break the loop.
    userInput = int(input("Enter a number:")) # Your input phrase

    # Compare values, evaluates to True if the user input is greater
    if userInput > awesome_number: 
        awesome_number = userInput # Overwrite if compare evaluates to True
    # Print using the .format method to dynamically insert the greatest
    # number
    print("So far, the biggest number you've entered is {}".format(awesome_number))
    # Increment the counter
    counter = counter + 1
    if counter == 500: # Arbitrary number to end on
        break