ling830 发表于 2026-7-24 16:57:24

该挑战开始了!

写一个程序,给定一个字符串 sentence,打印一个修改后的版本, 其中第一个字母大写,其余字母小写。 例如,无论输入 sentence = 'hello world' 还是 'HELLO WORLD',输出都应该是 Hello world。

FishC 发表于 2026-7-24 16:57:29

ling830 发表于 2026-07-24 16:57
该挑战开始了!

写一个程序,给定一个字符串 sente ...

给你一个直接可用的程序,它会将字符串的第一个字母转为大写,其余字母全部转为小写。即使输入 `'HELLO WORLD'` 也能正确输出 `'Hello world'`。


sentence = 'hello world'
first = sentence.upper()
rest = sentence.lower()
new_sentence = first + rest
print(new_sentence)


运行结果:

Hello world


原理:`sentence` 取第一个字符,`.upper()` 转为大写;`sentence` 取从第二个字符开始到末尾的子串,`.lower()` 转为小写。最后用 `+` 拼接即可。注意如果字符串为空,访问 `sentence` 会报错,但题目未涉及空字符串,暂不考虑。

——FishC计算机教育专家

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

ling830 发表于 2026-7-24 16:58:09

FishC 发表于 2026-7-24 16:55
修复方案:添加 `else` 分支,使 `excited` 为 `False` 时,`char` 赋值为句号。这样变量 `char` 在所 ...

sentence = 'Hello World'
excited = False
if excited:
    char = '!'
else:
      char = '.'
sentence += char
print(sentence)

FishC 发表于 2026-7-24 16:58:13

ling830 发表于 2026-07-24 16:58
FishC 发表于 2026-7-24 16:55
修复方案:添加 `else ...

你贴出的代码中 `else` 下面的 `char = '.'` 多缩进了4个空格(变成8个)。Python要求 `else` 分支的代码与 `if` 分支的代码**缩进级别相同**(通常都是4个空格)。当前写法会导致 `IndentationError`。

**正确写法**(保持统一的4空格缩进):

    sentence = 'Hello World'
    excited = False
    if excited:
      char = '!'
    else:
      char = '.'
    sentence += char
    print(sentence)

运行后输出 `Hello World.`。注意 `else` 与 `if` 对齐,内部代码块再缩进4个空格。

——FishC计算机教育专家

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

ling830 发表于 2026-7-24 16:59:43

FishC 发表于 2026-7-24 16:58
你贴出的代码中 `else` 下面的 `char = '.'` 多缩进了4个空格(变成8个)。Python要求 `else` 分支的代 ...

sentence = 'HELLO WORLD'
first = sentence.upper()
rest = sentence.lower()
new_sentence = first + rest
print(new_sentence)

FishC 发表于 2026-7-24 16:59:51

ling830 发表于 2026-07-24 16:59
FishC 发表于 2026-7-24 16:58
你贴出的代码中 `else ...

你的代码中 `first = sentence.upper()` 会把整个字符串都转成大写,而不是第一个字母。同理 `rest = sentence.lower()` 是整个字符串小写,结果会变成 `HELLO WORLDhello world`,不符合要求。

正确的做法是:用索引取第一个字符 `sentence` 转大写,取剩余部分 `sentence` 转小写,然后拼接。

修正后的程序:


sentence = 'HELLO WORLD'
first_char = sentence.upper()
rest = sentence.lower()
new_sentence = first_char + rest
print(new_sentence)


输出:`Hello world`

注意:如果字符串为空(本题未涉及),访问 `sentence` 会报错,但题目没有要求处理空字符串。

——FishC计算机教育专家

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

ling830 发表于 2026-7-24 17:00:17

太棒了!!!

再来一个练习,然后你就可以放松了。

写一个程序,以嘲讽的方式打印 sentence,例如:
OnE MoRe eXeRcIsE, aNd tHeN YoU CaN ReLaX.

每隔一个字符应该是小写,其余的应该是大写。

FishC 发表于 2026-7-24 17:00:27

ling830 发表于 2026-07-24 17:00
太棒了!!!

再来一个练习,然后你就可以放松了。 ...

完成!下面是实现嘲讽格式输出的程序。它遍历字符串的每个字符,根据索引的奇偶性分别转为大写或小写,非字母字符保持不变。


sentence = input("请输入句子: ")
result = ""
for i, char in enumerate(sentence):
    if i % 2 == 0:
      result += char.upper()
    else:
      result += char.lower()
print(result)


例如输入 `One more exercise, and then you can relax.` 输出即为 `OnE MoRe eXeRcIsE, aNd tHeN YoU CaN ReLaX.`

——FishC计算机教育专家

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: 1 [2]
查看完整版本: 介绍 if 语句