【问题标题】:Why am I not getting 333 in Python为什么我在 Python 中没有得到 333
【发布时间】:2022-01-22 22:53:36
【问题描述】:
num=int(input("what is your number"))
total=int(input("how many times do you want this number to appear"))
new_num=0
for i in range (total):
    new_num=num*10
    new_num=new_num+num
print (new_num)

即使我将范围更改为 (total+1),我也一直得到 33。我必须做什么才能获得 333

【问题讨论】:

  • 您输入的总计值是多少?请同时指定它们。

标签: python python-3.x ranged-loops


【解决方案1】:

当您遇到此类问题时,请使用调试器(python 在 pdb 中包含一个)来单步调试代码并查看变量如何变化。

在简单的情况下,只需使用 print。在这种情况下,在每次分配给 new_num 之后添加一个print(new_num)

在这种情况下,您会注意到 new_num 被设置为错误值的位置。

您继续分配 new_num=num*10 而不是将 new_num 乘以 10

【讨论】:

    【解决方案2】:

    正如我从您的问题中了解到的那样,您将 num 的值视为3。对于total 以及相同的3

    注意:在发布您的问题时,请务必尝试提供一些示例,以便回答者可以阅读、理解和建议、帮助。

    我这里有一个快速的解决方案,只是尝试修改以用于其他目的。

    int(f'{num}' * total) 足以满足您的要求。你可以稍微改变一下,也可以为浮点数做。

    >>> num=int(input("what is your number: "))
    what is your number: 3
    >>> 
    >>> total=int(input("how many times do you want this number to appear: "))
    how many times do you want this number to appear: 3
    >>> 
    >>> int(f'{num}' * total)
    333
    >>> 
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 2020-11-19
      • 2013-07-15
      • 2022-01-14
      • 2023-01-23
      • 2010-12-08
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      相关资源
      最近更新 更多