text stringlengths 37 1.41M |
|---|
"""
1:Kevin
2:Guang Zhu Cui
3:Ze Yue
"""
"""
Project: Team Work
1. Each team member generate 5K entry of data
Description:
Generate a 5K lines of record and save them into a CSV file
Each entry should record such information as:
StudentID, First Name, Last Name, DateOfBirth, ClassNo, GPA
Sample:
20180001, fn-Bill, ln... |
"""
[Homework]
Date: 2021-02-21
1. Write a GUI program of Label counter for implementing version 3.
Requirements:
(Function)
When the number reaches 10, then it comes to stop and displays the text of 'END'.
If a user clicks to close the main window, the program terminates.
(UI)
Using the layout manager of pack() for th... |
"""
for loop ex
"""
# sum from 1..1000
sum = 0
for i in list(range(1,1001)):
sum = i + sum
print("The sum of the sequence is {}".format(sum))
sum = 0
for i in range(1,1001):
# sum = i + sum
sum += i
print("The sum of the sequence is {}".format(sum))
# prod from 1..20
prod = 1
for i in range(1,21):
... |
"""
Homework 3
"""
# 1.
dict1 = {1: 'a', 2: 'b', 3: 'c'}
dict2 = {}
def dictchecker(dictionary):
if len(dictionary) == 0:
return "Length is 0"
else:
return "Length is not 0"
print(dictchecker(dict1))
print(dictchecker(dict2))
# 2.
def square(num):
mydict = {key: key * key for key in r... |
"""
app: unit converter
ver: 1
author: Yi
"""
def kilometers_miles(x):
s = x * 0.621371
return s
def miles_kilometers(x):
s = x * 1.609344
return s
def fahrenheit_celsius(x):
s = (x - 32) * 5/9
return s
def celsius_fahrenheit(x):
s = (x * 9/5) + 32
return s
def kilogram_pound(x):
... |
"""
boolean value
boolean literal
"""
bool1 = True
bool2 = False
print("bool1=", bool1)
print("bool2=", bool2)
# True => 1
print(True + 1)
print(True == 1)
# False => 0
print(False == 0)
print(False + 1)
|
"""
Calculate the GPA for every student and print out the report properly
export as a text file
"""
try:
csvfile1 = open("File_CSV_1.csv")
csvfile2 = open("File_CSV_2.csv")
csvfile3 = open(r"C:\Users\Li\PycharmProjects\stem1401python\py201011\File_CSV_3.csv")
stugpas = open("studentGPAs.txt", "w")
... |
"""
1. Write a program to generate a list.
selecting all even numbers from 1 to 100, and then generate a list in which each item is square of the corresponding even number.
Hints: Using list comprehension
Sample: [1,2,3,4,5,6,7,...100]
Expected Result: [ 4, 16, 36, 64, 100, ... , 10000]
2. Write a program to generate ... |
"""
"""
# how to create
list1 = []
list2 = [1,2,3]
list3 = list(list2) # clone
list4 = list3 # reference
# how to access items in a list
# by index
nested_list = [[1,2,3],[1,2,3],[1,2,3]]
print(nested_list[0][0])
# negative index
# slicing
list5 = [1,2,34,6,6,67,7,8,8,9,9]
print(list5[2:5])
print(list... |
"""
2021-04-11
quiz 5
Due date by the end of next saturday
"""
"""
q1
b
q2
<class 'int'>
<class 'float'>
<class 'complex'>
"""
# q3
# floating numbers
f = 1.5
print('The data type of f is',type(f))
print(isinstance(f, float))
f = 2.5
print('The data type of y is',type(f))
print(isinstance(f, int))
# integers
a = 10
p... |
"""
module: datetime
class: timedelta
"""
from datetime import datetime, date
# case1
# 2020-06-01
t1 = date(year=2020, month=6, day=1)
# 2019-06-01
t2 = date(year=2019, month=6, day=1)
dt = t1 - t2
print(f"delta time is {dt}")
# case2
# 2020-06-01
t3 = datetime(year=2020, month=6, day=1, hour=8, minute=10, secon... |
"""
place and show two image label
1. png image
2. gif image
"""
from tkinter import *
root = Tk()
root.title("Python GUI - Homework images")
# 16:9
window_width = 1200
window_height = 675
# window centered
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
x = int(screenwidth/2 - win... |
"""
12. Write a Python program to count the occurrences of each word in a given sentence.
problem: performance
option 1.
remove duplicated items before counting
option 2.
remove duplicated items during counting
"""
"""
plan
1. write sentence
2. split sentence and get the list of word
3. count each word
iterate
... |
"""
file cursor
seek()
tell()
"""
try:
file = open("homework/myweb.html")
content = file.read()
print(content)
print("=================",end="\n")
# read from start
file.seek(0)
content2 = file.read()
print(content2)
print("=================")
file.close()
print("\n\n... |
"""
converting oct to dec
converting dec to oct
8^n result
8^0 1
8^1 8
8^2 64
8^3 512
"""
# oct -> dec
c1 = 0o2345
print(c1)
# dec -> oct
d1 = 1253
print(oct(d1))
print(oct(1253))
|
"""
exception handling
else clause
try:
pass
finally:
pass
finally - close resources, release resources
"""
try:
num = int(input("Enter a integer:"))
if num <=0:
raise ValueError("That is not a positive integer")
except ValueError as ve:
print(ve)
finally:
print("this is finally cl... |
"""
Homework 14
Date: 2021-04-10
Design and write program for a login form
Requirements:
A GUI interface
Preset the username is 'admin' and the password is '123456'
User may input username
User may input password, and the password should show mask char ('*') instead
If the user's input matches the presetting, then the... |
"""
literal string
"""
str1 = "Hello Python World!"
print(str1)
print("str1 is", str1)
print()
str2 = 'Hello Python World'
print(str2)
print("str2 is", str2)
print()
# please give a name to your website
# www.athensoft.com
website_url = 'www.athensoft.com'
print(website_url)
print()
# www stands for world wide web
... |
import re
def is_number(num):
pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
result = pattern.match(num)
if result:
return True
else:
return False
print(is_number(str(-12.0))) |
"""
Homework 11
"""
# 1.
# ?
# Tuples are immutable
# 2.
mylist = [1, 1, 5, 4, 2, 6, 9, 7, 5, 4, 6]
def duplicate(num_list):
for i in num_list:
count = num_list.count(i)
for x in range(count - 1):
num_list.remove(i)
return num_list
print(duplicate(mylist))
# 3.
mylist = []
... |
"""
filter()
mylist1 = [1,2,3,4,5,6,7,8,9,10]
even number
expect result = [2,3,4,8,10]
"""''
mylist1 = [1,2,3,4,5,6,7,8,9,10]
print("The original list is: ",mylist1)
result = []
for i in mylist1:
if i % 2 == 0:
result.append(i)
print("The result is: ", result)
# using lambda function with filter()
pri... |
"""
variable function arguments
"""
"""
output Good morning, your_friend_name!
friend1 = f1
friend2 = f2
friend3 = f3
friend4 = f4
"""
def greeting(words, name):
print("{}, {}!".format(words, name))
# 1st
greeting("Good morning", 'f1')
# 2nd
greeting("Good morning", 'f2')
# 3rd
greeting("Good morning", 'f3')... |
"""
nested for loop
"""
# create a matrix by 3X4
matrix = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
for row in matrix:
# print(row)
for item in row:
print(item)
|
"""
rmdir() - remove an empty directory
"""
import os
try:
dirpath = "testdir"
if os.path.exists(dirpath):
os.rmdir(dirpath)
except FileNotFoundError as fe:
print(fe)
except Exception as e:
print(e)
print("done.") |
"""
q3. max number
"""
list1 = [1, 2, 20, 3, 2, 4, 16, 15]
max = list1[0]
for num in list1:
if num > max:
max = num
print("max = ", max)
|
"""
delete/remove element from a list
"""
# 1. del
my_list = ['p','r','o','b','l','e','m']
# remove one element
del my_list[2]
print(my_list)
# remove multiple elements
del my_list[1:5]
print(my_list)
# remove entire list
del my_list[:]
print(my_list)
# del my_list
# print(my_list)
# empty a list
my_list = ['p','... |
"""
catching specific exception
one try block
multiple exception blocks
"""
print("=== start ===")
mylist = ['5','a','0','2','3']
for value in mylist:
try:
result = 1 / int(value)
print(result)
print()
except ValueError:
print("ValueError")
print()
except ZeroDivi... |
"""
[Homework]
1. Write a Python program to read an entire text file.
2. Write a Python program to read the first n lines of a file.
5. Write a Python program to read a file line by line and store it into a list.
8. Write a python program to find the longest words.
""" |
"""
Locale's appropriate date and time
Format codes %c, %x and %X are used for locale's appropriate date and time representation.
"""
from datetime import datetime
now = datetime.now()
timestamp = now.timestamp()
date_time = datetime.fromtimestamp(timestamp)
d = date_time.strftime("%c")
print("Output 1:", d)
d =... |
"""
list slicing
"""
mylist = [1,2,3,4,5,6,7,8,9]
# case 1. slicing from the most left
res = mylist[0:5]
print("mylist[0:5]",res)
# 1..5
x = mylist[:5]
print("mylist[:5]",x)
# ex. slicing for 1..8
# leon
# x = mylist[0:7}
# Print(x)
x = mylist[0:8]
print(x)
# youran
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
resu... |
"""
Assignment operators
assignment expression : from right to left
symbol: =
compared with ==
"""
a = 100
x = y = z = 6
# z = 6
# y = 6
# x = 6
# Compound operator
# 1. arithmetic operator and assignment operator -> compound operator
# 2. bitwise operator and assignment operator -> compound operator
x = 6... |
"""
mini calculator
user can input option (adding, subtracting, mul, div, //, %, **)
to perform arithmetic operation
user can input option (logical and, or, not)
to perform logical operation
after user selected one option of operation, he/she is asked to input operand(s)
The system print out the result with necess... |
"""
slicing
"""
mylist = ['a','b','c','d','e','f','g','h']
# case 1. from 0..('e')
print(mylist[0:5])
print(mylist[:5])
print()
# case 2. from ('f')..end
print(mylist[5:len(mylist)-1+1])
print(mylist[5:8])
print(mylist[5:-1]) # error
print(mylist[5:])
# case 3. from ('c')..('f')
print(mylist[2:6])
# case 4.
print(... |
"""
"""
def foo():
x = "hi"
x = x * 2
print(x)
x = "global"
foo()
print(x)
# x = "global"
# x = x * 2
# print(x)
# def foo3():
# y = 9
# print("y={}".format(y))
#
# foo3()
# print("y={}".format(y)) |
"""
the full syntax of exception handling
"""
"""
try:
pass
except:
pass
else:
pass
finally:
pass
"""
try:
num = int(input("Input a number:"))
if num <= 0:
raise ValueError(f"invalid literal for positive int with base 10:'{num}'")
except ValueError as ve:
print(ve)
else:
prin... |
from tkinter import *
root = Tk()
root.title("Calculator")
root.geometry("800x500+200+200")
root.config(bg="gray85")
root.resizable(1, 1)
font = ("Helvetica", 16)
expression: str = ""
expression_answer = ""
display_Label = Label(text=expression, width=63, height=3, bg="gray85", relief="raised", padx=5, anchor=E, font=... |
"""
"""
# create or declare a dictionary
mydict = {
"a":5,
"b":3,
"c":6
}
print(mydict)
#
mydict["d"] = 8
print(mydict)
|
"""
Quiz
Write a program to rename multiple files in a specific directory
date : 2020-11-29
author : Kevin Liu
"""
import os
# instruction of program
print("This program allows you to change rename multiple files in a specific directory.")
#
specified_directory = input("Please enter the full path of the desired di... |
"""
Event binding and handling
button
"""
from tkinter import *
def attack(event):
print('This is a normal attacking action.')
print(event.x,event.y)
root = Tk()
root.title('Python | Event handling')
root.geometry("640x480+200+200")
btn1 = Button(text='My Btn 2')
btn1.pack()
btn1.bind('<Button-1>',attac... |
"""
Project 3 v 1.1
"""
global_var = ""
def length_choice():
global global_var
print()
print("Press 1 to convert meters into inches.")
print("Press 2 to convert inches into meters.")
user_choice_1 = int(input("Input your choice: "))
global_var = user_choice_1
def temperature_choice():
gl... |
mylist = [3, 8, 1, 6, 0, 8, 4]
mylist.pop(1)
mylist.insert(2,1)
target = 8
if target in mylist:
print(mylist.index(target))
else:
print(None)
#
mylist = [3, 8, 1, 6, 0, 8, 4]
indexes = [index for index in range(len(mylist)) if mylist[index] == 8]
print(indexes) |
"""
app: unit converter
ver: 3
author: Yi
"""
def kilometers_miles(x):
s = x * 0.621371
return s
def miles_kilometers(x):
s = x * 1.609344
return s
def fahrenheit_celsius(x):
s = (x - 32) * 5/9
return s
def celsius_fahrenheit(x):
s = (x * 9/5) + 32
return s
def kilogram_pound(x):
... |
"""
python statement
1. Instruction
2. Basic unit of program
"""
# assignment statement
a = 1
# call a function
print("abc")
# if statement
if 3<6:
pass
# for statement
for i in [12,34,45]:
pass
# while statement
while True:
break
# End of a statement
# ;
a = 1;
b = 2;
a = 1
b = 2
# multiple state... |
"""
access dictionary value
"""
dict2_en = {
"mon": "Monday",
"tue": "Tuesday",
"wed": "Wednesday",
"thu": "Thursday",
"fri": "Friday",
"sat": "Saturday",
"sun": "Sunday"
}
# access value via key of a dictionary
v_mon = dict2_en["mon"]
print("v_mon is {}".format(v_mon))
|
"""
Project_3
menu 2
"""
"""
km_m
km to meter ?
km to mile ?
"""
# Time
def min_hour(x):
return x / 60
def min_sec(x):
return x * 60
def hour_min(x):
return x * 60
def hour_sec(x):
return x * 3600
def sec_hour(x):
return x / 3600
def sec_min(x):
return x / 60
# Temperature
def ce... |
"""
string
A string is a sequence of characters.
char = alphabet, digit, symbol, punctuation
immutable
discovery
C - string is not a primitive type
Java - string is reference type
"""
# create a string
str1 = 'hello'
print(str1)
# string v.s. tuple
# immutable, ordered
('h','e','l','l','o')
# use a string as a... |
"""
String methods - case
Python String capitalize() [yes]
Converts first character to Capital Letter
Python String casefold() [no1]
converts to case folded strings
Python String islower() [yes]
Checks if all Alphabets in a String are Lowercase
Pyt... |
"""
Homework 9
"""
import random
from py201107.errors import *
randint = random.randint(1, 100)
guess = 0
print("Guess a number between 1 and 100")
for i in range(8):
guess += 1
valid = False
while not valid:
try:
print()
num = int(input("Please enter a number: "))
... |
"""
methods of tuple
count(x) - return occurrence times of x in the tuple
index(x) - return the first occurrence of x in the tuple
index(x, start)
index(x, start, end)
"""
tuple1 = (1,1,2,2,2)
# count(x)
num_1 = tuple1.count(1)
num_2 = tuple1.count(2)
print(num_1)
print(num_2)
print()
# index(x)
pos_1 = tuple1.index... |
"""
dict
create
key: immutable value
number
string
tuple
other immutable type
"""
# create a normal dictionary
dict1 = {
1: 'a',
2: 'b',
3: 'c'
}
print(dict1)
# output {1: 'a', 2: 'b', 3: 'c'}
# question
# one value for one key
# key must be unique
# values are not neccessary different
... |
"""
Literal collections
A collection is a group of items
1. list
2. tuple
3. set
4. dict (dictionary)
"""
a = 1
b = 2
x = 55
# list
array_odd = [1,3,5,7,9,10]
odd0=1
odd1=3
#
# len()
length = len(array_odd)
print(array_odd)
print('length=',length)
# index - position of item in the list
# index starts from 0
... |
"""
list and lambda
"""
mylist = [1,2,3,4,5]
def f(n):
return lambda list1 : list1[n] * 2
result = f(1)
print(result(mylist))
|
"""
[Homework]
Date: 2021-04-10
Design and write program for a login form
Requirements:
A GUI interface
Preset the username is 'admin' and the password is '123456'
User may input username
User may input password, and the password should show mask char ('*') instead
If the user's input matches the presetting, then the p... |
"""
iterating through a tuple
"""
for name in ('John','Kate', 'Peter', 'Jack', 'Kevin'):
print("Hello",name)
|
"""
score
no docstring of comment (-5)
"""
import tkinter
import time
root = tkinter.Tk()
root.title("Homework, Label")
image = False
if image:
root.iconbitmap(image)
w_width = int(input("Please enter the desired width for your widget: "))
w_height = int(input("Please enter the desired height for your wid... |
"""
[Homework]
1. Write a Python program to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
e.g. User inputs 5
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
2. Write a program to sort a dictionary by key in both ascending and descending order.
3. Write a program to s... |
"""
list sort
"""
# case 1. simple list
mylist = [1,4,3,5,3,5,6,7,8,9,0,2]
mylist.sort()
print(mylist)
# case 2. nested list (matrix)
mylist2 = [[4,'a'],[8,'b'],[2,'c'],[1,'d']]
mylist2.sort()
print(mylist2)
print()
# case 3. sorting by specified column(key)
# solution 1.
# basic idea: let the key be the first o... |
"""
isnumeric()
returns True if all characters in a string are numeric characters.
If not, it returns False.
"""
# Example 1
s = '1242323'
print(s.isnumeric())
#s = '²3455'
s = '\u00B23455'
print(s.isnumeric())
# s = '½'
s = '\u00BD'
print(s.isnumeric())
s = '1242323'
s='python12'
print(s.isnumeric()) |
"""
[Homework] 2021-01-06
Read all content from a text file and write them into another file at the same location
to optimize the code to make it safer
"""
try:
# sub-problem 1
file1 = open('datasource.txt')
content = file1.read()
print(content)
# sub-problem 2
file2 = open('datadest.txt',... |
"""
biggest item in list
"""
list1 = [1, 2, 3, 4, 5]
list1.sort(reverse=True)
print(list1[0])
#
list1 = [1, 2, 3, 4, 5]
list1.sort()
print(list1[-1])
|
"""
dictionary removing elements from a dictionary
pop() - removes an item with the provided key and returns the value
popitem() - can be used to remove and return an arbitrary (key, value) pair
clear() - remove all items
"""
months = {'Jan': 'January',
'Feb': 'February',
'Mar': 'March',
... |
"""
datatype
"""
# numbers
# number - integer
i1 = 1000
print("i1=",i1, type(i1))
print("i2=",123, type(123))
# number - float
f1 = 1.23
print(f1, type(f1))
print(f1, type(1.23))
# string
s1 = "abc"
print(s1, type(s1))
# string, str
# boolean
b1 = True
b2 = False
print(b1, type(b1))
print(b2, type(b2))
# bool... |
"""
literal - string
is a sequence of characters surrounded by quotes.
"""
# string literal
str1 = 'abc'
str2 = "abc"
str3 = 'C'
str4 = 'c'
str5 = '&'
print(str3, str4, str5)
multiline_str = """This is a multiline string with
more than one line code."""
print(multiline_str)
print()
multiline_str2 = '''This is... |
"""
Test user-defined errors
"""
# user input a number from a keyboard
# if it is > 100, then raise an error
# if it is < 1, then raise an error also
import sj200917_python2m6.day09_201112.myerrors as err
print("Please enter a number from 1 to 100: ", end="")
num = int(input())
try:
if num> 100:
raise... |
"""
dictionary Counter
"""
# candidate 1, 2
# vote by state
# candidate1
# A state : 50
# B state : 45
# C state : 70
# candidate2
# A state : 60
# B state : 50
# C state : 40
from collections import Counter
# import collections
# state A
vote_state_a = {
'c1' : 50,
'c2' : 60
}
# state B
vote_state_b = ... |
"""
Tkinter
using grid layout
grid()
rowspan, columnspan
merge cells
"""
from tkinter import *
root = Tk()
root.geometry('320x240+200+200')
root.config(bg='#ddddff')
# create label widgets
label1 = Label(root, text='Label 0,0',bg='yellow')
label2 = Label(root, text='Label 0,1')
label3 = Label(root, text='Label 1,1... |
"""
[Homework] 2021-01-23
Create your own window
requirements:
1. make it at center point on your screen
2. specify dimension at 16:9
3. set a background color
4. make it topmost
5. make it non-resizable
6. print out the window's height and width at console
Due date: by the end of next Friday
"""
import tkinter as tk... |
"""
[Homework]
Date: 2021-03-08
1. Write a GUI program of clock
Requirements:
(Function)
Show current time in the pattern of HH:mm:ss.aaa
i.e.
10:12:45.369
(UI)
Display a title, main area for clock, and footer for the date
Due date: by the end of next Friday
Hint:
import datetime
strftime
"""
"""
score:
footer, improp... |
"""
[Homework]
Date: 2021-07-29
please write a program to get the product of
1x2x3x4x5x6x7x8x9x10
hints:
for-loop
"""
# sum = 1
#
# for i in range(1, 11):
# sum = sum * i
#
# print(sum)
product = 1
for i in range(1, 11):
product = product * i
print(product)
|
def OR(num_1, num_2):
return num_1 or num_2
print(OR((float(input('Please enter the or:')),float(input('Please enter the other or:'))))) |
"""
change value(s) of items from a list
"""
odd = [2, 4, 6, 8]
# update value
odd[0] = 1
print(odd)
# update multiple items at one time
odd[1:4] = [3,5,7]
print(odd)
|
"""
Printing out a which is 3x4 so 3 rows and 4 columns
"""
a = [
["Magic", "Nothing", "Hello", "Crocodile"],
[1, 2, 3, 4],
["Simple", "Math", "French", "Science"]
]
print(a) # printing the entire matrix
print(a[0]) # printing the first row of the matrix
print(a[0][2]) # printing the element "Hello" fro... |
"""
3 step to operate on a file
step 1. Open a file
step 2. Read/Write (perform operation)
step 3. Close the file
"""
# open()
try:
file = open('text1.txt1')
print(file)
except FileNotFoundError as fe:
print(fe)
|
"""
String formatting
print()
format()
with named parameter
"""
width = 2560
height = 1600
# solution 2
print("My screen resolution is {0} x {1}".format(width, height))
# solution 3.
# your code goes here
# Andy
print('My screen resolution is {my_width} x {my_height}'.format(my_width=width, my_height=height))
# L... |
"""
[Homework]
Date: 2021-02-06
1. Try out label widget
Description:
- create a window based on previous homework
- set icon, title, dimension, maxsize, minsize, bg and any other options for the window as much as you know
- create a text Label
"""
import tkinter as tk
import time
root = tk.Tk()
root.title("Christmas... |
"""
how to validate the number and make it within your upper and lower bound
"""
"""
x = int(input("enter a number (1-100):"))
if x > 100 or x <1:
print("Warning: Please input a valid number!")
else:
print("Your input is {}".format(x))
"""
# Leon - do-while v.s. while
def inputValidNumber():
x = ''
... |
"""
Ze Yue Li
7/7/2020
Exercises on Dictionary
1. Write a Python script to sort (ascending and descending) a dictionary by value.
2. Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}
3. Write a Python script to concatenate following dictionari... |
"""
Symmetric difference
(A - B) | (B - A)
"""
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
result = A.symmetric_difference(B)
result2 = B.symmetric_difference(A)
print(result)
print(result2)
# solution2
result3 = (A - B) | (B - A)
print(result3)
|
"""
q3
"""
total_score = 0
average = 0
a_num = 0
scores = [85, 78, 96, 85, 73, 59, 45, 97, 89, 90]
num_people = len(scores)
for num in scores:
total_score = total_score + num
if num >= 90:
a_num += 1
average = total_score / num_people
print("Average score is {:.1f}".format(average))
print("{} stude... |
"""
anchor of Label widget
anchor = n, s, w, e, ne, nw, se, sw, center
"""
import tkinter as tk
root = tk.Tk()
root.title('Python GUI - Label')
winw= 640
winh= 480
posx=300
posy=200
root.geometry(f'{winw}x{winh}+{posx}+{posy}')
root.config(bg='#ddddff')
# create a Label
label1 = tk.Label(root, text='My Text Label... |
"""
creating dictionary based on other dictionary
"""
# case 1. literal of dictionary
# dict()
my_dict = dict({1:'apple', 2:'orange'})
print(my_dict)
# case 2. compatible data structure
my_dict = dict([[3,'apple'],[4,'orange']])
print(my_dict)
|
"""
list comprehension
"""
# case 1.
# [1,2,3,4,5] get a new list by doubling each item
mylist = [1,2,3,4,5]
# solution 1. for-loop
newlist = []
for i in mylist:
newlist.append(i*2)
print(newlist)
# solution 2. map()
newlist = list(map(lambda item: 2*item, mylist))
print(newlist)
# solution 3. list comprehen... |
"""
Homework
"""
"""
score
perfect
"""
from tkinter import *
root = Tk()
root.title("Python GUI - Homework")
win_width = 640
win_height = 480
positionRight = int(root.winfo_screenwidth() / 2 - win_width/2 )
positionDown = int(root.winfo_screenheight() / 2 - win_height/2 )
root.maxsize(900, 600)
root.minsize(100,... |
"""
[Homework]
2021-02-28
Show and Hide a label in a window
Due date: By the end of next Sat.
"""
"""
score:
one minor logic defect (-5)
"""
from tkinter import *
def hide(widget):
return lambda: Pack.forget(widget)
def show(widget):
return lambda: widget.pack(side=LEFT)
root = Tk()
root.title("Python GU... |
str1 = "The quick brown fox jumps over the lazy dog"
dumb = str1.split()
yet = int(input("Please input a number:"))
str2 = []
for i in dumb:
if len(i) > yet:
str2.append(i)
print(str2)
|
"""
float number
decimal point
"""
f1 = 1.5
f2 = -1.56
# type()
print(type(f1), f1)
d1 = 100
print(type(d1), d1)
# scientific
s1 = 15000000000
# s1 = 1.5X10^10
s1 = 1.5e10
print(s1)
s2 = 15
s2 = 1.5e1
print(s2)
print(int(s2))
s3 = 0.15
s3 = 1.5e-1
print(s3)
s4 = 0.0015
s4 = 1.5e-3
print(s4)
|
"""
2. Write a Python function that takes two lists and returns True
if they have at least one common member.
"""
# create two lists
list1 = ['x','2','c']
list2 = ['a','2','3']
#
for item in list1:
result = item in list2
if result:
print(f'the common member is {item}')
break
|
"""
2021-03-21
Create a set with 8 items
A story or topic must be applied as you did with list in class
Create a dictionary with 8 pairs of key and value
A story or topic must be applied as you did with list in class
"""
instrument_dict = {1: 'trumpet', 2: 'trombone', 3: 'guitar', 4: 'sax', 5: 'clarinet', 6: 'bass', 7... |
"""
list method
index()
"""
# student list of last year
stulist = [101,102,103,104,201,202,203,204,205,301,302,303,304]
# get the position of student 201 in the list
stu_no = 201
print("The student {} is at stulist[{}]".format(stu_no,stulist.index(stu_no)))
# get the position of student 201 in the list
stu_no = 301
... |
"""
Number guessing AI v1.1
Ze Yue Li
2020-06-27
猜数字的AI
和猜数字一样,不过这次是设计一个能猜数字的AI
功能描述: 用户输入一个单位以内的数字,AI要用最少的次数猜中,并且显示出猜的次数和数字。
"""
def input_num(message, smallerthan=-1, greaterthan=0):
num = input(message)
while not num.isdigit():
num = input(message)
while int(num) < greaterthan or int(num) > sma... |
"""
Homework 10
"""
import random
normal = 0
magic = 0
rare = 0
legendary = 0
ancient_legendary = 0
for i in range(1000):
chance = random.randint(1, 1000)
if chance in range(1, 638):
print('normal')
normal += 1
elif chance in range(639, 888):
print('magic')
magic += 1
... |
"""
Number Formatting Types
Type Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as 'd'. Except it uses current locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential no... |
"""
Final exam part II - Issa
1. Writing a GUI program in Python tkinter for the registration process of a network application.
Basic requirements:
a. User can input a username --> done
b. User can input a password --> done
c. User can input a password for the second time to ensure user's password was input correctly ... |
"""
generate list
combing or repeating
"""
# + operator
list1 = [1,2,3]
list2 = [4,5,6]
newlist = list1 + list2
print(newlist)
newlist = list2 + list1
print(newlist)
#
old_students = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8']
new_students = ['nm1','nm2','nm3']
namelist = old_students +... |
"""
score
not executable (-35)
missing docstring of comment (-5)
not enough white spaces (-1)
"""
import tkinter
import time
print("This program will create a widget of specified size."
" After, it is going to resize it to 500x350, then ending the program")
root = tkinter.Tk()
# window title
root.title("stem140... |
"""
show an .gif image without any gap
"""
from tkinter import *
root = Tk()
root.title('Python GUI - Label image')
root.config(bg='#ddddff')
# step 1. create an object of PhotoImage
photo_obj = PhotoImage(file='img/pimon.gif')
# step 2.
label1 = Label(root, image=photo_obj)
# step 3. place label with image into ... |
"""
string1 = 'ab'
string2 = 'xy'
['ax','ay','bx','by']
"""
string1 = 'ab'
string2 = 'xy'
# solution 1
result = []
for c1 in string1:
# print(c1)
for c2 in string2:
# print(c2)
# print(c1, c2)
print(c1+c2)
result.append(c1+c2)
print(result)
print("=================")
# sol... |
"""
1. List can make some change. And Tuple can't make change. So Tuple is safer than List, and list is very convenient.
(missing: ordered, collection of items)
2. Set is mutable, But items in set are immutable. And all items in set are unique.
Also, all items in dictionary are unique, but dictionary have 2 Column, so... |
"""
to set your window at the center point
"""
import tkinter as tk
# from tkinter import *
root = tk.Tk()
root.title('Python GUI - Position')
# set position
root.geometry('800x450-300+200')
root.iconbitmap('img/IMG_2408.ico')
# set your window at center point
root.mainloop()
|
# flow control - if statement
# 0 - 9.99 buy a knife
# 10 - 19.99 buy a armor
# 20 - 29.99 buy a pair shoes
# 30 - 39.99 buy a pendent
# 40 - 49.99 buy an earing
# 50 - 50.99 buy a ring
# 60 - 69.99 buy a sword
# 70 arena
while(True):
level = int(input("Enter your current level: "))
if level < 0:
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.