Variablen benennen Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Variablen benennen Python

Hallo, ich will für ein Projekt in einer while schleife Variablen erstellen. Der Name soll n1, n2, n3, n4 ... sein. Hat irgendwer eine Idee wie man das macht?

14th Jan 2021, 4:33 PM
TJ06
TJ06 - avatar
9 Answers
+ 6
Ja, es gibt einen Weg, dies zu tun. In Python können Sie vars () verwenden, das die Variable all in Ihrem Programm in Form eines Diktats für Ihren Code zurückgibt. i=1 while i<5: vars()['n'+str(i)]="data "+str(i) i+=1 print(n1,n2,n3,n4) (edited)
14th Jan 2021, 4:55 PM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 3
Yeah we are not going to change the value for a variable with this method and no one does that.😅 This method can make our code more compact but I don't think we are going to use it frequently. Similar to vars() function there is a globals() function also with that can create global variables when you are working inside a function because at that time vars() will ony return local variables and you can only create local variables with vars () inside a function
15th Jan 2021, 10:09 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 2
Lisa actually vars is a function that returns a dictionary containing all the local variables in a program/function and their respective values. By making changes in that dictionary we can create new variables ,we can change the value of a specific variable, or deleting a variable (similarly as what you can do with a dictionary). For example purpose see this https://code.sololearn.com/cHK777pLU2YB/?ref=app Tom Jennes Wenn Sie dies auch verstehen möchten, können Sie diese mit einem Übersetzer in Ihre Sprache übersetzen.
15th Jan 2021, 4:52 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 1
Vielen Dank! Sie haben nur i += 1 vergessen :)
14th Jan 2021, 4:56 PM
TJ06
TJ06 - avatar
+ 1
Tom Jennes Herzlich willkommen Oh, Es tut uns leid.😅
15th Jan 2021, 4:26 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 1
Tom Jennes Ähnlich wie bei der Funktion vars () gibt es auch eine Funktion globals (), mit der globale Variablen erstellt werden können, wenn Sie innerhalb einer Funktion arbeiten, da vars () zu diesem Zeitpunkt nur lokale Variablen zurückgibt und Sie können nur lokale Variablen mit vars () innerhalb einer Funktion erstellen
15th Jan 2021, 10:11 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
0
Just out of curiosity: What would be sample application of creating variables at runtime via vars()? I mean, why not use a list or dict?
14th Jan 2021, 9:56 PM
Lisa
Lisa - avatar
0
AKSHAY [less active] Thank you for this explanation! 😊 Can you think of a use case in which you would really want to transform keys/values of this local variables dict as in the example? I am just wondering, because it looks quite "hacky" to me and the so created variables might be difficult to use anywhere in the programm.
15th Jan 2021, 6:32 AM
Lisa
Lisa - avatar
0
AKSHAY [less active] Thanks a lot! 😊
15th Jan 2021, 10:21 AM
Lisa
Lisa - avatar