ToofanHasArrived
ToofanHasArrived

Reputation: 85

Passing user input as limit for python for loop

I am new to python and would like to set user input as the limit in a for loop. Code below:

    q = raw_input("Enter desired instances: ");
    for x in range(0, q)
       print "Hello"

Currently I am getting a syntax error. I have also tried %q and $q and those fail also.

Upvotes: 1

Views: 2088

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You need to convert the result to int since raw_input returns a string.

q = raw_input("Enter desired instances: ")
for x in range(0, int(q)):
    print "Hello"

And as a more pythonic approach since it's possible that user type a non digit input and in that case python will raise a ValueError you can use a try-except expression to wrap your code for handling the exception.

Upvotes: 3

comalex3
comalex3

Reputation: 2606

q = int(raw_input("Enter desired instances: "))
for x in range(q):
   print "Hello"

raw_input() return string, need convert to int

Upvotes: 5

Related Questions