python - Python:根据 IF 语句输出,在自身之外执行不同的代码
问题描述
如果 my_input == "n" 我想让我的程序再次循环,这很好。但是,如果我的 else 语句为 True,我不希望它再次运行整个程序,而只是在 my_input 变量处“开始”。
我怎样才能做到这一点?
def name_user_validation():
while True:
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split()
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
my_input = input("Is that right? (y/n) ")
if (my_input == "y"):
print("Great!")
break
elif my_input == "n":
print("Oh no :(")
else:
print("Invalid input, try again.")
name_user_validation()
解决方案
我误解了您的问题,我可能会稍微重构您的代码,因此您可以摆脱 while 循环并在需要时使用递归函数调用返回,
类似于下面的东西
def name_user_validation():
full_name = input("What is your name? ")
print(f"Hello {full_name}, nice to meet you.")
full_name.split() # This line actually doesn't do anything
print(f"If I understood correctly, your first name is {full_name[0]} and your last name is {full_name[-1]}.")
if not accept_input():
name_user_validation()
def accept_input():
my_input = input("Is that right? (y/n) ")
if my_input == "y":
print("Great!")
return True
elif my_input == "n":
print("Oh no :(")
return False
else:
print("Invalid input, try again.")
accept_input()
name_user_validation()
推荐阅读
- python - 在 PyPI 上上传 scipt 以获取 CLI 程序
- r - 执行 ShinyFileChoose 处理时如何停止处理直到选择文件
- javascript - 如何更改变量的范围
- c# - 使用信号器实现流
- nginx - 具有域映射的多租户应用程序的 NGINX 配置
- .net-core - 如何在运行时获取 dotnet 核心应用程序的当前进程 ID?
- javascript - 如何仅在“一个单元格”的谷歌表格中显示我的实时传感器数据?
- python - matplotlib 的 Historgram 函数返回奇怪的 y 轴值
- javascript - 如何在涉及数组或其他类型的嵌入或嵌套文档的 mongodb 更新操作中使用变量?
- elasticsearch - 如何在 beats.yml 配置文件中为 Elasticsearch 提供多节点输出?