笔记
【1】输入内容
- 变量名 = input()
print("How old are you?", end=" ")
age = input()
# 输出 How old are you?,然后空一格(end=“ ”,表示末尾不换行 只空1格 继续输出下行代码)
# 接着由用户输出内容如:24 years old;将该str值赋值给变量age
print(f"So,you're {age}.")
# 最后输出带有age的字符串 So,you're {age} old
‘’‘
How old are you? 24 years old
So,you're 24 years old
’‘’
input()进去的值是str类型的。如果要将输入的数进行运算,则需要额外再转化:
- 【将“字符串”格式转为“整数”】 x = int(input()) :其会输入的字符串str中的数字(输入的内容需为 整数数字,否则会报错),然后用int()把其转成整数
- 【将“字符串”格式转为“浮点数”】x = float(input()):其会输入的字符串str中的数字(输入的内容可为 整数数字/浮点数字),然后用float()把其转成浮点数
# 以下介绍了两种环节转格式的方式,私认为第一种比较灵活,需要的时候再转 #【方式1】:在计算时,再将输入的字符串 转为 可计算的数字 x = input() y = input() # 「报错1」:不转化,直接将字符串进行运算 print(x * y) # 报错1 print(int(x * y)) # 报错1 # 若出现“x*y”,则出「报错1」:TypeError: can't multiply sequence by non-int of type 'str' # 因为:input输入的内容为str格式,并不能直接进行运算 # 「报错2」:数字转化出错。若输入的字符串是浮点型数字,则转化为int时会报错 print(int(x) * int(y)) # 其为int整数运算,输入的字符串中的数字也需是整数 # 执行时,若输入x=2.2,y=3,则出「报错2」ValueError: invalid literal for int() with base 10: '2.2' # 执行时,若输入x=2,y=3,则顺利输出 6 print(float(x) * float(y)) # 其为float浮点数运算,则输入的是整数数字,浮点数数字均可。最后会输出浮点数结果 # 执行时,若输入x=1/2,y=3,则出「报错3」ValueError: could not convert string to float: '1/2'。字符串中的分数,没法转化为浮点数 # 执行时,若输入x=2.2,y=3,则顺利输出 6.6 # 执行时,若输入x=2,y=3,则顺利输出 6.0 #【方式2】:直接将输入的字符串转化为 可计算的数字,赋予给变量 x = int(input()) # 若输入2(输出1/2会报错、输入2.2会报错),则将字符串2,转化为int型2,赋值给x y = int(input()) # 若输入3,则将字符串3,转化为int型3,赋值给x print(x * y) # 将两个int型数字相乘,输出 6
- 在input()时,显示提示符
如 x = input("How old are you?")。这句话会用“How old are you?”提示用户,然后将用户输入的str值赋予给变量 x
# 提示用户的两种方式
#【提示方式1】直接通过print输出提示内容,然后 再将录入的str值赋予变量
print("How old are you?",end=" ")
x = input()
#【提示方式2】在input()中,加入提示内容
x = input("How old are you? ")
print(f"So,you're {x}.")
'''
两次命令行都输入“24 years old”,最后结果如下:
How old are you? 24 years old
How old are you? 24 years old
So,you're 24 years old.
'''
【2】查找帮助
- 在终端上输入pydoc input,可以获取关于input的帮助说明(如下图)。还可以使用pydoc 查看 open、file、os、sys的含义
- 键入 q 退出pydoc