基本輸入輸出
Python中常用基本輸入輸出
- 輸入字串
name = input("What is your name?")
print(name)
What is your name?Jack
Jack
- 輸入整數
age = int(input("How old are you?"))
print(age)
How old are you?23
23
- 輸入浮點數
height = float(input("How tall are you? (m)"))
print(height)
How tall are you? (m)1.68
1.68
- 分三行輸入三個整數
a = int(input("a=?"))
b = int(input("b=?"))
c = int(input("c=?"))
print(a, b, c)
a=?5
b=?4
c=?3
5 4 3
- 分三行輸入兩個整數與一個浮點數
a = int(input("a=?"))
b = int(input("b=?"))
c = float(input("c=?"))
print(a, b, c)
a=?5
b=?2
c=?6.5
5 2 6.5
- 分二行輸入兩個數(不確定是整數還是浮點數)
a = eval(input("a=?"))
b = eval(input("b=?"))
print(a, type(a))
print(b, type(b))
a=?4
b=?9.3
4 <class 'int'>
9.3 <class 'float'>
- 一行輸入兩個整數(空格分隔)
a, b = map(int, input("2 integers ").split())
print(a, b)
2 integers 4 7
4 7
- 一行輸入兩個整數( , 分隔)
a, b = map(int, input("2 integers ").split(","))
print(a, b)
2 integers 4, 7
4 7
- 一行輸入三個整數( , 分隔),存成三個整數
a, b, c = map(int, input("3 integers ").split(","))
print(a, b, c)
3 integers 3,4,5
3 4 5
- 一行輸入不定數個整數(空格分隔),存成一個整數list
la = [int(i) for i in input("many integers ").split()]
print(la)
many integers 2 3 4 5 6
[2, 3, 4, 5, 6]
- 重複輸入整數直到輸入0為止
while True:
a=int(input("stop at 0 "))
if a==0:
break
print(a)
stop at 0 3
3
stop at 0 4
4
stop at 0 5
5
stop at 0 0
- 重複輸入整數直到輸入"STOP"為止,並存入list中
la=[]
while True:
a=input("STOP to exit ")
if a=="STOP":
break
la.append(int(a))
print(la)
STOP to exit 4
STOP to exit 5
STOP to exit 6
STOP to exit STOP
[4, 5, 6]
- 輸出為浮點數
a = int(input("a? "))
b = int(input("b? can not be 0 "))
c = a/b
print(c)
a? 3
b? can not be 0 5
0.6
a? 4
b? can not be 0 3
1.3333333333333333
- 輸出為浮點數限定小數位數2位
a = int(input("a? "))
b = int(input("b? can not be 0 "))
c = a/b
print(f"{c:.2f}")
a? 8
b? can not be 0 3
2.67
a? 4
b? can not be 0 3
1.33
a? 4
b? can not be 0 2
2.00
- 輸出限定為整數 (計算過程中能不變成浮點數就不要變成浮點數)
轉整數會無條件捨去
用格式化輸出會用一種奇怪的四捨五入方式進位
a = int(input("a? "))
b = int(input("b? can not be 0 "))
c = a/b
print("轉整數",int(c))
print(f"格式化輸出 {c:.0f}")
a? 4
b? can not be 0 2
轉整數 2
格式化輸出 2
a? 5
b? can not be 0 2
轉整數 2
格式化輸出 2
a? 7
b? can not be 0 2
轉整數 3
格式化輸出 4