1

I am programming in python at the moment, but I have a general programming question.

I have a IF statement and depending on which if I need to use a for loop and some commands or I just need the commands without the for loop. Now, I can just copy my code, but I was wondering if it is possible to go into the for loop?

I'll give my example:

if counter == 0:
   for measurement in measlist: #here I work with a list and I need to loop through this list
         command 1

 elif counter ==1: #here I don't have a list so i cannot walk through the list
         command 1

My command 1 is a lot of code, so it would be nice if I don't need to copy it but I can reuse it.

tx

4
  • 5
    Make command a function?
    – R2RT
    Commented Nov 20, 2017 at 11:12
  • 1
    Just put your code of command 1 in a separate function, and call this function in your if/loop.
    – Igl3
    Commented Nov 20, 2017 at 11:13
  • 1
    This also looks a bit like an antipattern. A simpler fix might actually be to make a list (with just one element) when counter != 0 and then process the list you have regardless. It will only perform one iteration if your list only contains one element, but that's obviously fine. If whatever produced the list will always produce a list, perhaps you will find that the rest of your code becomes simpler and more straightforward.
    – tripleee
    Commented Nov 20, 2017 at 11:26
  • Thank you all for the good advice. I actually didn't thought of changing my variable into a list, which is actually very handy. And indeed placing my code into a function is also a very good solution! Thanks
    – VeVi
    Commented Nov 20, 2017 at 13:57

1 Answer 1

1

The simplest solution here would probably be to just use the for loop anyways, and if you happen to only have a single value at the beginning - to pack it into a 1-element list (or another iterable).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.