Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我是错误地使用了Python循环还是遗漏了什么?_Python - Fatal编程技术网

我是错误地使用了Python循环还是遗漏了什么?

我是错误地使用了Python循环还是遗漏了什么?,python,Python,我目前是Python的初学者。这是我的问题:首先,程序要求你输入一个数字 例如,如果我放1,我就得到1。如果我投2,我就投12。如果我放3,我得到123。如果我放4,我得到1234。这就是这组问题的要点。然而,我开发了一个数学方程,如果我把它通过一个循环: if __name__ == '__main__': # ignore this part n = int(input()) s = 1 while s > n: z = s*10**(n-s)

我目前是Python的初学者。这是我的问题:首先,程序要求你输入一个数字

例如,如果我放1,我就得到1。如果我投2,我就投12。如果我放3,我得到123。如果我放4,我得到1234。这就是这组问题的要点。然而,我开发了一个数学方程,如果我把它通过一个循环:

if __name__ == '__main__': # ignore this part

    n = int(input())
    s = 1
    while s > n:
        z = s*10**(n-s)
        s += 1
        answer = z
        if s == n:
            print(z)
当我试图运行这段代码时,我一无所获,尽管我在最后添加了print。我在这里做错了什么?对于任何回答问题的人,请介绍您知道的任何可能对我有帮助的概念;我想学它


请开导我。不要给我确切的答案……但试着引导我走向正确的方向。如果我在代码中犯了错误(我100%确定我犯了错误),请向我解释错误。

这是因为您的while循环条件是向后的。它从不进入循环,因为s不大于n。它应该是
,而s

以下是解决方案:

使用字符串

a = int(input())

# taking the input from the user
res=''
# using empty string easy to append 
for i in range(1,a+1):
     # taking the range from 1 (as user haven't said he want 0, go up to 
     # a+1 number (because range function work inclusively and  will iterate over 
     # a-1 number, but we also need a in final output ))
     res+=str(i)
     # ^ appending the value of I to the string variable so for watch iteration 
     # number come append to it.
     # Example :  1-> 12-> 123-> 1234-> 12345-> 123456-> 1234567-> 12345678-> 123456789
     # so after each iteration number added to it ,in example i have taken a=9

sol = int(res) #converting the res value(string) to int value (as we desire)

print(sol)
在一行中,解决方案是

a=int(input())
res=int(''.join([str(i) for i in range(1,a+1)]))

使用
range()
循环使用

for i in range(1, n+1):
其中,
n
是输入,以便可以获得从
1
n
的数字

现在使用
print()
在每次迭代期间打印
i
的值

print()
默认情况下将在末尾添加一个换行符。要避免这种情况,请使用如下参数

print(var, end='')

一旦熟悉了这一点,您还可以使用and
join()
通过以下语句获得输出

print( ''.join([str(i) for i in range(1, n+1)]) )

使用
input()
int()
进行输入,尽管您可能希望在输入不是整数的情况下包含异常处理

请参阅。

试试这个

n = int(input('Please enter an integer'))
s = 1
do:
    print(s)
    s+=1
while s == n
这很有效。
(简单且简短)

对于任何正输入,您将永远不会进入循环,因为条件不满足。对于输入=11,输出将是
1234567891011
?@prashantrana,这是正确的,您的循环条件总是失败的。对于负整数,代码可以工作,但对于正整数,它永远不会进入循环条件。更新循环条件
,但您不能在此问题中使用字符串。不幸的是,它不适用于数字10或更大的数字。@Kid\u Vic查看更新的循环条件。它对所有人都有效。向某人提供解决方案并不能帮助他们了解自己做错了什么。说明为什么原始代码是错误的,不要只是提供一个替代方案,而不是解释为什么替代方案更正确。另请参见。@halfer将从现在开始尝试给出更多解释的解决方案。哇……我真是太傻了。谢谢你的反馈,杀手!在这种情况下,“var”是什么意思?@Kid\u Vic需要打印的变量。因此,如果循环中的变量是
i
,则将
var
替换为
i