如何在python的while循环结束时打印所有输出

时间:2018-07-12 04:24:40

标签: python python-3.x

我已经使用list.append()函数解决了这个问题,但是我的教练告诉我只能使用基本的python函数。这是我的代码:

    a = 0
    b = 0
    s = 0
    x = str(s)

    print ('Enter the first number: ', end = '')
    c = input()
    a = int(c)
    finished = False
    while not finished:
        print ('Enter the next number (0 to finish): ', end ='')
        n = input()
        b = int(n)
        if b != 0:
            if b == a: 
                x = ('Same')
            elif b > a:
                x = ('Up')
            elif b < a:
                x = ('Down')
            a = b
            s = x
        else:
            finished = True

    print (str(x))

我的目标是在while循环结束时在一行中打印(例如,向上,向下,向下,向下比较输入整数)。让我知道如何改善我的代码。非常感谢

3 个答案:

答案 0 :(得分:0)

不确定您要查找的结果是什么,但这也许可行:

a = 0
b = 99
result = ""

a = int(input('Enter the first number: '))

while b != 0:
    b = int(input('Enter the next number (0 to finish): '))

    if b == a:
        result += ' Same'
    elif b > a:
        result += ' Up'
    elif b < a:
        result += ' Down'
    a = b

print(result.strip())

输出:

Enter the first number: 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 5
Enter the next number (0 to finish): 0
Same Same Down Same Up Down

答案 1 :(得分:0)

您可以简单地用一个空字符串初始化CreateObject("Wscript.Shell").Run "C:\windows\system32\mshta.exe ""%cd%\app.hta""",0,True 并保持串联。

  <div itemscope itemtype="http://schema.org/Review">
 <div itemprop="itemReviewed" itemscope itemtype="http://schema.org/Restaurant">
<img itemprop="image" src="seafood-restaurant.jpg" alt="Catcher in the Rye"/>
<span itemprop="name">Legal Seafood</span>
 </div>
 <span itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">
<span itemprop="ratingValue">4</span>
 </span> stars -
<b>"<span itemprop="name">A good seafood place.</span>" </b>
<span itemprop="author" itemscope itemtype="http://schema.org/Person">
<span itemprop="name">Bob Smith</span>
 </span>
    <span itemprop="reviewBody">The seafood is great.</span>
    <div itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
     <meta itemprop="name" content="Washington Times">
   </div>
   </div>

答案 2 :(得分:0)

使用字符串连接来获得所需的结果,而无需使用列表:

http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python

我将给您两个有关如何为您的程序执行此操作的提示:

  1. 通过替换将x初始化为空字符串

    x=str(s)
    

    x=""
    

    没有必要以字符串“ 0”开头,因为s为0,str(s)会这样做。

  2. 而不是说

    x=('SAME')
    x=('UP')
    x=('DOWN')
    

尝试说

    x=x+'SAME'
    x=x+'UP'
    x=x+'DOWN'

我删除了括号,因为它们不是必需的。

关于样式,优良作法是将变量命名为有用的东西,而不只是字母。涵盖所有基础的if / else链中的最后一个要素应该是其他。先生,祝你好运

相关问题