一、如何接收用戶的輸入
#基礎階段寫程式的思路,就是把自己想象成一臺計算機,如果是你,你的作業流程是什么
在python3中,input會將用戶輸入的所有內容都保存成字串型別
username = input('請輸入你的賬號:') print(username,type(username)) age = input('請輸入你的年齡:').strip() print(age,type(age)) age = int(age) print(age >17) print(age,type(age))
在python2中:
raw_input的用法與python3中的input一模一樣
input要求用戶必須輸入一個明確的資料型別,輸入的是什么型別,就存成什么型別
>>> s = input('>>>>>>>>>:') >>>>>>>>>:18 >>> s,type(s) (18, <type 'int'>) >>> s = input('>>>>>>>>>:') >>>>>>>>>:1.3 >>> s,type(s) (1.3, <type 'float'>) >>> s = input('>>>>>>>>>:') >>>>>>>>>:[1,2,22] >>> s,type(s) ([1, 2, 22], <type 'list'>) >>>
二、字串格式化輸出
2.1 %格式化字串的方式從python誕生之初就已經存在
時至今日,python官方也并未棄用%,但是也不推薦這種格式化方式
值按照位置與%s 一一對應,少一個也不行,多一個也不行
res = 'my name is %s, my age is %s' %('egon',18) res = 'my name is %s, my age is %s' %('18','egon') res = 'my name is %s, my age is %s' %('egon',18) print(res)
傳入字典的形式,可以打破位置的限制
res = 'my name is %(name)s, my age is %(age)s' %{'name':'egon','age':'18'} print(res)
print('my age is %s' %'18') print('my age is %s' %18) print('my age is %s' %[1,22,3]) print('my age is %s' %{1,22,3}) print('my age is %d' % 18) # %d只能接受int,%s可以接受任何型別的值
2.2 str.format :兼容性好
按照位置取值
res = 'my name is {}, my age is {}'.format('egon', 18) print(res) res = 'my name is {0}{0}{0}, my age is {1}{1}'.format('egon', 18) print(res)
打破位置的限制,按照key=value傳值
res = 'my name is {name}, my age is {age}'.format(age= 18 , name = 'egon') print(res)
2.3 f python3.5以后推出
name = input('請輸入你的名字:').strip() age = input('請輸入你的年齡:').strip() res = f'my name is {name}, my age is {age}' print(res)
三、運算子
3.1 基本運算子
1.算數運算子
+ - * /
print(10 + 3) print(10 - 3) print(10 * 3) print(10 / 3) print(10 // 3) print(10 % 3) print(10 ** 3) # 運行結果 """ 13 7 30 3.3333333333333335 3 1 1000 """
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/296016.html
標籤:Python
