繁体   English   中英

在while循环中的if语句外部打印

[英]printing outside of if statement in while loop

我是python的初学者,我知道这个问题表明了这一点。 以下是我的代码和问题...

print("This program tests if the sequence of positive numbers you input are unique")
print("Enter -1 to quit")


def inputvalues():
    firstnumber=int(input("Enter the first number:"))
    Next=0
    sequence=[firstnumber]
    while Next !=-1:
       Next=int(input("Next: "))
       nextvalue=Next
       sequence.append(nextvalue)
       if sequence.count(nextvalue)==1:
          print("The sequence {} is unique!".format(sequence))
       else:
          sequence.count(nextvalue)>1
          print("The sequence {} is NOT unique!".format(sequence))

inputvalues()

正在打印以下内容...

This program tests if the sequence of positive numbers you input are unique
Enter -1 to quit
Enter the first number:5
Next: 6
The sequence [6] is unique!
Next: 7
The sequence [6, 7] is unique!
Next: 8
The sequence [6, 7, 8] is unique!
Next: 9
The sequence [6, 7, 8, 9] is unique!
Next: -1
The sequence [6, 7, 8, 9, -1] is unique!

我需要它来输出以下内容...

This program tests if the sequence of positive numbers you input are unique
Enter -1 to quit
Enter the first number: 9
Next: 5
Next: 3
Next: 6
Next: 23
Next: -1
The sequence [9, 5, 3, 6, 23] is unique..

如何在不打印输入条目之间的顺序的情况下打印最后一行(唯一的,不是唯一的)(下一个:)?

Dave Costa正确更正了您的代码。 如果您对较短的内容感兴趣,这是一个替代解决方案:

print("This program tests if the sequence of positive numbers you input are unique")
print("Enter -1 to quit")
sequence = list(map(int, iter(lambda: input('Enter a number: '), '-1')))
if len(sequence) == len(set(sequence)):
    print("The sequence %s is unique!" % sequence)
else:
    print("The sequence %s is NOT unique!" % sequence)

具有唯一编号的序列:

This program tests if the sequence of positive numbers you input are unique
Enter -1 to quit
Enter a number: 2
Enter a number: 4
Enter a number: 5
Enter a number: 1
Enter a number: -1
The sequence [2, 4, 5, 1] is unique!

具有重复编号的序列:

This program tests if the sequence of positive numbers you input are unique
Enter -1 to quit
Enter a number: 3
Enter a number: 5
Enter a number: 23
Enter a number: 5
Enter a number: -1
The sequence [3, 5, 23, 5] is NOT unique!

看起来您想要做的就是检查,在输入每个数字时,是否已经在序列中。 如果是这样,则可以立即将其声明为“非唯一”并退出循环。 否则,您将继续操作直到用户通过结束-1终止序列。 如果达到这一点,顺序必须是“唯一的”。

def inputvalues():
    firstnumber=int(input("Enter the first number:"))
    Next=0
    sequence=[firstnumber]
    while Next !=-1:
       Next=int(input("Next: "))
       nextvalue=Next
       sequence.append(nextvalue)
       if sequence.count(nextvalue)>1:
          print("The sequence {} is NOT unique!".format(sequence))
          break

    print("The sequence {} is unique!".format(sequence))

您可以尝试更多的想法:我认为nextvalue变量不是必需的。 您还需要确保不将-1添加到序列中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM