一、与用户交互1、接收用户的输入在Python3中,input会将用户的所有输入内容都存为字符串类型 >>> >>> username = input("请输入您的账号:") 请输入您的账号:CC >>> print(username, type(username)) CC <class 'str'> >>> >>> age = input("请输入的你的年龄: ") 请输入的你的年龄: 18 >>> >>> print(age, type(age)) 18 <class 'str'> >>> age=int(age) >>> print(age > 16) True >>> >>> int("12345") # int只能将纯数字的字符串转成整型 12345 >>> >>> int("1234.5") Traceback (most recent call last): File "<pyshell#177>", line 1, in <module> int("1234.5") ValueError: invalid literal for int() with base 10: '1234.5' >>> int("1234abc5") Traceback (most recent call last): File "<pyshell#178>", line 1, in <module> int("1234abc5") ValueError: invalid literal for int() with base 10: '1234abc5' >>>
在Python2中,用户输入什么类型,就保存为什么类型 # raw_input():用法与python3的input一模一样 >>> age=input(">>>>>>>>>>>>>>>>>>>>>: ") >>>>>>>>>>>>>>>>>>>>>: 18 >>> age,type(age) (18, <type 'int'>) >>> >>> x=input(">>>>>>>>>>>>>>>>>>>>>: ") >>>>>>>>>>>>>>>>>>>>>: 1.3 >>> x,type(x) (1.3, <type 'float'>) >>> >>> x=input(">>>>>>>>>>>>>>>>>>>>>: ") >>>>>>>>>>>>>>>>>>>>>: [1,2,3] >>> x,type(x) ([1, 2, 3], <type 'list'>) >>>
2、格式化输出2.1—— %
>>> res="my name is %s my age is %s" %('egon',"18") >>> print(res) my name is egon my age is 18 >>> res="my name is %s my age is %s" %("18",'egon') >>> print(res) my name is 18 my age is egon >>> res="my name is %s" %"egon" >>> print(res) my name is egon 以字典的形式传值,打破位置的限制 >>> >>> res="我的名字是 %(name)s 我的年龄是 %(age)s" %{"age":"18","name":'egon'} >>> print(res) 我的名字是 egon 我的年龄是 18 >>> %s可以接收任意类型,%d只能接收int >>> >>> print('my age is %s' %18) my age is 18 >>> >>> print('my age is %s' %[1,23]) my age is [1, 23] >>> >>> print('my age is %s' %{'a':333}) my age is {'a': 333} >>> print('my age is %d' %18) # %d只能接收int my age is 18 >>> >>> print('my age is %d' %"18") Traceback (most recent call last): File "<pyshell#202>", line 1, in <module> print('my age is %d' %"18") TypeError: %d format: a number is required, not str >>> 2.2 ——str.format:兼容性好按照位置传值>>> >>> res='我的名字是 {} 我的年龄是 {}'.format('egon',18) >>> print(res) 我的名字是 egon 我的年龄是 18 >>> >>> res='我的名字是 {0}{0}{0} 我的年龄是 {1}{1}'.format('egon',18) >>> print(res) 我的名字是 egonegonegon 我的年龄是 1818 >>> 打破位置的限制,按照key=value传值 >>> >>> res="我的名字是 {name} 我的年龄是 {age}".format(age=18,name='egon') >>> print(res) 我的名字是 egon 我的年龄是 18 >>>
了解知识—— 【填充与格式化】
2.3—— f:python3.5以后才推出 >>> >>> x = input('your name: ') your name: CC >>> y = input('your age: ') your age: 18 >>> res = f'我的名字是{x} 我的年龄是{y}' >>> print(res) 我的名字是CC 我的年龄是18 >>>
二、运算符1、算数运算符>>> print(10 + 3.1) 13.1 >>> print(10 + 3) 13 >>> print(10 / 3) # 结果带小数 3.3333333333333335 >>> >>> print(10 // 3) # 只保留整数部分 3 >>> print(10 % 3) # 取模、取余数 1 >>> print(10 ** 3) # 10的三次方 1000 >>> 2、比较运算符: >、>=、<、<=、==、!=>>> >>> print(10 > 3) True >>> print(10 == 10) True >>> >>> print(10 >= 10) True >>> print(10 >= 3) True >>> >>> >>> name=input('your name: ') your name: cc >>> print(name == 'egon') False >>>
3、赋值运算符# 3.1 =:变量的赋值
|
|
来自: 文炳春秋 > 《Python资料》