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

时间:2018-06-27 01:28:48

标签: python python-3.x

我是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..

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

2 个答案:

答案 0 :(得分:1)

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 :(得分:1)

看起来您想要做的就是检查,在输入每个数字时,是否已经在序列中。如果是这样,则可以立即将其声明为“非唯一”并退出循环。否则,您将继续操作直到用户通过结束-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添加到序列中。