+ 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.

22nd Aug 2018, 6:36 PM
Roger Wang
Roger Wang - avatar
6 Answers
+ 9
Roger Wang In Python3 for char in "abcd": exec(f"{char} = {input()}")
22nd Aug 2018, 8:24 PM
Eduardo Petry
Eduardo Petry - avatar
+ 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.
22nd Aug 2018, 8:55 PM
Eduardo Petry
Eduardo Petry - avatar
+ 8
Roger Wang Yes, that is the standard way to parse space separated input šŸ‘šŸ»ā˜ŗ
22nd Aug 2018, 9:26 PM
Eduardo Petry
Eduardo Petry - avatar
+ 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
22nd Aug 2018, 9:11 PM
Roger Wang
Roger Wang - avatar
+ 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
22nd Aug 2018, 6:40 PM
Roger Wang
Roger Wang - avatar
+ 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
22nd Aug 2018, 8:49 PM
Roger Wang
Roger Wang - avatar