0

I want to take an input from the user and and store it in a variable, lets say k. Then use this k as a counter for a for loop.

while i<k: doesn't work! code:

k= input('number of points:')
p=[]
i=0
while i<k:
x=float(input('Enter value='))
p.append(x)
i=i+1

Output:

number of points:3
Traceback (most recent call last):
File "/home/ramupradip/tes.py", line 4, in <module>
while i<k:
TypeError: unorderable types: int() < str()

I also tried using range

for i in range(1,k)

which gave me an error: Traceback (most recent call last): File "/home/ramupradip/reflect.py", line 6, in for i in range(1,k): TypeError: 'str' object cannot be interpreted as an integer

2
  • 2
    what is k.....? is it int?Plz post errors that you getting Commented Sep 4, 2013 at 14:27
  • Please explain what "doesn't work" means. Commented Sep 4, 2013 at 15:09

2 Answers 2

1

Read the input like this:

k = int(input('enter counter: '))

... I guess you forgot to convert the number to int, but it's impossible to tell if you don't show the relevant code. Other than that, the looping constructs shown in the question should work fine, but the first one is preferred in Python, just be careful with the indexes:

for i in range(1, k+1):
    # do something

Equivalently:

i = 1
while i <= k:
    # do something
    i += 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you :) . It was the missing 'int' which was the problem.
0

That does not make any sense. You could want this:

for i in range(k):
     ...

Where k is the total number of iterations set by the user and i is a value that changes from 0 to k - 1. Or you could want this:

for k in range(x):
     ...

Where k is a value from 0 to x - 1 and the user input doesn't mean anything. Or you could want this:

for i in range(k, x):
    ...

Where k is the start value set by the user, x is a value set by the program and i is a value that starts from k and ends in x - 1

See the documentation for more info http://docs.python.org/3/library/functions.html#func-range

1 Comment

You're changing the starting value of i, this is not equivalent to the code in the question. It might be possible that OP is only interested in looping k times (we can't tell by just looking at the current question), but if he is going to use i, the expected starting value is 1, according to the question

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.