在while循环中在if语句之外打印

2024-09-24 22:19:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何打印最后一行(是唯一的,不是唯一的),而不打印输入项之间的顺序(下一步:)?你知道吗


Tags: oftheinputifisteststhisprogram
2条回答

看起来您要做的是在输入每个数字时检查它是否已经在序列中。如果是,您可以立即将其声明为“非唯一”并跳出循环。否则,您将一直运行,直到用户以-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添加到序列中。你知道吗

戴夫·科斯塔正确地更正了你的代码。如果您对较短的内容感兴趣,这里有一个替代解决方案:

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!

相关问题 更多 >