Skip to main content

[Python] Notebook-3 Introduction to Python: Fundamentals—Part.1


這大概是我人生中最認真學寫程式的時刻了。
寫HSpice不算的話啦!

聽完「絕對菜鳥」之後我接著去聽另一門課—Introduction to Python: Fundamentals
對。
感覺比較沒那麼菜了。

但我還是一樣(很厚顏的)把自己整理的筆記提供給大家。
不過要注意這門課有時候一個網頁會有兩到三部影片,
要記得下拉確認。

內容有indexing with string、len() function、.find() function、reversing the content of strings、accessing sub-strings、.append() function、.insert() function、del function、.pop() function、.remove() function、creating a specific span of a counting sequence with range(a, b, c)、list concatenation、extending lists、.reverse() and reversed() function、.sort() and sorted() functions、.split() and .join() functions。

然後在讀取資料(Open, read, and write)的部分,
我會放到下一篇再做分享。



# -*- coding: utf-8 -*-
"""
Created on Fri Sep  1 21:36:17 2017
@author: ShihHsing Chen
This is a note for the class 
"Introduction to Python: Fundamentals".
"""

#We can access each character in a string with either a positive or 
#negative index. In this case, [0], [1], [2], ... = ..., [-3], [-2], [-1]
student_name = "Kevin Chen"
print(student_name[0], "--> First character is at index 0.")
print(student_name[-1])

#We can count the length of the string with len() and find the index 
#of a specific character's first occurance with .find(the character) 
#To search a sub-string, we use .find(sub-string, start index, end index)
print("There are", len(student_name), "characters in student_name.")
print(student_name.find("v"))
print(student_name.find("in", 1, 7))

#We can access a sub-string with [a:b:c], which means the sub-string
#starts from index a, stops befroe index b with a step c. 
print(student_name[0: 7])
print(student_name[: 4])
print(student_name[: 9: 2])

#If we combine negative index and string slicing techniques, 
#we can print out the reversed string.
print(student_name[: : -1], "\n")

#We can use for/in to iterate through a string.
#And here we combine negative indexes to make it more complicated.
new_name = ""

for ltr in student_name[-1: -11: -1]:
    if ltr.lower() == "i":
        new_name += ltr.upper() + ltr.upper()
    else:
        new_name += ltr

print("From", student_name, "to", new_name, "\n")

#Let's get to know lists and access items in them.
empty_list = []
sample_list = [1, 2, 3, 3, 4, 5, 5]
mixed_list = [1, 1, "one", "two", 2.0, sample_list, "Hello World"]
print(mixed_list[3: 6])
print("mixed_list: ", type(mixed_list), "\n")

#To append exactly one item at the end of a list, we use .append()
empty_list.append("I'm learning Python.")
print(empty_list)

#To insert exactly one item, we use .insert(index, item)
empty_list.insert(1, "XD")
print(empty_list, "\n")

#To delete items, we use del.
print(sample_list)
del sample_list[0: 2]
print(sample_list)

#To return and delete items, we use .pop(index) and the default
#index is the last one.
print(sample_list.pop(3))
print(sample_list)

#If we're not sure about the indexes of items to delete, use .remove(item)
#However, if there is more than one item to remove, we need for/in loop
#to remove all the items we want to remove.
#FYI, the reason we can use for/in to iterate through string and list is that
#they are both sequences.
sample_list.remove(3)
print(sample_list)
sample_list.append(3)
print(sample_list, "\n")

for num in sample_list:
    print(sample_list)
    sample_list.remove(3)
    print(sample_list)

print()

#To find occurances of a character when you iterate lists of strings,
#we can use .count(the character that you want to count occurances)
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "São Paulo"]
search_letter = input("What letter do you want to count occurances? ")
total = 0

for city_name in cities:
    total += city_name.lower().count(search_letter)

print("The total # of \"" + search_letter + "\" in the list is", total)
    
def city_search(search_item, cities = ["Shanghai", "Munich", "Tokyo"] ):
    for city in cities:
        if city.lower() == search_item.lower():
            return True
        else:
            # go to the next item
            pass
    # no more items in list
    return False

visited_cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai"]
search = input("enter a city visited: ")
print(search, "in default cities is", city_search(search))
print(search, "in visited_cites list is", city_search(search,visited_cities))

#To create a specific span of a counting sequence, we use 
#range(start, stop, step)
sub_total = 0
temp = 0

for item in range(25, 46, 5):
    temp = sub_total
    sub_total += item
    print("sub_total:", temp, "+", item, "=",sub_total)

print("Total =", sub_total)

#Concatenation = the action of linking something together
#We can combine two or more lists with + or .extend() Let's take a look.
US_grad_school_1 = ["Stanford University", "Cornell University"]
US_grad_school_2 = ["UCLA", "UC San Diego"]
Taiwan_grad_school = ["National Taiwan University", 
                      "National Chiao Tung University"]
US_grad_school = US_grad_school_1 + US_grad_school_2
print("Some Graduate Schools in the US: ", US_grad_school, "\n")

#Caution: We cannot use the following operation since nothing would be 
#assigned to grad_school.
#grad_school = US_grad_school.extend(Taiwan_grad_school)
US_grad_school.extend(Taiwan_grad_school)
grad_school = US_grad_school
print("Some Graduate School: ", grad_school, "\n")

#Here we get the .reverse() method for lists but not for strings.
#If you want to reverse strings, either iterate through them or 
#use reversed(str_name)
#I show you both of these methods below.
print("Original order: ", grad_school, "\n")
grad_school.reverse()
print("Reversed order: ", grad_school, "\n")

print(student_name)

rev_student_name_1 = ""
rev_student_name_2 = ""

for count in student_name[-1: -11: -1]:
    rev_student_name_1 += count

print(rev_student_name_1)

for count in reversed(rev_student_name_1):
    rev_student_name_2 += count

print(rev_student_name_1)
print(rev_student_name_2)

#Sorting a string!
#We can use .sort() or sorted() to sort a string.
#Caution: .sort() change the original order of a string, but sorted() does 
#not change the original order. The sorted() function works like the 
#reversed() function. Don't you think?
GRE_score = [320, 330, 322, 319, 331, 334, 340, 336, 337, 321]
print(GRE_score)
sorted_GRE_score = sorted(GRE_score)
print(sorted_GRE_score)
print(GRE_score)
GRE_score.sort()
print(GRE_score)

print(grad_school, "\n")
grad_school.sort()
print(grad_school)

#Converting a string to a list with .split(split point = blank space)
adage = "Do not pray for an easy life, pray for the strength to endure."
print(adage, "\n")
adage_words = adage.split()
print(adage_words, "\n")
adage_character = adage.split("a")
print(adage_character, "\n")

#To reverse this process, we use "connecting character you like".join()
restored_string = "-".join(adage_words)
print(restored_string)
print("*".join(student_name))
print(student_name)

#Change the default setting of "end of line."
#This is the trick the lecturer offered, which is not useful to me by now.
print("Hello World", end = "!!!!!!!\n")

Comments

Popular posts from this blog

[申辦綠卡] EB-2 NIW 國家利益豁免綠卡申請教學(一)找合作的律師事務所

Image by  David Peterson  from  Pixabay

[申辦綠卡] EB-2 NIW 國家利益豁免綠卡申請教學(零)名詞解釋 Petitioner vs Applicant

Image by  David Peterson  from  Pixabay

[申辦綠卡] EB-2 NIW 國家利益豁免綠卡申請教學(七)組裝 NIW I-140 申請文件包

Image by  David Peterson  from  Pixabay