You need to enable JavaScript to run this app. Python入门:如何用if语句实现三个独立输入字符串的字母序排序
优惠活动
大模型
产品
解决方案
定价
更多

Python入门:如何用if语句实现三个独立输入字符串的字母序排序

代码修正方案

拆分三个独立输入提示不会导致排序功能失效。你之前遇到排序失效的问题,本质是存储了word1/word2/word3三个独立变量后,没有补写对应的if比较判断逻辑,没有把这三个变量接入排序流程。

基础调整说明

  • 你原代码中input(str(...))的写法里,str()属于冗余代码:input()方法本身返回的就是字符串类型,删掉外层的str()不影响运行,新手阶段可以先保留原代码这部分不做改动。
  • Python 中字符串可以直接用</>运算符对比字母顺序,比如"apple" < "banana"会返回True,不需要额外转换就能实现字母顺序判断。

完整可运行代码(严格使用if语句实现排序,符合入门作业要求)

word1 = input(str("Please enter a word of your choice:"))
word2 = input(str("please enter another word, but make sure the word does not start with the same letter:"))
word3 = input(str("Awesome! Ok, finally, enter one last word, again making sure not to use the same letter:"))

if (word1 == word2):
    print("The words are the same")
else:
    print("Nicely done, you read directions well!")

print("The words in alphabetical order are..")
# 以下为if实现的排序逻辑
# 逐层判断三个单词的大小关系,按顺序输出
if word1 < word2 and word1 < word3:
    # 最小的单词是word1,比较剩下两个的顺序
    if word2 < word3:
        print(word1, word2, word3)
    else:
        print(word1, word3, word2)
elif word2 < word1 and word2 < word3:
    # 最小的单词是word2,比较剩下两个的顺序
    if word1 < word3:
        print(word2, word1, word3)
    else:
        print(word2, word3, word1)
else:
    # 最小的单词是word3,比较剩下两个的顺序
    if word1 < word2:
        print(word3, word1, word2)
    else:
        print(word3, word2, word1)

额外说明

  • 上述逻辑完全通过if分支实现,没有调用内置的sorted()或列表sort()方法,完全匹配作业要求的“用if语句实现排序”的规则。
  • 目前的字符串比较是区分大小写的,如果希望忽略首字母大小写的影响,可以在比较环节把单词统一转成小写再判断,比如把比较条件改成word1.lower() < word2.lower(),等你熟悉基础逻辑后可以灵活调整。
  • 你之前用单提示输入三个词能正常排序,是因为当时把输入拆分后存到了序列类型的变量里;现在拆分三个独立input存储,只要直接对三个word变量做大小比较,功能和之前是完全一致的,不存在输入拆分导致的功能故障。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 13:45:01