第1章-1 从键盘输入两个数,求它们的和并输出

题目描述

在这里插入图片描述

题解

用python做第一道题目就把我给难住了,我一开始写的代码是这样的:

a = input()
b = input()
print(a+b)
'''
output:
1
2
12
'''

很显然这是不对的

input函数的用法

一开始,我还沾沾自喜,python不需要在输入时去规定变量的类型。但是,我们直接对变量进行赋值时,python会自动判断存储数据的类型,不需要我们进行操作,但input函数并不是这样。
无论我们输入的值是int,float还是string,最后input()函数返回的类型均为string。也因此,字符串是没办法进行算数运算的,如果要使用input输入的数据来进行数学运算,则需要提前规定数据的类型。(即进行强制类型转换)

本题正确写法:

a = int(input())
b = int(input())
print(a+b)

带提示的input()函数

例:

name = input('请输入你的名字')
print(name)
'''
output:
请输入你的名字lmy
lmy
'''
name = 'lmy'
number = input('你好!'+str(name)+'请输入你的学号: ')
print(number)
'''
output:
你好!lmy请输入你的学号: 202005
202005
'''

猜你喜欢

转载自blog.csdn.net/qq_52109814/article/details/121856357