Хотите выбрать случайный элемент из списка и повторно использовать элемент в другой функции - PullRequest
0 голосов
/ 24 марта 2020

мой код довольно грязный, поскольку я новичок, но я не могу понять это!

Между прочим, я включил только соответствующие фрагменты моего кода.

Практически все, что я хочу сделать, это сказать одно и то же местоположение дважды для random_place1 и затем новое местоположение для random_place2. В настоящее время он просто дает мне три отдельных местоположения, потому что я просто призываю random_place1 переназначить.

def random_place1():

    import random

    locations = ["Paris" , "New York", "San Francisco" , "Tokyo", "Istanbul", "São Paulo", "Xi'an", "Bogotá", "Casablanca", "Rabat"]


    first_place = random.choice(locations)

    return (first_place)

def random_place2():

    import random

    locations = ["London" , "Miami" , "Chicago", "Cairo", "Vienna" , "Manila", "Munich", "Delhi"]


    second_place = random.choice(locations)
    return(second_place)

def main():

    answer = input("Type Yes to continue or No to exit: ")
    if answer == "yes":
        print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
        restart2()
    elif answer == "y" :
        print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
        restart2()
    elif answer == "Yes":
        print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
        restart2()
    elif answer == "YES":
        print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
        restart2()
    elif answer == "Y":
        print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
        restart2()

    elif answer == "no":
        print("\nThanks for trying out the Madlibs Generator!")
    elif answer == "n":
        print("\nThanks for trying out the Madlibs Generator!")
    elif answer == "No":
        print("\nThanks for trying out the Madlibs Generator!")
    elif answer == "NO":
        print("\nThanks for trying out the Madlibs Generator!")
    elif answer == "N":
        print("\nThanks for trying out the Madlibs Generator!")
    else:
        print("\nInvalid response please try again!")
        restart()

1 Ответ

0 голосов
/ 24 марта 2020

Вы можете вызывать методы произвольного места и сохранять возвращаемое значение в переменной, чтобы использовать это значение позже. Один из принципов кодирования, который вам может понадобиться, называется «DRY» (не повторяйте себя). Если вы видите, что сами пишете много одного и того же кода, скорее всего, вы можете выбрать лучший подход.

Итак, ниже приведено лишь краткое обновление вашего кода, чтобы сделать его чище. Вы не могли бы позаботиться о забавном c random_place, так как вместо вызова его из main мы могли бы просто вызвать random.choice. Однако я включил его, чтобы показать вам, что вам не нужно писать random_place дважды. Вы можете написать его один раз и указать место для выбора.

Также вы можете взять ввод и сделать его строчным. тогда вам нужно проверять только такие вещи, как «да» или «у», которые вам не нужно проверять для всех версий с учетом регистра. Таким образом, вы только напишите строку печати один раз.

import random

locations1 = ["Paris", "New York", "San Francisco", "Tokyo", "Istanbul", "São Paulo", "Xi'an", "Bogotá", "Casablanca",
              "Rabat"]
locations2 = ["London", "Miami", "Chicago", "Cairo", "Vienna", "Manila", "Munich", "Delhi"]

def random_place(locations):
    return random.choice(locations)

def main():
    while True:
        answer = input("Type Yes to continue or No to exit: ").lower()
        if answer == "yes" or answer == "y":
            location1 = random_place(locations1)
            location2 = random_place(locations2)
            print(f"Last year i went to {location1}. This year i was going to go again to {location1}.",
                  f"However my friends suggested to go to {location2} as the people in {location2} are nicer")

        elif answer == "no" or answer == "n":
            print("\nThanks for trying out the Madlibs Generator!")
            break

        else:
            print("\nThats not a valid input")


main()

ВЫХОД

Type Yes to continue or No to exit: yes
Last year i went to São Paulo. This year i was going to go again to São Paulo. However my friends suggested to go to Manila as the people in Manila are nicer
Type Yes to continue or No to exit: nodf

Thats not a valid input
Type Yes to continue or No to exit: no

Thanks for trying out the Madlibs Generator!
...