【问题标题】:How to end whileTrue loop when same input value is put in twice?当两次输入相同的输入值时如何结束while True循环?
【发布时间】:2021-05-26 11:04:39
【问题描述】:

如果看起来很奇怪,我很抱歉,这是我第一次发帖。

问题是,如果相同的单词 str 输入连续输入两次,我该如何结束循环并打印整个故事(我尝试使用 len(set()) 执行此操作,但没有成功) ?

story = ""

while True:
    word = input("Give me a word: ")

    if word == "end" or word == len(set(word)):
        break

    story += word + " " 

print(story)

【问题讨论】:

  • 我知道如果一个人在努力寻找解决方案时会尝试绝望的事情,但问问自己:字符串 word 怎么可能与从 len 返回的数字相同?跨度>

标签: python input while-loop


【解决方案1】:

连续两次,我只记录前一个单词

story = ""
prev = ""

while True:

    word = input("Give me a word: ")

    if word == "end" or word == prev:

        break

    prev = word
    story += word + " "

print(story)

【讨论】:

    【解决方案2】:

    我会这样做:

    story = []
    prev = ""
    
    while True:
    
        word = input("Give me a word: ")
    
        if word == "end" or word == prev:
    
            break
    
        prev = word
        story.append(word+" ")
    
    print(''.join(story))
    

    【讨论】:

      【解决方案3】:
      '''Program to take single word as input from users, 
      combine input word as a string and end the program
      if any of the word in the string is repeated'''
      import re
      storyString = ""
      
      def takeInput(storyString):
          global inputWord 
          inputWord = input("Give me a word: ")
          creatWordFromString(storyString)
      
      def creatWordFromString(storyString):
          storyList = storyString.split()
          if inputWord in storyList:
              exit()
          else:
              storyList.append(inputWord)
              storyString =' '.join(storyList)
              print(storyString)
              takeInput(storyString)
          
      takeInput(storyString)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多