-3

Python Version=3.5

  1. So I would like to know how I can set variables based on the input from the user. For example if a user was to answer 7 to this:

    residents=input("How many people live at your house?")

EDIT= if they entered 7- how could I ask for the name of each individual??

Thanks!

  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – tripleee Jan 09 '16 at 18:43

1 Answers1

1
def get_int(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:   # not an int!
            pass   # try again

residents = get_int("How many people live at your house? ")

Edit: rather than having named variables for each person, you can use a list:

resident_names = [input("Name of resident {}: ".format(i)) for i in range(1, residents + 1)]
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • If they were to enter 3- how would i do it so that it looks like this Resident1Name=(...) Resident2Name=(...) Resident3NAme=(...) They should be able to enter new info for each of the amount of people under the house name..?- basically, inputting a name for each registered person – TheHolyTurnip Jan 09 '16 at 18:20
  • @OmarMiah, if you want an answer, this should be a separate question, or you should at least add it to your current question. – sleblanc Jan 09 '16 at 18:48
  • Thanks for the tip! added it as an edit to my original question! – TheHolyTurnip Jan 09 '16 at 18:50
  • @Hugh Bothwell - how would I structure this piece of code then based on what you said. – TheHolyTurnip Jan 09 '16 at 19:27
  • @OmarMiah: exactly as I show above (it's functional code, you know!) – Hugh Bothwell Jan 09 '16 at 19:30
  • @HughBothwell resident_names = [input("Name of resident {}: ".format(i)) for i in range(1, residents + 1)] can you explain this bit please, I thought a for loop has to be on a new line also, TypeError: Can't convert 'int' object to str implicitly – TheHolyTurnip Jan 09 '16 at 19:33
  • @OmarMiah: ... if it asks for #residents and they reply 7, it will then prompt for "Name of resident 1", "Name of resident 2", etc to "Name of resident 7". The names will be stored in resident_names[0] to resident_names[6]. Hope that helps. – Hugh Bothwell Jan 09 '16 at 19:37