+ 7
How to assign multiple inputs to variables? (DRY solution please)
Iām trying to accomplish this using a for loop like this: for char in "abcd": char = input() However this makes it that char is assigned to the inputs (at the end of the loop, it is assigned to the last input) and not the variables a, b, c, and d. I could do this using 4 separate lines of repetitive code, but that would look really WET.
6 Answers
+ 9
Roger Wang In Python3
for char in "abcd":
exec(f"{char} = {input()}")
+ 8
Roger Wang Well, you see, my solution is kind of a hack (in the "quick and dirty but still workable" sense).
The `exec` function executes a string as if it were a line of code. The way I made it, you can initialize a large number of variables, and it just works.
# this would create 26 variables
# and ask for input for each of them
# in just 2 lines of code
for char in "abcdefghijklmnopqrstuvwxyz":
exec(f"{char} = {input()}")
While this works just fine, it isn't very readable at first glance, so you should try not using it in production code.
I didn't really understand your question now, but this is the best I can explain it.
+ 8
Roger Wang Yes, that is the standard way to parse space separated input šš»āŗ
+ 4
Eduardo Petry
I think I have found a great way š:
# Separate inputs with a single space
values = input().split(" ")
a, b, c, d = values
+ 3
Iām also looking for a solution for assigning multiple variables without input as I think there is a much more elegant solution than:
a = b = c = d = 5
or
a, b, c, d = 5, 5, 5, 5
+ 3
Eduardo Petry
Thank you! Do you know of any other codes/functions that do the same?
In your code, char is assigned to the character ādā at the end but thatās an easy fix by writing this at the end:
del char # with or without indent