0

I would like pass the variables into the function that uses range(). How do I pass variable C that has more then one number via one variable. Something like range(5, 10, 2)?

Here is my example code:

a = 0
b = 10
c = 2   
def num_count(a, b, c):
        for number in range(c):
            a += b
        print("New Count is: {0}".format(a))

I tried passing it as a string and converting it to an integer as well as by using a list. Nothing worked.

7
  • 2
    You mean like c=(5,10,2) then range(*c) ? Commented Jul 5, 2017 at 19:25
  • Yes. I keep getting errors that I am passing a string. Commented Jul 5, 2017 at 19:26
  • Then stop passing a string. Commented Jul 5, 2017 at 19:26
  • Create the range outside the function and pass it in…? What's the best approach is very debatable with such artificial scenarios. Commented Jul 5, 2017 at 19:26
  • 1
    It means "expand this variable" so it becomes three arguments to range. See docs.python.org/3/tutorial/… Commented Jul 5, 2017 at 19:33

1 Answer 1

3

you can pass in the range like you mentioned with only a small change to the for loop

a = 0
b = 10
c = range(5, 10, 2)   
def num_count(a, b, c):
    for number in c:
        a += b
    print("New Count is: {0}".format(a))

num_count(a,b,c)

or, as khelwood* mentioned, pass in a list/tuple and expand it with *

a = 0
b = 10
c = (5, 10, 2)   
def num_count(a, b, c):
    for number in range(*c):
        a += b
    print("New Count is: {0}".format(a))

num_count(a,b,c)

both output 30 which is expected

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

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.