Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling on a variable using two concatenated strings Python

Sorry for the lack of detail as I am a beginner in python:

c1 = c2 = c3 = c4 = c5 = False

x = int(input("Enter a number 1-5: "))  

if x > 5 or x < 1:
  print("Your number must be between 1 and 5")
else:
  "c", x = True

Line 8 is where you would concatenate the 2 strings.

I’m not sure if I’m being clear enough or whether this is even possible in Python but it would be amazing if someone more experienced could respond.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve looked gone through pages of questions and still haven’t found anything related to what I’m trying to do. Same with Youtube.

>Solution :

Use a list instead of a pile of variables:

c = [False] * 5

x = int(input("Enter a number 1-5: "))  

if x > 5 or x < 1:
  print("Your number must be between 1 and 5")
else:
  c[x-1] = True

Also you should be aware that string literals (e.g. "c") don’t mix well with variable names. If you want to use a string as a way to identify a variable use a dict.

Added to address the issue of scaling. A defaultdict can be useful as an analog to a sparse array.

from collections import defaultdict

c = defaultdict(lambda: False)
x = int(input("Enter a number 1-500000: "))  

if x > 500000 or x < 1:
  print("Your number must be between 1 and 500000")
else:
  c[x] = True
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading