【问题标题】:How to check if two consecutive inputs in a loop are the same (PYTHON)?如何检查循环中的两个连续输入是否相同(PYTHON)?
【发布时间】:2021-11-29 01:11:42
【问题描述】:

我目前正在尝试制作一个程序,它首先询问用户可数整数的数量。然后程序继续向用户单独询问每个可数整数,最后,程序打印计算出的总整数的总和。 这是我的程序的代码:

amount_of_integers = int(input("How many numbers do you want to count together: "))
sum = 0
repeat_counter = 1

while repeat_counter <= amount_of_integers:
    countable_integer = int(input(f"Enter the value of the number {repeat_counter}: "))
    sum += countable_integer
    repeat_counter += 1

print()
print("The sum of counted numbers is", sum)

这就是它目前的工作方式:

How many numbers do you want to count together: 5
Enter the value of the number 1: 1
Enter the value of the number 2: 2
Enter the value of the number 3: 3
Enter the value of the number 4: 4
Enter the value of the number 5: 5

The value of the counted numbers is: 15

现在,棘手的部分来了:如果两个 CONSECTUTIVE 输入都为零 (0),则程序应该结束。如何创建一个变量来检查程序中每个 CONSECTUTIVE 输入的值是否不为零?我需要创建另一个循环还是什么?

这就是我希望程序工作的方式:

How many numbers do you want to count together: 5
Enter the value of the number 1: 1
Enter the value of the number 2: 0
Enter the value of the number 3: 0

Two consectutive zero's detected. The program ends.

提前致谢!

【问题讨论】:

    标签: python loops input integer counting


    【解决方案1】:

    好吧,让我们先将问题分解为它的组成部分,您有两个要求。

    1. 总和
    2. 如果连续给出两个零,则退出

    你已经完成了一个,对于两个考虑有一个 if 来确定给定值是否是非零值,如果它是零值检查它不等于最后一个值。

    你可以修改你的代码如下

    amount_of_integers = int(input("How many numbers do you want to count together: "))
    sum = 0
    repeat_counter = 1
    # last integer variable
    last_integer = None
    
    while repeat_counter <= amount_of_integers:
        countable_integer = int(input(f"Enter the value of the number {repeat_counter}: "))
        # if statement to validate that if the last_integer and countable_integer
        # are equal and countable_integer is zero then break the loop
        if countable_integer == last_integer and countable_integer == 0:
            break
        else:
            last_integer = countable_integer
        sum += countable_integer
        repeat_counter += 1
        
    print()
    print("The sum of counted numbers is", sum)
    

    【讨论】:

    • 非常感谢您帮助我!你让我学到了一些新东西。
    猜你喜欢
    • 1970-01-01
    • 2021-03-06
    • 2023-04-01
    • 1970-01-01
    • 2022-11-22
    • 2016-07-07
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多