內存中⽤於存儲值的命名位置
x = 10 #整數
y = "hello" #字串
z = [1, 2, 3] #陣列
x = 5
y = 3
z = x + y # x和y相加存在z中 = 8
x = 5
x = x + 1 # x的值增加1,x = 6
x = 10
del x # 删除變量x
Python 有許多內置數據類型,包括整數、浮點數、字符串和布林值。
可以使⽤ type() 函數找出值的數據類型。
print(type(10)) # Output: <class 'int'>
print(type(3.1415926)) # Output: <class 'float'>
print(type("Hello World")) # Output: <class 'str'>
print(type(True)) # Output: <class 'bool'>
算術運算符(例如,+、-、*、/)、比較運算符(例如,==、!=、>、<)和邏輯運算符(例如,和、或、不是)。
x = 5
y = 20
# Arithmetic operators
print(x + y) # Output: 25
print(x - y) # Output: -15
print(x * y) # Output: 100
print(x / y) # Output: 0.25
x = 10
y = 20
# Comparison operators
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: False
print(x < y) # Output: True
# Logical operators
print(x > 5 and y < 25) # Output: True
print(x < 5 or y > 25) # Output: False
print(not(x > 5 and y < 25)) # Output: False
根據某個條件是True還是False來執⾏
x = 20
y = 30
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")
For loop
for i in range(5):
print(i) # Output: 0 1 2 3 4
i = 0
while i < 5:
print(i)
i += 1 # Output: 0 1 2 3 4
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number ** 2)
# 1 4 9 16 25
for i in range(5):
print(i)
x = int(10.5) # x 現在是 10 y = int("10") # y 現在是 1
x = float(10) # x 現在是 10.0 y = float("10.5") # y 現在是 10.5
x = str(10) # x 現在是“10” y = str(10.5) # y 現在是“10.5”
x= bool(0) # x 現在為 False y = bool(10) # y 現在為 True
length = float(input("The Length: "))
width = float(input("The Width: "))
area = length * width
print(f"The area of the rectangle is {area}.")
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num+1):
factorial *= i
print( f"You entered: ",num,f"!")
print(f"The factorial of {num} is {factorial}.")
xn = xn-1 + xn-2
費氏數列原理可參考:
https://zh.wikipedia.org/zh-tw/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0
terms = int(input("Enter the number of terms: "))
# Initialize the first two terms of the sequence
a, b = 0, 1
# Print the terms of the sequence
for i in range(terms):
print(a)
a, b = b, a+b