Python 使用for循环输入提示

Python input prompt using for loop

我已经创建了一个脚本,它使用用户输入来打招呼,但它在一个句子中打印的是字母而不是完整的名字。怎么样?

val = input()

for i in val:
    print("Hello", i)

但这会打印 你好 你好 你好我 你好 你好ç 你好e

函数input()接受来自命令行的输入。例如,如果您在命令行中输入 prince,那么现在变量 val 的值为 "prince".

对于 for 循环,您使用的是 for-each 表示法。字符串也是一种迭代器——实际上,字符串只是字符数组。把它想象成一个常规列表,但不是像 [1, 2, 3, 4] 这样的列表,而是 ['p', 'r', 'i', 'n', 'c', 'e'] 这样的列表。因此 for 循环的每次迭代只打印当前正在迭代的字符。

您可以通过避免 for 循环并仅使用代码 print("Hello", val).

来简化您的代码

不过,如果你只想练习for循环,你可以使用下面的代码。尝试了解如何以及为什么可以简化它!

val = input()            //stores the user input into val
name = ""                //creates an empty string called name

for s in val:            //iterates through each character in val
    name += s            //adds that character to name
                         //when the for loop ends, the user input is stored in name
print("Hello", name)     //prints "Hello" and the name