Python中的平方数列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22304562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:43:58  来源:igfitidea点击:

Square number sequence in Python

pythonwhile-loopsequence

提问by iNuwanS

I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.

我是 python 的新手,我正在尝试编写一个代码来打印所有平方数,直到用户输入的所需值的平方为止。

    n = raw_input("Enter number")

    a=1

    while a < n:
            a=1
            print a*a
            a += 1
            if a > n:
            break

When I run this code it infinitely prints "1" ... I'm guessing that the value of adoes not increase by +=so it's a=1forever. How do I fix this?

当我运行这段代码时,它会无限地打印“1”……我猜它的值a不会增加,+=所以它是a=1永远的。我该如何解决?

采纳答案by Christian

There are some problems. First, your input (what raw_input()returns) is a string, so you must convert it to integer:

有一些问题。首先,您的输入(raw_input()返回的内容)是string,因此您必须将其转换为 integer

n = int(raw_input(...))

Second, you are setting a = 1each iteration, so, since the loop condition is a < n, the loop will run forever ( if n > 1). You should delete the line

其次,您正在设置a = 1每次迭代,因此,由于循环条件为a < n,循环将永远运行( if n > 1)。你应该删除该行

a = 1

Finally, it's not necesary to check if a > n, because the loop conditionwill handle it:

最后,没有必要检查 if a > n,因为循环条件会处理它:

while a < n:
    print a * a
    a += 1

    # 'if' is not necessary

回答by Zaur Nasibov

There is a small error in your code:

您的代码中有一个小错误:

while a < n:
    a=1            # `a` is always 1 :)
    print a*a
    a += 1
    if a > n:
        break

回答by Michelle

You're setting the value of aback to 1on every iteration of the loop, so every time it checks against n, the value is 2. Remove the a=1line.

您在循环的每次迭代中都将aback的值设置为1,因此每次检查时n,该值为2。删除a=1线。

回答by Daren Thomas

The first line in your loop sets's ato one on every iteration.

循环中的第一行在a每次迭代时都设置为一行。

回答by RexE

You assign a=1 inside the loop. That means it's overwriting the a+=1.

您在循环内分配 a=1 。这意味着它正在覆盖a+=1.

回答by jonrsharpe

As others have noted, your specific problem is resetting aeach time you loop. A much more Pythonic approach to this is the forloop:

正如其他人所指出的,您的具体问题是a每次循环时都会重置。一个更加 Pythonic 的方法是for循环:

for a in range(1, n):
    print(a ** 2)

This means you don't have to manually increment aor decide when to breakor otherwise exit a whileloop, and is generally less prone to mistakes like resetting a.

这意味着您不必手动递增a或决定何时break或以其他方式退出while循环,并且通常不太容易出现重置等错误a

Also, note that raw_inputreturns a string, you need to make it into an int:

另外,请注意raw_input返回一个字符串,您需要将其变成一个int

n = int(raw_input("Enter number: "))

回答by nakkulable

try this:

尝试这个:

n = eval(raw_input("Enter number"))

a=1

while a < n:            
        print a*a
        a += 1

The issue here is that the value of a gets overridden every time you enter in the loop

这里的问题是每次进入循环时 a 的值都会被覆盖

回答by Joran Beasley

an even better idea is to make a simple function

一个更好的主意是做一个简单的函数

def do_square(x):
    return x*x

then just run a list comprehension on it

然后只需对其运行列表理解

n = int(raw_input("Enter #:")) #this is your problem with the original code
#notice we made it into an integer
squares = [do_square(i) for i in range(1,n+1)]

this is a more pythonic way to do what you are trying to do you really want to use functions to define functional blocks that are easy to digest and potentially can be reused

这是一种更pythonic的方式来做你想做的事情你真的想使用函数来定义易于理解并且可能可以重用的功能块

you can extend this concept and create a function to get input from the user and do some validation on it

您可以扩展这个概念并创建一个函数来从用户那里获取输入并对其进行一些验证

def get_user_int():
    #a function to make sure the user enters an integer > 0
    while True:
         try:
            n = int(raw_input("Enter a number greater than zero:"))
         except TypeError:
            print "Error!! expecting a number!"
            continue;
         if n > 0: 
            return n
         print "Error: Expecting a number greater than zero!"

and then you can build your input right into your list

然后您可以将您的输入直接构建到您的列表中

 squares = [do_square(i) for i in range(1,get_user_int()+1)]

and really do_squareis such a simple function we could easily just do it in our loop

真的do_square是一个如此简单的函数,我们可以很容易地在我们的循环中完成它

squares = [x*x for x in range(1,get_user_int())]

回答by Souvikavi

Problem is in the condition of the while loop, to print squares of numbers upto a limiting value, try this..

问题是在 while 循环的条件下,要打印达到极限值的数字平方,试试这个..

def powers(x):
    n=1
    while((n**2)<=x):
        print(n**2, end =' ')
        n +=1