Home > Software design >  taking an input from a user, adding elements of the string together
taking an input from a user, adding elements of the string together

Time:11-05

so I take a user input in a loop seen below

mail_list = []
x = 0
while x >= 0:
    user_input = input('enter first name, last name, ID, and email domain: ')
    mail_list.append(user_input)
    if user_input == 'done':
        break

so it is supposed to add the first name, last name, and email domain together to make a full email address. not sure if lists are the best path to go or splicing the spring. The problem I ran into when trying to just splice it would only use 'done' as the last input so I assumed adding it to a list would be the best path. just lost

CodePudding user response:

Are you expecting something like email = first_name '.' last_name '@gmail.' domain

I'll suppose this comment by Gautam Chettiar is right.


At this point you have mail_list which contains all the parts of the email address, you can join this manually.

email = mail_list[0]   '.'   mail_list[1]   '@gmail.'   mail_list[2]

This is not an elegant solution, but if you really don't want to create more variables or (even better) to input all the address at once, I think this is the only way.

CodePudding user response:

IIUC, you might want something like:

mail_list = []
while True: # use an infinite loop
    user_input = input('enter first name, last name, ID, and email domain: ')

    # check if we're done before doing anything else
    if user_input == 'done':
        break

    # try to split the string into 4 chunks
    try:
        first, last, ID, domain = map(str.strip, user_input.split(','))
    except ValueError:
        print('Invalid format, please try again')
        continue

    # do something with the input
    # here creating a first.last@domain string
    mail_list.append(f'{first}.{last}@{domain}')
print(mail_list)

Example:

enter first name, last name, ID, and email domain: first, last, ABC, example.org
enter first name, last name, ID, and email domain: first2, last2, DEF
Invalid format, please try again
enter first name, last name, ID, and email domain: first2, last2, DEF, example.org
enter first name, last name, ID, and email domain: done
['[email protected]', '[email protected]']
  • Related