gpt4 book ai didi

python - 从特定点重新运行代码

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:40 26 4
gpt4 key购买 nike

我不知道如何重新运行我的某段代码:

print('Welcome to your currency converter\n Please choose your starting currency from the four options:')
currency1=input('(GDP) = Pound Sterling £ \n(EUR) = Euro € \n(USD) = US Dollar ($) \n(JPY)= Japanese Yen ¥\n').lower()
if currency1!='gdp' or 'eur' or 'usd' or 'jpy':
print('Sorry not accepted try again')

当代码打印Sorry not accepted try again 我想重新开始代码。我该怎么做呢?

最佳答案

官方常见问题解答涵盖了三个选项,尽管您可能永远找不到它,因为它在问题 Why can't I use an assignment in an expression 下:


首先,有 while True:

print('Welcome to your currency converter\n Please choose your starting currency from the four options:')
while True:
currency1=input('(GDP) = Pound Sterling £ \n(EUR) = Euro € \n(USD) = US Dollar ($) \n(JPY)= Japanese Yen ¥\n').lower()
if currency1 not in ['gdp','eur','usd','jpy']:
print('Sorry not accepted try again')
else:
break

这对于顽固的 C 程序员来说可能看起来很奇怪,他们被教导 break (如早期 return 和类似功能)不好。但是 Python 不是 C。(更不用说现在,甚至 MISRA 都建议在新的 C99 代码中使用 break……)您可以避免 break通过使用 while not done:和设置 done = True而不是 break ,但这没有任何好处,只会让您的代码更长更复杂。


接下来是while <condition>:

print('Welcome to your currency converter\n Please choose your starting currency from the four options:')
currency1 = input('(GDP) = Pound Sterling £ \n(EUR) = Euro € \n(USD) = US Dollar ($) \n(JPY)= Japanese Yen ¥\n').lower()

while currency1 not in ['gdp', 'eur', 'usd', 'jpy']:
print('Sorry not accepted try again')
currency1 = input('(GDP) = Pound Sterling £ \n(EUR) = Euro € \n(USD) = US Dollar ($) \n(JPY)= Japanese Yen ¥\n').lower()

正如常见问题解答所说,这“看起来很有吸引力,但通常不太稳健”:

The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into sys.stdin.readline()) you have to remember to change two places in your program – the second occurrence is hidden at the bottom of the loop.


最后,正如常见问题解答所说,“最好的方法是使用迭代器,这样就可以使用 for 语句遍历对象”。

如果您已经有了一个迭代器,或者可以简单地构建一个迭代器,那就太好了。但是如果你不这样做,它可能会增加比你节省的更多的复杂性。我认为这里就是这种情况。例如,这并不比其他选项简单:

def get_currency():
currency1=input('(GDP) = Pound Sterling £ \n(EUR) = Euro € \n(USD) = US Dollar ($) \n(JPY)= Japanese Yen ¥\n').lower()
if currency1 in ['gdp','eur','usd','jpy']:
return currency
else:
print('Sorry not accepted try again')
for currency1 in iter(get_currency, None):
do_stuff(currency1)

关于python - 从特定点重新运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124976/

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