0

I made a program that looks like:

n = eval(input("enter a whole number: "))
x = 1
print (x)
while x != n:
    x = x + 1
    print (x)

This code produces a list from 1 to the given whole number n.

What would i do to be able to interact with this list making a second column that gave the square of the adjacent number?

something like

1 1 
2 4
3 9

3 Answers 3

1

If you want to be able to show the square of 1, you need to initialize x as 0 and delete print(x) from your third line

this should do it:

n = eval(input("enter a whole number: "))
x = 0
while x != n:
    x = x + 1
    print (x, " ", x**2)

This code prints x and x**2 (the value of 'x ^ 2') separated by a space.

Sign up to request clarification or add additional context in comments.

2 Comments

I do not know what the downvote is for, this outputs exactly what he needs
@vilty no problem, please accept answer if this helped you
1

Here is what you are looking for:

n = eval(input("enter a whole number: "))
x = 1
print (x)
while x != n:
    x = x + 1
    p = x * x
    print (x, p)

I would urge caution on using eval() so lightly though, you can use the int() function to run a string as an integer. Here is how I would write that code:

n = int(input("enter a whole number: "))
x = 0
while x != n:
    x = x + 1
    p = x * x
    print (x, p)

EDIT: Updated code

2 Comments

Why would you evaluate int(n) every time through the loop, instead of once when setting n?
I am new to python and that did not occur to me, but it does make sense, I will update the code
0

Well, you could use a list of lists. Using a generator expression,

nums = [[n, n**2] for n in range(1,int(input("Enter a number"))]

So if you input 10, nums[1,1] will be 2.

So to print this out,

for i in nums:
    print(i[0] + " " + i[1])

This is by far the simplest way to go.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.