You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复用星号打印数字最后两位的Python代码问题

代码修正方案

存在的问题

  • 变量定义顺序错误,未输入就调用words变量会触发命名错误,且最后两位数字没有随每次输入更新
  • 两个数字的星型图案拼接逻辑错误,原有写法会让两个数字垂直排列,不符合常规阅读习惯
  • 缺少输入合法性校验,未验证输入是否为8位、是否仅包含1~4的数字
  • 退出判断分支顺序错误,输入QUIT时会先触发非法输入提示才退出
  • 打印参数错误,使用end='\r'会导致多行图案被覆盖无法正常显示

修正后完整代码

### 数字1的星型图案 ###
def one():
    x_str = ""
    for row in range(0,6):
        for col in range(0,6):
            if (col==3 and row>0) or (row==2 and col==2):
                x_str += "*"
            else:
                x_str += " "
        x_str += "\n"
    return x_str

### 数字2的星型图案 ###
def two():
    x_str = ""
    for row in range(0,6):
        for col in range(0,6):
            if (col==4 and 1<row<3) or (col==2 and 3<row<5) or (row in (1,3,5) and 1<col<5):
                x_str += "*"
            else:
                x_str += " "
        x_str += "\n"
    return x_str

### 数字3的星型图案 ###
def three():
    x_str = ""
    for row in range(0,6):
        for col in range(0,6):
            if (col==4 and (1<row<3 or 3<row<5)) or (row in (1,3,5) and 1<col<5):
                x_str += "*"
            else:
                x_str += " "
        x_str += "\n"
    return x_str

### 数字4的星型图案 ###
def four():
    x_str = ""
    for row in range(0,6):
        for col in range(0,6):
            if (col==4 and row>0) or (col==2 and 0<row<4) or (col==3 and row==3):
                x_str += "*"
            else:
                x_str += " "
        x_str += "\n"
    return x_str

### 主逻辑 ###
shapes = {'1': one(), '2': two(), '3': three(), '4': four()}
while True:
    words = input("请输入由1~4组成的8位数字,输入QUIT退出:")
    # 先判断退出
    if words == "QUIT":
        break
    # 合法性校验
    if len(words) != 8 or not all(c in shapes for c in words):
        print("错误:输入不合法,请重新输入")
        continue
    # 取最后两位
    last_two = words[-2:]
    # 拆分两个数字的图案为逐行列表,方便横向拼接
    num1_lines = shapes[last_two[0]].splitlines()
    num2_lines = shapes[last_two[1]].splitlines()
    # 逐行拼接两个数字
    output = ""
    for i in range(6):
        output += num1_lines[i] + "  " + num2_lines[i] + "\n"
    # 打印结果
    print(f"您输入的数字是{words},最后两位数字的星型图案如下:")
    print(output)

功能说明

运行后输入符合要求的8位数字即可输出最后两位的横向并排星型图案,输入QUIT可直接退出程序。

内容的提问来源于stack exchange,提问作者Rum Dou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:24:03