udemy_python_100_days

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

1
2
print("print('what to print')")
print('print("what to print")')

string

print("Hello world!\nHello World!")

output
Hello world!
Hello World


1
2
print ("Hello" + " Angela")
print ("Hello" + " " "Angela")

Hello Angela
Hello Angela


print("Hello world!")

1
2
3
  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


new_num_char = str(num_char)

print(type(1234))

<class 'int'>

float("100.5)


1
2
3
4
5
6
7
two_digit_num = input("your number is?")
print(type(two_digit_num))
first_digit = int(two_digit_num[-2])
second_digit = int(two_digit_num[-1])
answer = str(first_digit + second_digit)

print("your answer is " + answer)

mathmatical operator

7 - 4
3 * 2
2 ** 3
6 / 3

print(type(6/2))
<class 'float'>

pemdas

parentheses ()
exponents **
multiplication/division * /
addition/subtraction + -

left to right

1
2
print(3 * 3 + 3 / 3 - 3)
print(3 * (3 + 3) / 3 - 3)

7.0
3.0

print(8 / 3)
print(round(8 / 3))
print(round(8 / 3, 2))
print(8 // 3)
print(type(8 // 3))

2.6666666666666665
3
2.67
2
<class 'int'>

% remainder


1
2
3
4
score = 4
score -= 2
# score = score - 2
print(score)

2


1
2
3
4
5
6
score = 0
height = 1.8
isWinning = True
name = "john"

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

Alt text

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

Alt text


Alt text

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


logical operators

and or not


1
2
3
4
5
6
print("""dfas
ag
ags
ags""")

print('you\'re good "student"')

day 04

randomisation

mersenne twister

python module

1
2
import random
print(random.randint(1, 10))

random module

Returns a random integer between a and b (both inclusive).


random.random() -> Returns the next random floating point number between [0.0 to 1.0)

1
2
3
import random
random_float = random.random()
print(random_float)

0.0000000… -> 0.9999999…
0.9597056472657862

print(random_float * 5)

0.000000… –> 4.99999…
2.441770790800433


list

have order

fruits = [item1, item2]

data structure

day 05

for item in items_list:
do someting on item

1
2
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.


letters[random.randint(0, len(letters)-1)]

random.choice(letters)

day 06

python buildin funtions

1
2
3
4
5
def my_function():
print("Hello")
print("Bye")

my_function()

range(6)

day 07

Alt text

How To Use Break, Continue, and Pass Statements when Working with Loops in Python 3

1
2
3
4
# import moduel_07_01
# stages = moduel_07_01.stages

from moduel_07_01 import stages

day 08

argument parameter

def my_function(something)
#do this with something

my_function(123)

somthing -> parameter
123 -> arguments

positional argument
keyword argument

greet_with(name = "Angela", location = "London")
greet_with(location = "London", name = "Angela")

math.ceil(-23.11) : -23.0
math.ceil(300.16) : 301.0
math.ceil(300.72) : 301.0

math.floor(-23.11) : -24.0
math.floor(300.16) : 300.0
math.floor(300.72) : 300.0

1
2
3
4
5
#for n in range(len(alphabet)):
# if letter == alphabet[n]:
# letter_index = n
# break
letter_index = alphabet.index(letter)

day 09

dictionares

{key: value}

1
2
3
4
5
6
7

dic1 = {
"bug": "asd",
"function": "asdfq",
123: "asgqe",
"name": 164,
}

dic1[“bug”]
dic1[123]

dic1[“bog”]
KeyError: ‘bog’

add a pair
dic1[“Loop”] = “asdf asdf wrye”

wipe a dic
dic1 = {}

edit an item
dic1[“bug”] = “sdaf dasfa das g”

1
2
3
for key in dic1:
print(key)
print(dic1[key])

{
key: [list],
key2: {dict},
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# nesting a list in a dictionary
travel_log = {
"france": ["paris", "lille", "dijon"],
"germany": ["berlin", "hamburg"],
}

# nesting a dictionary in a dictionary

travel_log = {
"france": {
"visited_cities": ["paris", "lille", "dijon"],
"total_visits": 12,
},
"germany": {
"visited_cities": ["berlin", "hamburg"],
"total_visits": 6,
},
}

# nesting a dictionary in a list

travel_log = [
{
"country": "france",
"visited_cities": ["paris", "lille", "dijon"],
"total_visits": 12,
},
{
"country":"germany",
"visited_cities": ["berlin", "hamburg"],
"total_visits": 6,
}
]

day 10

1
2
3
4
def my_function():
return 3 * 2

result = my_function

str.title()
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def add(a, b):
return a + b

def sub(a, b):
return a - b

def multi(a, b):
return a * b

def div(a, b):
return a / b

operations = {
"+": add,
"-": sub,
"*": multi,
"/": div,
}

cal_function = operations["*"]
cal_function(2, 3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# local scope
# in a function
# any named object, not just variables

def drink_potion():
potion_strenth = 2
print(f"{potion_strenth}")

drink_potion()

# global scope
# not in a function

player_health = 10

def drink_potion():
potion_strenth = 2
print(f"{potion_strenth}")
print(f"{player_health}")

# no block scope
# if statement

game_level = 3
enemies = ['skeleton', 'zombie', 'alien']
if game_level < 5:
new_enemy = enemies[0]

print(f"{new_enemy}")

1
2
3
4
5
6
7
8
9
10
11
12
enemies = 1

def increse_enemies():
enemies = 2
print(f"{enemies}")

# 2

increse_enemies()
print(f"{enemies}")

# 1
1
2
3
4
5
6
7
8
9
10
11
12
13
enemies = 1

def increse_enemies():
global enemies
enemies = 2
print(f"{enemies}")

# 2

increse_enemies()
print(f"{enemies}")

# 2
1
2
3
4
5
6
7
8
enemies = 1
def increse_enemies():

print(f"{enemies}")
return enemies + 1

enemies = increse_enemies()

# global constant

PI = 3.1415926

day 13

debug

day 14

day 15

day 16

object oriented programming oop

attribute
has

method
does

class
type/blueprint

object

car = CarBlueprint()

object.attribute
car.speed

object.method()
car.move()

day 17

class name PascalCase

not camelCase

else: snake_case

initialize -> construtor

def init(self):

day 18

dont
from turtle import *

module alias
import turtle as t

installing moduel


tuple

tuple_a = (1, 2, 3)

= list(tuple)

day 19

event listeners

higher order function

object state

instance

day 20

day 21

class inheritance

slicing list/dictionary

[2: 5: 2]
[::-1]

day 22

create the screen

create the paddle

create the ball and move

detect collision with wall and bounce

detect collision with paddle

detect when paddle misses

keep score

day 23

move the turtle with keypress

create and move the cars

detect collision with car

detect when turtle reaches the other side

create a scoreboard

day 24

read/write files

1
2
3
4
5
with open("data.txt") as file:
return file.read()

with open("data.txt", mode="w") as file:
file.write(str(self.high_score))

absolute file path

relative file path
./ working directry or “”

../ working directory parent folder


1
2
3
4
5
strip_name = name.strip()
mail_content = start_content.replace("[name]", strip_name)

with open("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

with open("data.csv") as data_file:
weather_data = csv.reader(data_file)

pandas -> data analysis

1
2
3
4
# print(data["temp"])
# print(type(data["temp"]))
# print(data)
# print(type(data))

Series column
DataFrame table

import pandas

data = pandas.read_csv(“data.csv”)

print(data[data["day"] == "Monday"])
print(type(data[data["day"] == "Monday"])) -> DataFrame

ser.iloc[0]
Purely integer-location based indexing for selection by position.

Series.item()
Return the first element of the underlying data as a Python scalar.


1
2
3
4
5
6
7
8
data_dict = {
"students": ["Amy", "James", "Angela"],
"scores": [76, 56, 65],
}
data = pandas.DataFrame(data_dict)
data.to_csv("score_data.csv")

print(data)

day 26

comprehension

create a list from a exsiting list

1
2
3
4
5
6
7
8
9
10
# new_list = [new_item for item in list]

numbers = [1, 2, 3]
new_list = []
for n in numbers:
add_1 = n + 1
new_list.append(add_1)


n_list = [n+1 for n in numbers]
1
2
3
numbers = range(1, 5)
print(type(numbers))
new_list = [n * 2 for 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 if len(name) < 5]
print(short_names)
long_names = [name.upper() for name in names if len(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)

{‘Alwe’: 45, ‘Betaafh’: 95, ‘carol’: 21, ‘dava’: 24}

1
2
student_scores = {'Alwe': 45, 'Betaafh': 95, 'carol': 21, 'dava': 24}
passed_student = {student: score for (student, score) in student_scores.items() if score >= 60}

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.


1
2
3
4
5
6
7
8
9
student_dict = {
"student": ["Angela", "James", "Lily"],
"score": [56, 76, 98]
}

# for key, value in student_dict.items():
for (key, value) in student_dict.items():
print(key)
print(value)
1
2
3
4
5
6
for (index, row) in student_data.iterrows():
print(index)
print(row)
print(type(row))
print(row["student"])
print(type(row["student"]))
1
2
3
4
5
6
7
8
9
10
11
0

student Angela
score 56
Name: 0, dtype: object

<class 'pandas.core.series.Series'>

Angela

<class 'str'>

day 27

tkinter

gui

function advanced argument

default value

# def my_function(a=0, b, c=0):
def my_function(b, a=0, c=0):
Alt text

=…

Alt text


any number of arguments
unlimited position arguments

1
2
3
4
5
6
7
8
9
10
def add(*args):
result = 0
print(type(args))
for n in args:
print(n)
result += n
return result

result = add(1, 2, 3, 4)
print(result)

<class 'tuple'>


1
2
3
4
5
6
7
8
def calc(n, **kwargs):
print(type(kwargs))
print(kwargs)
n += kwargs["add"]
n *= kwargs["multi"]
return n

calc(2, add=3, multi=5)

<class 'dict'>
{‘add’: 3, ‘multi’: 5}

1
2
3
4
5
6
7
8
9
class Car:
def __init__(self, **kwargs):
self.make = kwargs["make"]
# self.model = kwargs["model"]
self.model = kwargs.get("model")


my_car = Car(make="Nissan")
print(my_car.model)

None


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")


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
## label

my_label = tkinter.Label(text="label text", font=("Arial", 24, "bold"))
my_label.pack()

## button

def button_click():
print("I am clicked")

button = tkinter.Button(text="Click Me", command=button_click)
button.pack()

## entry

input = tkinter.Entry(width=10)
input.pack()

input_text = input.get()

day 28

dynamic type

a = 1
a = “Hello”

day 29

1
2
3
4
passwords_1 = ['a', 'b']
passwords_2 = ['c', 'd']
passwords_3 = ['e', 'f']
passwords = passwords_1 + passwords_2 + passwords_3

final_password = "".join(passwords)


messagebox.showinfo(title="oops", message="Please dont leave any fields empty!")

is_ok = messagebox.askokcancel(title=f"{website}", message=f"Email: {username}\nPassword: {password}\n Is it ok to save?")


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

label_username = Label(text="Email/Username:")
label_username.grid(row=2, column=0)



text_website = Entry(width=45)
text_website.focus()
# text_website.delete(0, END)
text_website.grid(row=1, column=1, columnspan=2)

text_username = Entry(width=45)
text_username.insert(0, "lucfe2010@gmail.com")
text_username.grid(row=2, column=1, columnspan=2)


button_password = Button(text="Generate Password", command=generate_password)
button_password.grid(row=3, column=2)

1
2
3
4
5
6
7
8
window = Tk()
window.title("password manager")
window.config(padx=50, pady=50)

canvas_main = Canvas(width=200, height=200, highlightthickness=0)
bg_img = PhotoImage(file="logo.png")
canvas_main.create_image(100, 100, image=bg_img)
canvas_main.grid(column=1, row=0)

day 30

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# # FileNotFoundError
# with open("a_file.txt") as file:
# file.read()


# #KeyError
# a_dictionary = {"key": "value"}
# value = a_dictionary["non_existent_key"]


# # 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()
1
2
3
4
5
6
7
8
height = float(input("height: "))
weight = int(input("weight: "))

if height > 3:
raise ValueError("human should not be over 3 meters")

bmi = weight / height ** 2
print(bmi)
1
2
3
4
5
6
7
8
9
10
11
fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
try:
fruit = fruits[index]
except IndexError as e:
print("Fruit pie")
else:
print(fruit + " pie")

make_pie(4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
facebook_posts = [
{"likes": 21, "Comments": 2},
{"likes": 13, "Comments": 2, "Shares": 1},
{"likes": 33, "Comments": 8, "Shares": 3},
{"Comments": 4, "Shares": 2},
{"Comments": 1, "Shares": 1},
{"likes": 19, "Comments": 3},
]

total_like = 0

#
# for post in facebook_posts:
# try:
# post_likes = post['likes']
# except KeyError:
# post_likes = 0
# finally:
# total_like = total_like + post_likes
# print(total_like)

for post in facebook_posts:
try:
total_like = total_like + post['likes']
except KeyError:
pass
print(total_like)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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


def generate_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)


generate_phonetic()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
website = text_website.get()
username = text_username.get()
password = text_password.get()

new_data = {
website: {
"email": username,
"password": password,
}
}


try:
with open("data.json", "r") as fp:
data = json.load(fp)
except FileNotFoundError:
with open("data.json", "w") as fp:
json.dump(new_data, fp, indent=4)
else:
data.update(new_data)
with open("data.json", "w") as fp:
json.dump(data, fp, indent=4)
print(data)
finally:
text_website.delete(0, END)
text_password.delete(0, END)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def search():
website = text_website.get()
try:
with open("data.json", 'r') as fp:
data = json.load(fp)
# website_infos = data[website]

except FileNotFoundError:
messagebox.showinfo(message="no data yet")
# except KeyError:
# messagebox.showinfo(message=f"no password stored for {website}")
else:
if website in data:
website_infos = data[website]
email_info = website_infos["email"]
password_info = website_infos["password"]
messagebox.showinfo(title=website, message=f"email: {email_info}\npassword: {password_info}")
pyperclip.copy(password_info)
else:
messagebox.showinfo(message=f"no password stored for {website}")
# email_info = website_infos["email"]
# password_info = website_infos["password"]
# messagebox.showinfo(title=website, message=f"email: {email_info}\npassword: {password_info}")
# pyperclip.copy(password_info)

day 31

https://en.wiktionary.org/wiki/Wiktionary:Frequency_lists
https://github.com/hermitdave/FrequencyWords

google excel
=GOOGLETRANSLATE(A2,"fr","en")

https://cloud.google.com/translate/docs/languages?hl=zh-cn

1
2
3
4
5
6
7
8
9
10
11
12
French,English
partie,part
histoire,history
chercher,search
seulement,only
police,police
pensais,thought
aide,help
demande,request
genre,kind
mois,month
frère,brother
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import random
from tkinter import *
import pandas

BACKGROUND_COLOR = "#B1DDC6"

current_card = {}
try:
data = pandas.read_csv("data/words_to_learn.csv")
except FileNotFoundError:
data = pandas.read_csv("data/french_words.csv")

# to_learn = data.to_dict() # {'French': {0: 'partie', 1: 'histoire',...}, 'English': {0: 'part', 1: 'history', 2:
to_learn = data.to_dict(orient="records") # [{'French': 'partie', 'English': 'part'}, {'French': 'histoire', ...


def is_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()


def next_card():

# print(to_learn)
global current_card
current_card = random.choice(to_learn)
french_word = current_card["French"]

canvas.itemconfig(title, text="French", fill="black")
canvas.itemconfig(word, text=french_word, fill="black")
canvas.itemconfig(card_bg_img, image=card_front_img)

global flip_timer
window.after_cancel(flip_timer)
flip_timer = window.after(3000, func=flip_card)


def flip_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)


window = Tk()
window.title("Flashy")
window.config(padx=50, pady=50, bg=BACKGROUND_COLOR)

flip_timer = window.after(3000, func=flip_card)

canvas = Canvas(width=800, height=526)
canvas.config(bg=BACKGROUND_COLOR, highlightthickness=0)
canvas.grid(row=0, column=0, columnspan=2)

card_front_img = PhotoImage(file="images/card_front.png")
card_back_img = PhotoImage(file="images/card_back.png")
card_bg_img = canvas.create_image(400, 263, image=card_front_img)

title = canvas.create_text(400, 150, text="Title", font=("Ariel", 40, "italic"))
word = canvas.create_text(400, 263, text="word", font=("Ariel", 60, "bold"))

wrong_img = PhotoImage(file="images/wrong.png")
unknown_button = Button(image=wrong_img, command=next_card)
unknown_button.config(highlightthickness=0)
unknown_button.grid(row=1, column=0)

right_img = PhotoImage(file="images/right.png")
known_button = Button(image=right_img, command=is_known, highlightthickness=0)
known_button.grid(row=1, column=1)

next_card()

window.mainloop()

day 32

Alt text

1
2
3
4
5
6
7
8
9
10
import smtplib

my_email = "lcftest323@gmail.com"

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()

data_of_birth = dt.datetime(year=1996, month=5, day=21, hour=8,)
print(data_of_birth) # 1996-05-21 08:00:00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import datetime as dt
import random
import smtplib

weekday_of_today = dt.datetime.now().weekday()

with open("quotes.txt", "r") as fp:
quotes = fp.readlines()
print(quotes)
if weekday_of_today == 3:
today_quote = random.choice(quotes)
print(f"Subject:Hello\n\n{today_quote}")
my_email = "lcftest323@gmail.com"

# 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=f"Subject:Hello\n\n{today_quote}")

day 33

1
2
3
4
5
6
def get_quote():
response = requests.get(url="https://api.kanye.rest/")
response.raise_for_status()
data = response.json()
quote = data["quote"]
canvas.itemconfig(quote_text, text=quote)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import smtplib
import time
import requests
from datetime import datetime

MY_LAT = 30.018256
MY_LONG = 115.928905

def is_dark():
parameters = {
"lat": MY_LAT,
"lng": MY_LONG,
"formatted": 0,
}

response = requests.get(url="https://api.sunrise-sunset.org/json", params=parameters)
response.raise_for_status()
data = response.json()
print(data)
sunrise = data["results"]["sunrise"]
sunset = data["results"]["sunset"]

sunrise_time_hour = int(sunrise.split("T")[1].split("+")[0].split(":")[0])
sunset_time_hour = int(sunset.split("T")[1].split("+")[0].split(":")[0])
time_now_hour = datetime.now().hour
print(time_now_hour)
if time_now_hour >= sunset_time_hour or time_now_hour <= sunrise_time_hour:
return True
else:
return False


def is_near_home():
response = requests.get(url="http://api.open-notify.org/iss-now.json")
print(response.status_code)
response.raise_for_status()

data = response.json()
print(type(data))
print(data["iss_position"])
longitude = float(data["iss_position"]["longitude"])
latitude = float(data["iss_position"]["latitude"])

iss_position = (longitude, latitude)
print(iss_position)
print(iss_position)
if iss_position[0] <= MY_LAT + 5 and iss_position[0] >= MY_LAT - 5 and iss_position[1] <= MY_LONG + 5 and iss_position[1] >= MY_LONG -5:
return True
else:
return False

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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# type hints


# age: int
# name: str
# height: float
# is_human: bool


def police_check(age: int) -> bool:
if age > 18:
can_drive = True
else:
can_drive = False
return can_drive


if police_check(20):
print("pass")

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from question_model import Question
from data import question_data
from quiz_brain import QuizBrain
from ui import QuizInterface


question_bank = []
for question in question_data:
question_text = question["question"]
question_answer = question["correct_answer"]
new_question = Question(question_text, question_answer)
question_bank.append(new_question)


quiz = QuizBrain(question_bank)


ui = QuizInterface(quiz)
# while quiz.still_has_questions():
# quiz.next_question()

print("You've completed the quiz")
print(f"Your final score was: {quiz.score}/{quiz.question_number}")

quizbrain.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import html

class QuizBrain:

def __init__(self, q_list):
self.question_number = 0
self.score = 0
self.question_list = q_list
self.current_question = None

def still_has_questions(self):
return self.question_number < len(self.question_list)

def next_question(self):
self.current_question = self.question_list[self.question_number]
self.question_number += 1
q_text = html.unescape(self.current_question.text)
# user_answer = input(f"Q.{self.question_number}: {q_text} (True/False): ")
# self.check_answer(user_answer)
return f"Q.{self.question_number}: {q_text} (True/False): "


def check_answer(self, user_answer):
correct_answer = self.current_question.answer
if user_answer.lower() == correct_answer.lower():
self.score += 1
# print("You got it right!")
return True
else:
# print("That's wrong.")
return False

# print(f"Your current score is: {self.score}/{self.question_number}")
# print("\n")


ui.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
THEME_COLOR = "#375362"
from tkinter import *
from quiz_brain import QuizBrain

class QuizInterface:

def __init__(self, quiz: QuizBrain):
self.quiz = quiz
self.window = Tk()
self.window.title('quiz')
self.window.config(padx=20, pady=20, bg=THEME_COLOR)
self.score_label = Label(text="This is old text", fg="white", bg=THEME_COLOR)
self.score_label.grid(column=1, row=0)

self.canvas = Canvas(width=300, height=250, bg="white")
self.question_text = self.canvas.create_text(
150,
125,
width=280,
text="test question",
font=('Arial', 20, "italic"),
fill=THEME_COLOR)
self.canvas.grid(column=0, row=1, columnspan=2, pady=50)

true_img = PhotoImage(file="images/true.png")
self.true_button = Button(image=true_img, highlightthickness=0, command=self.answer_true)
self.true_button.grid(column=0, row=2)

false_img = PhotoImage(file="images/false.png")
self.false_button = Button(image=false_img, highlightthickness=0, command=self.answer_false)
self.false_button.grid(column=1, row=2)

self.get_next_question()
self.window.mainloop()

def get_next_question(self):
self.canvas.config(bg="white")
if self.quiz.still_has_questions():
q_text = self.quiz.next_question()
self.canvas.itemconfig(self.question_text, text=q_text)
self.score_label.config(text=f"Score: {self.quiz.score}")
else:
self.canvas.itemconfig(self.question_text, text="end of the quize")
self.true_button.config(state="disabled")
self.false_button.config(state="disabled")


def answer_true(self):
is_right = self.quiz.check_answer("True")
self.get_feedback(is_right)

def answer_false(self):
is_right = self.quiz.check_answer("False")
self.get_feedback(is_right)



def get_feedback(self, is_right):
if is_right:
self.canvas.config(bg="green")
else:
self.canvas.config(bg="red")
self.window.after(1000,self.get_next_question)