Reference: Think python: How to Think Like a Computer Scientist http://www.greenteapress.com/thinkpython/
Tell computer how to run via a series of prompt, it includes:
print("Hello World!") # (Keyboard input → calculation → output from screen)
Hello World!
from typing_extensions import Type
import keyword
Type
keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
When you need to check how a function works, google and help() is always a good approach. Of cause, now you have ChatGPT or other AI assistant can help.
help(print)# or ?print
Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
help('for')
The "for" statement ******************* The "for" statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object: for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the "expression_list". The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty or an iterator raises a "StopIteration" exception), the suite in the "else" clause, if present, is executed, and the loop terminates. A "break" statement executed in the first suite terminates the loop without executing the "else" clause’s suite. A "continue" statement executed in the first suite skips the rest of the suite and continues with the next item, or with the "else" clause if there is no next item. The for-loop makes assignments to the variables in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop: for i in range(10): print(i) i = 5 # this will not affect the for-loop # because i will be overwritten with the next # index in the range Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in type "range()" represents immutable arithmetic sequences of integers. For instance, iterating "range(3)" successively yields 0, 1, and then 2. Related help topics: break, continue, while
It works by assigning value to a variable, including value and type
1. value:a number or a string
2. type:type of the value,such as int, float (double) or str
message = "Hello World!" # In python, everything inside a double quotes("") or a quote ('') is a list.
height = 160 # Here, "=" means "asign", we asign 160 to the variable height.
print(message)
print(type("Hello World!"))# <class 'str'>
print(type(message))# <class 'str'>
print(type(height))# <class 'int'>
height
Hello World! <class 'str'> <class 'str'> <class 'int'>
160
Naming a variable:
◆ Could be letter, number, underscore, but need to begin with letter
◆ Upper case is ok, and upper case is different from lower case
◆ With meaning is better (flowrate is better than a)
◆ Avoid keywords in python
1. Integer(int) 整數
2. Floating point(float) 浮點數(有小數點)
3. String(string) 字串
4. Boolean (boolean) 布林值(0 or 1)
◆ True is 1,False is 0
◆ Boolean operation (and, or, not)
# 1
print(10)
# 2
print(1.5)
# 3
print("string")
# 4
True
print(1==2) #False
print(False==0)# True
10 1.5 string False True
# Boolean operations
print((1<=2) and (2>1) or (1==2))# True and True -> True
print((1==2) and (2>1))# False and True -> False
print((1==2) or (2>1))# False or True -> True
print(not (1==2)) # not False -> True
True False True True
Every variable in Python is an object and belongs to a class.
Functions in a class is called method.
◆ Similar to function but the syntax is different
◆ variable.method
# Use string as an example
string1 = "Hello world!"
print(string1.upper())
string1.count("l")
HELLO WORLD!
3
string1 = "This book is largely concerned with Hobbits, and from its pages a reader may discover much of their character and a little of their history. Further information will also be found in the selection from the Red Book of Westmarch that has already been published, under the title of The Hobbit. That story was derived from the earlier chapters of the Red Book, composed by Bilbo himself, the first Hobbit to become famous in the world at large, and called by him There and Back Again, since they told of his journey into the East and his return: an adventure which later involved all the Hobbits in the great events of that Age that are here related. Many, however, may wish to know more about this remarkable people from the outset, while some may not possess the earlier book. For such readers a few notes on the more important points are here collected from Hobbit-lore, and the first adventure is briefly recalled. Hobbits are an unobtrusive but very ancient people, more numerous formerly than they are today; for they love peace and quiet and good tilled earth: a well-ordered and well-farmed countryside was their favourite haunt. They do not and did not understand or like machines more complicated than a forge-bellows, a water-mill, or a hand-loom, though they were skilful with tools. Even in ancient days they were, as a rule, shy of ‘the Big Folk’, as they call us, and now they avoid us with dismay and are becoming hard to find. They are quick of hearing and sharp-eyed, and though they are inclined to be fat and do not hurry unnecessarily, they are nonetheless nimble and deft in their movements. "
string1.count("They")
2
Three basic data structure in Python
1. List <br>
◆ A list of items, each element could be differnt data type
◆ Every item is called element
◆ Use [] to create a list
# List
word = "string"
print(word[1:3])# 字串也是一種串列,每個字元為其元素 ***注意:[]可以選取元素,python中0代表第一個元素,-1則是最後一個,不包含index最後一項
# A string is also a list, every letter is an element.
# Use [] to select element. For example, [0] means the first element
# [-1] means the last element.
list1 = ['string',1,2]
list2 = [True,3.3,["string",2]]# a list in a list(nested list)
print(len(list1))# =3
list1[1] = 2# modify element in a list
print(list1)
list3 = list1 + list2# list的相加
print(list3)
del(list3[2])# 刪除list3中第4個元素
# 更多了解list 可以到 https://docs.python.org.tw/3/tutorial/datastructures.html#list
# copy of list
list1 = [1,2,3]
list2 = list1
list2[1] = 4# 將2改成4
print(list1)
tr 3 ['string', 2, 2] ['string', 2, 2, True, 3.3, ['string', 2]] [1, 4, 3]
2. 字典(dictionary)
◆ 跟list很像,但是index可以使用整數以外的型態(稱為keys)
◆ 可以使用{}創造
◆ key是一對一的,重複定義會覆蓋前面的
◆ 藉由.keys()可以查看所有keys
# Dictionary
dic1 = {"a":1,"b":2,"c":3}
# dic1[1] -> error
print(dic1["a"])
dic1 = {"a":1,"b":2,"a":3}
print(dic1)
1 {'a': 3, 'b': 2}
3. 元組(tuples)
◆ 可由一串值以逗號分隔定義,並由()表示
◆ 不可變更,因此常用來儲存不可改變的資料
# Tuples
tup1 = 1,5,3
print(tup1[1])
# tup1[1] = 2 -> error
5
# 補充 - about string and opeator
# 布林運算子 in: 檢查左邊的值是否存在於右邊
"a" in "Banana"# True
1 in [1,2,3]# 也可以對list等資料使用
#string operation
# comparison: 照第一個字的順序比,後面的大,大寫比小寫小
str1 = "apple"
str2 = "banana"
str3 = "Banana"
print(str1>str2)# False
print(str1>str3)# True
print(str1 + str2)
False True applebanana
# string中的文字不可以直接改變
str[1] = "a"# -> error
# 必須藉由重新指定才能進行文字操作
print()是python內建的函數,然而當我們需要使用一開始不在裏面的功能時,就需要先將函式庫引入。在這裡以math套件中的sqrt函數為例:
# sqrt函數可以用來開根號,如果直接使用:
from math import sqrt
sqrt(25)
5.0
import math
math.sqrt(25)
5.0
import math as mt
mt.sqrt(25)
5.0
from math import sqrt
sqrt(25)
5.0
# prompt: give me more example about using math in python
import math
# Calculate the sine of an angle
angle = math.radians(30) # Convert degrees to radians
sine_value = math.sin(angle)
print("Sine of 30 degrees:", sine_value)
# Calculate the cosine of an angle
cosine_value = math.cos(angle)
print("Cosine of 30 degrees:", cosine_value)
# Calculate the tangent of an angle
tangent_value = math.tan(angle)
print("Tangent of 30 degrees:", tangent_value)
# Calculate the square root of a number
sqrt_value = math.sqrt(25)
print("Square root of 25:", sqrt_value)
# Calculate the factorial of a number
factorial_value = math.factorial(5)
print("Factorial of 5:", factorial_value)
# Calculate the logarithm of a number
log_value = math.log(100, 10) # Logarithm base 10
print("Logarithm base 10 of 100:", log_value)
# Calculate the ceiling and floor of a number
number = 3.14
ceiling_value = math.ceil(number)
floor_value = math.floor(number)
print("Ceiling of 3.14:", ceiling_value)
print("Floor of 3.14:", floor_value)
Sine of 30 degrees: 0.49999999999999994 Cosine of 30 degrees: 0.8660254037844387 Tangent of 30 degrees: 0.5773502691896257 Square root of 25: 5.0 Factorial of 5: 120 Logarithm base 10 of 100: 2.0 Ceiling of 3.14: 4 Floor of 3.14: 3
# prompt: show me more examples of using math
import math
# Calculate the factorial of a number
print(math.factorial(5)) # Output: 120
# Calculate the greatest common divisor (GCD) of two numbers
print(math.gcd(12, 16)) # Output: 4
# Calculate the sine of an angle in radians
angle_rad = math.radians(30) # Convert degrees to radians
print(math.sin(angle_rad)) # Output: 0.5
# Calculate the cosine of an angle in radians
print(math.cos(angle_rad)) # Output: 0.8660254037844386
# Calculate the tangent of an angle in radians
print(math.tan(angle_rad)) # Output: 0.5773502691896257
# Calculate the value of pi
print(math.pi) # Output: 3.141592653589793
120 4 0.49999999999999994 0.8660254037844387 0.5773502691896257 3.141592653589793
# prompt: print a christmas tree
def print_christmas_tree(height):
"""Prints a Christmas tree with the given height."""
for i in range(1, height + 1):
spaces = " " * (height - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)
# Get the desired height of the tree from the user
height = int(input("Enter the height of the Christmas tree: "))
# Print the tree
print_christmas_tree(height)
Enter the height of the Christmas tree: 10 * *** ***** ******* ********* *********** ************* *************** ***************** *******************