Python Forum
Variable definitions inside loop / could be better?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable definitions inside loop / could be better?
#1
Dear Python Community,

I use Python a lot for my company projects, and I ussually do some taslks that seems to
repeats every time. For instance,I use to define vars prior to a loop, so I can use them
a few lines later in the code,
something like:

result = None
if cond_x == 'x':
    result = ....
print(result)
I feel there could be a better way to handle this. Of course, I am thinking something different
from the global tag, because it is just need in the current variable space.

Can you share your thoughts on this?

Best regars,

Gustavo A. Garcia
Gibgo
Yoriz write Jan-09-2024, 10:12 PM:
Please post all code, output and errors (in its entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
The example code does not have a loop so it does not show the problem you are having doubts about.
Reply
#3
global is not applicable here.

I think your pattern is fine. Sometimes I do this when I need to initialize a variable to one of two values based on a condition.
a = b if condition else c
If you want to know how to make sure a variable is assigned when you assign in a loop, provide an example that uses a loop.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable being erased inside of if statement deusablutum 5 129 Yesterday, 11:50 PM
Last Post: Skaperen
  How to create a variable only for use inside the scope of a while loop? Radical 10 2,195 Nov-07-2023, 09:49 AM
Last Post: buran
  Help adding a loop inside a loop Extra 31 5,166 Oct-23-2022, 12:16 AM
Last Post: Extra
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,755 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  loop (create variable where name is dependent on another variable) brianhclo 1 1,214 Aug-05-2022, 07:46 AM
Last Post: bowlofred
  Passing parameters with arrays and array definitions michael_lwt 1 1,016 Jul-07-2022, 09:45 PM
Last Post: Larz60+
  Multiple Loop Statements in a Variable Dexty 1 1,276 May-23-2022, 08:53 AM
Last Post: bowlofred
  Cursor Variable inside Another Cursor . CX_ORacle paulo79 1 1,615 Apr-09-2022, 10:24 AM
Last Post: ibreeden
Big Grin Variable flag vs code outside of for loop?(Disregard) cubangt 2 1,271 Mar-16-2022, 08:54 PM
Last Post: cubangt
  How to save specific variable in for loop in to the database? ilknurg 1 1,231 Mar-09-2022, 10:32 PM
Last Post: cubangt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020