Python基礎-python的輸入輸出(python2與python3的區別);算術運算子
阿新 • • 發佈:2018-11-23
程式:輸入(鍵盤)----程式碼(java/python/c)----輸出(螢幕)
#每一行程式碼只負責完成一個動作
#print的作用:把內容輸出到螢幕上來
#python是一個格式非常嚴格的程式設計語言,每行程式碼前面都不要增加空格
輸入:
1.1 pyhon2*
-
input:(只接收數值型別)
#>>> input() #1 #1 #>>> num = input('請輸入密碼:') #請輸入密碼:123456 #>>> print num #123456 #>>> num = input('請輸入密碼:') #請輸入密碼:westos12345 報錯: #Traceback (most recent call last): #File "<stdin>", line 1, in <module> # File "<string>", line 1, in <module> #NameError: name 'westos12345' is not defined
-
raw_input(接收字串型別)
#>>> name = raw_input('清輸入使用者名稱:') #清輸入使用者名稱:tom #>>> print name #tom #>>> name = raw_input('請輸入年齡:') #請輸入年齡:18 #>>> print name #18 #>>> type(name) #<type 'str'>
-
變數的定義:
#在python中,每個變數在使用之前都必須賦值,變數賦值後該變數才會被建立
#等號(=):就是用來給變數賦值的
#=左邊是一個變數名
#=右邊是儲存在記憶體中的值(被變數名所指向)
#變數名=值
1.2 python3:
input:接收的都是字串型別(沒有raw_input)
#In [1]: num = input()
#12
#
#In [2]: num
#Out[2]: '12'
#
#In [3]: name = input('請輸入你的名字:')
#請輸入你的名字:harry
#
#In [4]: name
#Out[4]: 'harry'
#
python的輸出
-
格式化輸出
在python中可以使用print函式將資訊輸出到控制檯
如果希望輸出文字的同時,一起輸出資料
語法格式:
print(‘格式化字串’ %(變數1,變數2…))
格式化字串 含義
%s: 字串
%d: 十進位制的整數
%f: 浮點數
%%: 輸出% -
定義字串變數name,輸出:我的名字叫小明,請多多關照
name = '大明' sex = '男' print('我的名字叫%s,請多多關照,我的性別是 %s' %(name,sex))
-
定義整數變數student_num,輸出:我的學號是000001
student_nu = 123456 #%06d:不到6位就補0,如果是6位,該是多少是多少 print('我的學號是 %06d' %(student_nu))
-
定義小數 price,weight,money,輸出:水果的單價是?元,購買了?斤,需要多少錢
price = 8.5 weight = 7.5 money = price * weight # %.2f:保留小數點後兩位 print('水果的單價是%.2f元,購買了%.2f斤,需要多%.2f少錢' %(price,weight,money))
-
定義一個小數scale 輸出:資料比例是10.00%
#scale = 0.1 scale = 0.1 * 100 #print('資料比例是 %.2f%%' %(scale * 100)) print('資料比例是 %.2f%%' %(scale))
算術運算子
-
先乘除後加減
-
同級運算子是從左至右 計算
-
可以使用()調整計算的優先順序
python2與python3的區別
-
python2輸入中文時,加入下列程式碼
-- coding:utf-8 --
print'hello world' #python2.*
#print('hello world') #python3.*
python2:
-range(1,5):即刻生成資料,消耗時間並且佔用記憶體
-xrange(1,5):先生成一個xrange物件,使用值的時候才生成資料,才佔用記憶體
python3:
-range(1,5):相當於python2中的xrange