How to avoid repeating code?

1

I have a script in Python 3 that tries to be a chatbot, where it has several if and elses that are used based on what the user responds to.

The problem is that in all functions, type get_name () or get_age () , these if and else are repeated.

def get_name():
while True:
    global name
    name = question_renderer("What's your name?")
    name = name.lower().capitalize()
    if name == '':
        continue
    elif name.isdigit():
        typing(1)
        print("Please don't type numbers.")
    else:
        list = ["I like your name.", "I always wanted to have that name.", "My friend has the same name."]
        typing(1)
        print(choice(list))
        break

def get_age():
while True:
    try:
        age = int(question_renderer("How old are you, {}?".format(name)))
    except ValueError:
        typing(1)
        print("Please, just type numbers.")
    else:
        if int(age) <= 25:
            typing(2)
            list = ["You're still young.", "Being young is very good.", "Enjoy your youth."]
            print(choice(list))
        elif int(age) > 25:
            typing(1)
            list = ["You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends."]
            print(choice(list))
        break

How do I not do this across the code?

    
asked by anonymous 30.09.2017 / 23:00

1 answer

1

I do not see a better way to get your code to remove these if , however I snapped your code and took unnecessary things.

1 - I took it to continue, it is not necessary.

2 - You created two lists of sentences, the list type is the slowest type of Data Structure, and it was unnecessary for Choice, so I created 2 Sets and I applied them within Choice.

from random import choice

def get_name():
    while True:
        global name
        name = input("What's your name?")
        name = name.lower().capitalize()
        if name != '':
            if name.isdigit():
                print("Please don't type numbers.")
            else:
                print(choice(("I like your name.", "I always wanted to have that name.", "My friend has the same name.")))
                break

def get_age():
    while True:
        try:        
            age = int(input("How old are you, "+name+"?"))
        except ValueError:
            print("Please, just type numbers.")
        else:
            if int(age) <= 25:
                print(choice(("You're still young.", "Being young is very good.", "Enjoy your youth.")))
            elif int(age) > 25:
                print(choice(("You're getting old already.", "I hope you have enjoyed your teenage years.", "More bills to pay than friends.")))
            break
    
01.10.2017 / 01:02