Getting input · 获取输入
Ask the user with input
input()waits for the user to type a line and press Enter.- It gives back what they typed. Store it in a variable.
- Join two strings together with
+.
用 input 向用户提问
input()会等待用户输入一行文字并按回车。- 它会把用户输入的内容返回。把它存进一个变量。
- 用
+把两个字符串连接起来。
name = input()
print("Welcome, " + name)
When your program waits
- When you press Run, the program stops at
input()and waits for you. - A highlighted box appears under the code: type here, then press Enter.
- Click the box, type your answer and press Enter. Then the program continues.
程序在等你
- 按下运行后,程序会停在
input()这里,等你输入。 - 代码下面会出现一个高亮的方框:在这里输入,然后按回车。
- 点一下方框,输入你的回答,再按回车键,程序就会继续运行。
input always gives a string
- Whatever the user types comes back as a string.
- Even if they type
5, you get the text"5", not the number. - So
"5" + "5"is"55"(joined text), not10.
input 永远返回字符串
- 不管用户输入什么,返回的都是字符串。
- 即使他们输入
5,你得到的也是文字"5",而不是数字。 - 所以
"5" + "5"是"55"(把文字拼起来),而不是10。
print("5" + "5") # 55 — joined text, not the number 10
Turn text into a number
int(...)turns text into a whole number:int("5")→5.float(...)turns text into a decimal:float("2.5")→2.5.- Convert first, then you can do maths.
把文字变成数字
int(...)把文字变成整数:int("5")→5。float(...)把文字变成小数:float("2.5")→2.5。- 先转换,然后才能做数学运算。
age = int(input())
print(age + 1)
Common mistakes
input()always returns a string, so wrap it inint(...)before doing maths.- The text inside
input("...")is the prompt shown to the user.
常见错误
input()总是返回字符串,做数学运算前要用int(...)包起来。input("...")里的文本是显示给用户的提示。
Now you try
- When you Run, type the input yourself in the box and press Enter.
- Check answer types the task's input for you, so just read it with
input(). - Each task needs only one
input().
现在轮到你
- 按运行时,要自己在方框里输入,再按回车键。
- 按检查答案时,检查会替你输入题目给的数据,所以你只要用
input()读取就好。 - 每个任务只需要一次
input()。
Input → process → output · 输入 → 处理 → 输出
Most programs follow one shape: get input, do something, show output. · 大多数程序都是一个模式:取得输入、做处理、显示输出。
Read a name with input(), then print Hi, then the name then !. For the input Sam, the output should be Hi, Sam!. · 用 input() 读取一个名字,然后输出 Hi, 、名字,再加 !。当输入为 Sam 时,应输出 Hi, Sam!。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read a whole number with input(), convert it with int(...), then print the number plus 100. For input 7, the output should be 107. · 用 input() 读取一个整数,用 int(...) 转换,然后打印这个数加 100 的结果。当输入为 7 时,应输出 107。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read a whole number, convert it with int(...), then print its square (the number times itself). For input 5, the output should be 25. · 读取一个整数,用 int(...) 转换,然后打印它的平方(自己乘自己)。当输入为 5 时,应输出 25。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read the width, then the height, each with int(input()). Print the area on one line and the perimeter on the next. For the inputs 3 and 5 the output is Area: 15 and Perimeter: 16. · 用 int(input()) 先读取宽,再读取高。第一行打印面积,第二行打印周长。输入 3 和 5 时,输出是 Area: 15 和 Perimeter: 16。
Click Run to see the output here. · 点击“运行”查看此处输出。