简体   繁体   中英

Creating a list of tuples from a function

I am fairly new to python but already i am a very big fan of the language, i am currently working with some tutorials as well as doing a lot of reading and trying to apply what i read.

Been using this site for a while but this my first time posting

I am working on a problem that requires me to modify a function so that a list of tuples are returned. I have tried everything that i know and i am not having any success, this is as far as i have got.

this is my function:

def ask_age ():
    newList=[]
    count = int (input( "Enter Count "))
    if count >7:
            count=7
    for n in range (count):  
            age = int(input( "Please Enter age = " ))
            if age > 0:
                    newList.append(age)
            print ("You are", age, "years old")
            if age < 16:
                    print ("This is a child")
            elif age >= 18:
                    print ("This is an Adult")
            else: 
                    print ("This is a youth")
    print(newList)

when I run:

ask_age()

and this is the result

Enter Count 4

Please Enter age = 15

You are 15 years old This is a child

Please Enter age = 17

You are 17 years old This is a youth

Please Enter age = 18

You are 18 years old This is an Adult

Please Enter age = 25

You are 25 years old This is an Adult

[15, 17, 18, 25]

As I mentioned, I now need to modify the function so that instead a list of tuples is returned that looks like so:

[(15, 'This is a child'), (17, 'This is a youth'), (18, 'This is an Adult'), (25, 'This is an Adult')]

Any help would be greatly appreciated

change the part that's now

if age > 0:
    newList.append(age)
    print ("You are", age, "years old")
    if age < 16:
        print ("This is a child")
    elif age >= 18:
        print ("This is an Adult")
    else: 
        print ("This is a youth")

to be instead:

if age > 0:
    if age < 16:
        newList.append((age, "This is a child"))
    elif age >= 18:
        newList.append((age, "This is an Adult"))
    else: 
        newList.append((age, "This is a youth"))

and the print(newList) at the end to be return newList instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM