Home > database >  How can I iterate through two User Inputs and put them in a new variable with Python?
How can I iterate through two User Inputs and put them in a new variable with Python?

Time:07-17

I need users to give two inputs:

name = input("for storing name") 
bDate = input("for storing birth dates")

I want these two user inputs in a new variable in such a way that the first item from both the inputs get to merge together like this:

name = ["Matt", "Jack", "Rosie"]
bDate = ["Jun 5", "Aug 16", "Dec 3"]

newVariable = ["Matt: June 5", "Jack: Aug 16", "Rosie: Dec 3"]

CodePudding user response:

So you want to format the strings in the input lists into a new list of formatted strings. The built-in zip function takes any "iterable", such as a list, and emits the cross section of the inputs. Combined with a "list comprehension", this can be done in one line.

(note, using the more common style guide names.)

names = ["Matt", "Jack", "Rosie"]  # note variable names are plural
birthdays = ["Jun 5", "Aug 16", "Dec 3"]

name_birthday = [f"{name}: {bday}" for (name, bday) in zip(names, birthdays)]

print(name_birthday)

this will print:

['Matt: Jun 5', 'Jack: Aug 16', 'Rosie: Dec 3']

CodePudding user response:

You want to build a dictionary rather than a list. You can accomplish this with a dictionary comprehension.

name = ["Matt", "Jack", "Rosie"]
bDate = ["Jun 5", "Aug 16", "Dec 3"]

new_dict = {key: value for key, value in zip(name, bDate)}

CodePudding user response:

I gather from your question that you want to store name and bDate input variables in new variables.

name = input("for storing name")
nameTemp = name
bDate = input("for storing birth dates")
bDateTemp = bDate

This will ensure that the input variables will never alter and for further queries, you can make use of the nameTemp and bDateTemp variables.

  • Related