Python中input( )和raw_input( )的区别及其用法

Python的基础语法:


https://blog.csdn.net/qq_37941471/article/details/81323824

input( )和raw_input( )的区别


input( )     获得的是一个数值类型的变量(eg: int )
raw_input( ) 获得是一个字符串(string)类型的变量

input( )和raw_input( )的用法:


raw_input练习:

1. 使用raw_input从用户输入得到一个字符串,并显示输入的内容
[xj@localhost day02]$ cat test.py
# __*__ coding: UTF -8 __*_ (中文注释加上这行代码)


str = raw_input("Please Enter one string:")
print "str = %s" % str

[xj@localhost day02]$ python test.py
Please Enter one string:xujia19970130
str = xujia19970130
2. 使用raw_input输入两个数字,计算两个数字的和,并显示
[xj@localhost day02]$ cat test.py
# __*__ coding: UTF -8 __*_ (中文注释加上这行代码)


a = raw_input("Please Enter a:")
b = raw_input("Please Enter b:")
print type(a)
print int(a)+int(b)                                                                                                                                                                # 因为raw_input输入的内容是字符串类型,所以必须强转类型
[xj@localhost day02]$ python test.py
Please Enter a:10
Please Enter b:20
<type 'str'>
30

用户输入一个数字,判断这个数字是正数,负数,还是0

1. input( )获得的是一个数字
[xj@localhost day02]$ cat test.py
# __*__ coding: UTF -8 __*__ (中文注释加上这行代码)

a = raw_input('Please Enter one number:')
a = int(a)
if a > 0:
    print "a 是 正数"
elif a < 0:
    print "a 是 负数 "
else:   # a = 0
    print "a 等于 0 "
[xj@localhost day02]$ python test.py
Please Enter one number:10
a 是 正数
[xj@localhost day02]$ python test.py
Please Enter one number:0
a 等于 0 
[xj@localhost day02]$ python test.py
Please Enter one number:-10
a 是 负数 
2. raw_input获得是一个字符串
[xj@localhost day02]$ cat test.py
# __*__ coding: UTF -8 __*__ (中文注释加上这行代码)

a = input('Please Enter one number:')
if a > 0:
    print "a 是 正数"
elif a < 0:
    print "a 是 负数 "
else:   # a = 0
    print "a 等于 0 "
[xj@localhost day02]$ python test.py
Please Enter one number:10
a 是 正数
[xj@localhost day02]$ python test.py
Please Enter one number:0
a 等于 0 
[xj@localhost day02]$ python test.py
Please Enter one number:-12
a 是 负数 

猜你喜欢

转载自blog.csdn.net/qq_37941471/article/details/81458304