gpt4 book ai didi

python - 在函数中使用用户输入以及带有用户输入的字典

转载 作者:行者123 更新时间:2023-12-01 02:33:02 25 4
gpt4 key购买 nike

def make_movie(movie_name = input("What is your favorite movie? "),studio = input("What studio is it under? "), running_time = + input("Do you know the running time? If not just type in 'no'")):
if running_time == 'no':
movie = {'movie name': movie_name, 'studio': studio, 'running time': running_time}
print(movie)
else:
movie = {'movie name': movie_name, 'studio': studio}
print(movie)
return movie
make_movie()

我的老师给了我们这个问题:

  1. Movie: Write a function called make_movie() that builds a dictionary describing a movie. The function should take in a movie name and the studio making the movie, and it should return a dictionary containing these two pieces of information. Use the function to make three dictionaries representing different movies. Print each return value to show that the dictionaries are storing the movie information correctly.

a. Add an optional parameter to make_movie() that allows you to store the running time of the movie. If the calling line includes a value for the running time of the movie, add that value to the movie’s dictionary. Make at least one new function call that includes the running time of a movie.

我被可选参数困住了。如果人们不知道电影的运行时间,那么我根本不希望字典显示它。我这样做是为了让该函数要求用户输入每个变量,但是当它要求运行时时,即使我输入“否”,它仍然会在字典中显示运行时。

所以我的问题是,我可以对我的代码进行任何更改以使其正常工作吗?

最佳答案

哦,最大的问题是陷入了 Python 中最常见的“陷阱”之一。作为函数头的一部分编写的代码(包括可选参数的默认值)仅被调用一次,并且在函数定义时运行,而不是在函数运行时运行。当您在那里创建可变对象并在函数内对其进行变异时,这通常是一个问题,但在这里也会产生问题。想象一下:

def echo(a=input("Enter a thing: ")):
return a

def main():
print("We're going to ask you to enter a thing now,")
resp = echo()
print(a)

if __name__ == "__main__":
main()

您希望从控制台看到:

We're going to ask you to enter a thing now,
Enter a thing: foobar
foobar

但你实际得到的是:

Enter a thing: foobar
We're going to ask you to enter a thing now,
foobar

这是因为当您 define echo 时,会调用 input("Enter a thing: ") 行,而不是当你实际调用它时。正确实现这一点的标准更改是:

def echo(a=None):
if a is None:
a = input("Enter a thing: ")
return a
<小时/>

除此之外,我强烈建议您不要,正如您提到的目标一样,尝试从结果字典中删除电影的运行时间。像这样的函数的结果应该是标准的,如果我正在编写需要这些电影词典之一的代码,我永远不必担心编写 incoming_dict['running time'] 可能会抛出 KeyError。

当我们这样做时——为什么函数会提示用户输入?在调用函数中执行此操作。

def make_movie(name, studio, runningtime=0):
return {'name': name, 'studio': studio, 'runningtime':runningtime}

def main():
name = input("Movie name: ")
studio = input("Studio: ")
rtime = input("Running time: ")
if not rtime:
rtime = 0
movie = make_movie(name, studio, rtime)

关于python - 在函数中使用用户输入以及带有用户输入的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46573071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com