Create a virtual environment A best practice among Python developers is to use a project-specific virtual environment. Once you activate that environment, any packages you then install are isolated from other environments, including the global interpreter environment, reducing many complications that can arise from conflicting package versions. You can create non-global environments in VS Code using Venv or Anaconda with Python: Create Environment.
Open the Command Palette (Ctrl+Shift+P), start typing the Python: Create Environment command to search, and then select the command.
The command then presents a list of interpreters that can be used for your project.
Ensure your new environment is selected by using the Python: Select Interpreter command from the Command Palette.
day 01
print function
1 2
print("print('what to print')") print('print("what to print")')
File "c:\Users\lcf\Documents\learning\udemy_python\02.py", line 6 print("Hello world!") IndentationError: unexpected indent
print(("Hello world")
1 2 3
print(("Hello world") ^ SyntaxError: '(' was never closed
print('string concatenation with "+" sign')
string concatenation with “+” sign
input
input("some prompt")
print("Hello " + input("What is your name?"))
print(len(input("What is your name? ")))
variable
1 2
name = input("What is your name? ") print(name)
What is your name? lucfe lucfe
1 2 3 4 5
name = "Jack" print(name)
name = "Angela" print(name)
Jack Angela
print(len(input("What is your name? ")))
1 2 3
name = input("What is your name? ") length = len(name) print(length)
What is your name? lucfe 5
–
1 2 3 4 5 6 7 8 9
a = input("a: ") b = input("b: ")
c = b b = a a = c
print("a = " + a) print("b = " + b)
a: 146 b: 645 a = 645 b = 146
1 2
name = "Jack" print(nama)
1 2 3 4 5
Traceback (most recent call last): File "c:\Users\lcf\Documents\learning\udemy_python\01.04.py", line 12, in <module> print(nama) ^^^^ NameError: name 'nama' is not defined. Did you mean: 'name'?
day 02
data type
string
1 2
print("Hello"[0]) print("123" + "358")
integer
print(123 + 345)
print(12_34_435_4)
float
3.1415
boolean
True False
len(132)
1 2 3 4
Traceback (most recent call last): File "c:\Users\lcf\Documents\learning\udemy_python\02.01.py", line 13, in <module> len(132) TypeError: object of type'int' has no len()
num_char = len(input("what is your name?")) print("your name " + num_char + " characters.")
print(“your name “ + num_char + “ characters.”) ~~~~~~~~~~~~~^~~~~~~~~~ TypeError: can only concatenate str (not “int”) to str
print(f"your name is {name},your score is {score}, your height is {height}, your are winning is {isWinning}")
your name is john,your score is 0, your height is 1.8, your are winning is True
pay_each = round(pay_each)
33.6
pay_each = "{:.2f}".format(pay_each)
33.60
day 03
if condition: do this else: do that
1 2 3 4 5 6 7 8 9
height = int(input("what is your height? ")) if height > 120: print("you can") else: print("you cant")
height >= 120 height == 120 height != 120
1 2 3 4 5 6
number = int(input("number pls? ")) even_odd = number % 2 if even_odd == 1: print("odd") else: print("even")
if condition1: if condition2: do this else: do that else: do else
if condition1: do A elif condition2: do B else: do that
year = int(input(“which year? “))
1 2 3 4 5 6 7 8 9 10
if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("a leap year") else: print("not a leap year") else: print("a leap year") else: print("not a leap year")
if condition1: do A if condition2: do B if condition3: do C
students_heights = input("a list of student height").split() range(0, len(students_heights))
rge = range(1, 10)
<class 'range'>
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
1 2 3 4 5 6 7
print(students_scores) max_score = 0 for score in students_scores: if max_score < score: max_score = score
# max_score = max(students_scores)
Randomize a List using Random.Shuffle() Random.Shuffle() is the most recommended method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list.
withopen("Input/Names/invited_names.txt") as invited_names_file: invited_names = invited_names_file.readlines()
The readlines() method returns a list containing each line in the file as a list item.
The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
string.strip(characters) Remove spaces at the beginning and at the end of the string: include “\n”
day 25
csv files
1 2 3 4
import csv
withopen("data.csv") as data_file: weather_data = csv.reader(data_file)
numbers = [1, 2, 3] new_list = [] for n in numbers: add_1 = n + 1 new_list.append(add_1)
n_list = [n+1for n in numbers]
1 2 3
numbers = range(1, 5) print(type(numbers)) new_list = [n * 2for n in numbers]
1 2 3
name = "Angela" new_list = [letter for letter in name] print(new_list)
1 2 3 4 5
names = ['Alwe', 'Betaafh', 'carol', 'dava'] short_names = [name for name in names iflen(name) < 5] print(short_names) long_names = [name.upper() for name in names iflen(name) >= 5] print(long_names)
[‘Alwe’, ‘dava’] [‘BETAAFH’, ‘CAROL’]
int(num.strip()) -> int(num)
new_dict = {new_key:new_value for item in list} new_dict = {new_key:new_value for (key, value) in dict_1.items()}
1 2 3
names = ['Alwe', 'Betaafh', 'carol', 'dava'] student_scores = {item: random.randint(0, 100) for item in names} print(student_scores)
Options control things like the color and border width of a widget. Options can be set in three ways:
At object creation time, using keyword arguments fred = Button(self, fg="red", bg="blue") After object creation, treating the option name like a dictionary index fred["fg"] = "red" fred["bg"] = "blue" Use the config() method to update multiple attrs subsequent to object creation fred.config(fg="red", bg="blue")
# # index error # fruit_list = ["apple", "banana", "pear"] # fruit = fruit_list[3]
# #type error # text = "abc" # print(text + 5)
1 2 3 4 5 6 7 8 9 10 11 12
try: # something that might cause an exception pass except: # do this if there was an exception pass else: # do this if there were no exceptions pass finally: # do this no matter what happens pass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
try: file = open("a_file.txt") a_dictionary = {"key": "value"} # value = a_dictionary["non_existent_key"] except FileNotFoundError: print("there was an error") open = open("a_file.txt", "w") except KeyError as e: print(f"key error{e}") else: print("no error here") content = file.read() print(content) finally: open.close()
phonetic_dict = {row["letter"]: row.code for (index, row) in data.iterrows()} print(phonetic_dict)
# is_end = True # while is_end: # word = input("enter a word: ").upper() # try: # output_list = [phonetic_dict[letter] for letter in word] # except KeyError: # print("sorry, only letters in the alphabet") # else: # print(output_list) # is_end = False
defgenerate_phonetic(): word = input("enter a word: ").upper() try: output_list = [phonetic_dict[letter] for letter in word] except KeyError: print("sorry, only letters in the alphabet") generate_phonetic() else: print(output_list)
defis_known(): to_learn.remove(current_card) df = pandas.DataFrame(to_learn) # df.to_csv("data/words_to_learn.csv") ## need to remove the index row df.to_csv("data/words_to_learn.csv", index=False) # print(len(to_learn)) next_card()
defnext_card():
# print(to_learn) global current_card current_card = random.choice(to_learn) french_word = current_card["French"]
global flip_timer window.after_cancel(flip_timer) flip_timer = window.after(3000, func=flip_card)
defflip_card(): canvas.itemconfig(title, text="English", fill="white") canvas.itemconfig(word, text=current_card["English"], fill="white") # card_back_img = PhotoImage(file="images/card_back.png") ## this is not work canvas.itemconfig(card_bg_img, image=card_back_img)
with smtplib.SMTP("smtp.gmail.com") as connection: connection.starttls() connection.login(user=my_email, password="xxx") connection.sendmail(from_addr=my_email, to_addrs="liucf2010@sina.com", msg="Subject:Hello\n\nThis is the body of the email")
1 2 3 4 5 6 7 8 9 10
import datetime as dt
now = dt.datetime.now() print(now) print(now.year) print(type(now.year)) # <class 'int'> now.weekday()
program_going = True while program_going: if is_near_home() and is_dark(): with smtplib.SMTP("smtp.google.com") as connection: connection.starttls() connection.login("lucfe2010@gmail.com", "xxx") connection.sendmail("lucfe2010@gmail.com", "liucf2010@hotmail.com", msg=f"Subject:check iss\n\nnow")
time.sleep(60)
day 34
import html q_text = html.unescape(self.current_question.text)