首页 > 解决方案 > 如何在 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 语句的格式不正确。谢谢你的帮助!

标签: pythonif-statement

解决方案


您的问题可能是打印语句的格式。下面的代码有效。

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?")

推荐阅读