python - 如何在 python 中正确格式化 if/else 缩进?
问题描述
我正在做一个关于决策语句的基本编程问题。每当输入每个选项时,代码都应与具有不同选项的三种鱼相关。我认为我的大部分代码都可以正常运行,除了我不确定如何格式化最终的、包含所有不正确输入的所有其他代码。
我当前的代码运行良好,但底部的 else 语句被附加到我在解决方案的第一个输入之外给出的每个响应中。
if fish_type == "carnivorous":
fish_size = str(input("Do you have smaller fish already? "))
if fish_size == "yes":
print("This is a bad idea! It'll eat the little ones!")
if fish_size == "no":
print("Great! Enjoy!")
if fish_type == "salt water":
print("Wow, you're a fancy fish parent!")
if fish_type == "community":
fish_number = int(input("How many fish of this species do you already have?\
"))
if fish_number < 3:
print("You should get more than one fish!")
else:
print("Yay, more friends!")
else:
print("I don't think that's a type of fish; maybe you're looking for a \
lizard?")
例如,如果我输入“carnivorous”,我会被正确地路由到 carnivorous if 语句,但是当我回答“yes”或“no”时,我的 else 语句的格式不正确。谢谢你的帮助!
解决方案
您的问题可能是打印语句的格式。下面的代码有效。
fish_type = 'not_a_fish'
if fish_type == "carnivorous":
fish_size = str(input("Do you have smaller fish already? "))
if fish_size == "yes":
print("This is a bad idea! It'll eat the little ones!")
elif fish_size == "no":
print("Great! Enjoy!")
elif fish_type == "salt water":
print("Wow, you're a fancy fish parent!")
elif fish_type == "community":
fish_number = int(input("How many fish of this species do you already have?\n"))
if fish_number < 3:
print("You should get more than one fish!")
else:
print("Yay, more friends!")
else:
print("I don't think that's a type of fish; maybe you're looking for a \n lizard?")
推荐阅读
- swift - AVURLAsset 返回空数组-尝试连接两个文件
- javascript - 如何将输入范围值从 1.9 更改为 2.0?
- angular - 如果通过 | 注入,Angular 9(或 2+)不会检测到变化。异步,在父 HTML [Input()] 上,如果它们太快 - 数百毫秒
- postgresql - Postgres 表无故大幅增长
- ios - 如何在场景包中设置雾以跟随曲线?
- python - 合并数组列表
- python - 试图将列表框放在页面中间,滚动条在右边
- c - 发出阅读线并在c中一起打印所有内容
- android-recyclerview - 如何在 RecyclerView 的 CardView 中实现对 Item Click 的操作以显示结果
- r - 为 R 中的位置频率矩阵绘制具有离散 x 轴的序列徽标