一,、與用戶交互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資料》