Home > front end >  Is it possible to assign only variables to the parameters of a range()?
Is it possible to assign only variables to the parameters of a range()?

Time:10-04

In a "range", is it possible to assign a number inputed by the user to a variable and use that variable for the start, stop, and set parameters in the range of a for loop?

Here is a piece of code that might help clear confusion:

Enter_integer = 4
for num in range((-Enter_integer) 1, (Enter_integer*-5) 1, Enter_integer):
        print(num, end = " ")

The main part I am having trouble with is the very last section where I try to add a "for loop" with a range and a variable that has an assigned valued from the beginning of the code, but nothing seems to output.

Is it even possible to have only variables in all three parameters of the "range function", or would I have to have a designated "stop" parameter inside the range function for the "for loop" to function?

Sorry if some of this is confusing, I'm a first year university student and I am new to code :/

CodePudding user response:

Is it even possible to have only variables in all ... ?

Yes. Not just in python but generally speaking, a variable can be used anywhere a value is supplied. You can put your mind at ease about that.

Enter_integer is positive, so -Enter_integer and Enter_integer*-5 are negative. You can't step from (in your case) -3 to -19 by 4. Try changing last parameter to -EnterInteger:

Enter_integer = 4
for num in range((-Enter_integer) 1, (Enter_integer*-5) 1, -Enter_integer):
    print(num, end = " ")

outputs:

-3 -7 -11 -15

CodePudding user response:

Yes you can do this. There's a few ways:

First and simplest, but requires more user input:

  • Ask the user to input each var themselves in the command line (assuming you're running on a command line)
    print("Enter start number: ")
    start = input()
    print("Enter stop number: ")
    stop = input()
    print("Enter step number: ")
    step = input()

Then run the rest of your code with those vars:

    for num in range(start, stop, step):
        do things

But from your code it looks like you only need one number 'enter_integer' to resolve the start, stop, and step, so:

    print("Enter your number: ")
    number = input()

Here it would be better to make new vars for your start, stop, step so you don't have excess unreadable code in your range() function:

    start = how you get start
    stop = how you get stop
    step = how you get step

Then as before:

    for num in range(start, stop, step):
        do things
  • Related