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-Gates, 1995-03-05, C301, 3.3 Field Pattern StudentID, 8-digit-number, yyyy+4-digit sequence no, 20180001 2018 to 2020, 0001 - 5000 First Name, string of prefix + 3-10 characters, 'fn-' prefix + randomly generated Last Name, string of prefix + 3-10 characters, 'ln-' prefix + randomly generated DateOfBirth, string of 8 char, yyyy-mm-dd, 2000-03-05 the range of year 1990 - 2010 ClassNo, C101, to C105, C201, to, C205 to C601 to C605, randomly generated GPA, 0 to 4.0, randomly generated, #.##, #.# Number of Records: 5,000 lines Data File Format: CSV 2. Each team member collects other two members' data file(s) in format of CSV 3. Calculate the GPA for every students and print out the report properly export as a text file summary detail 4. Consider time management schedule meeting """ import random import string # student ID def student_ID(): stuid = [] first_4_chars_student_id = str(random.randint(2018, 2020)) last_4_chars_student_id = str(random.randint(1, 5000)) stuid.append(last_4_chars_student_id) if last_4_chars_student_id in stuid: pass if len(last_4_chars_student_id) == 3: last_4_chars_student_id = '0' + last_4_chars_student_id if len(last_4_chars_student_id) == 2: last_4_chars_student_id = '00' + last_4_chars_student_id if len(last_4_chars_student_id) == 1: last_4_chars_student_id = '000' + last_4_chars_student_id student_id = first_4_chars_student_id.__add__(last_4_chars_student_id) return student_id # first name def fn(): first_name = 'fn-' len_first_name = random.randint(3, 9) a = 0 for i in range(len_first_name): first_char_fn = random.choice(string.ascii_uppercase) chars_fn = random.choice(string.ascii_lowercase) if a == 0: first_name += first_char_fn first_name += chars_fn a += 1 return first_name # last name def ln(): last_name = 'ln-' len_last_name = random.randint(3, 9) a = 0 for i in range(len_last_name): first_char_ln = random.choice(string.ascii_uppercase) chars_ln = random.choice(string.ascii_lowercase) if a == 0: last_name += first_char_ln last_name += chars_ln a += 1 return last_name # birthdate def date_of_birth(): year = str(random.randint(1990, 2010)) month = str(random.randint(1, 12)) # months = (1,3,5,7,8,10,12) # if month in months: # pass if month == '1' or month == '3' or month == '5' or month == '7' or month == '8' or month == '10' or month == '12': date = str(random.randint(1, 31)) elif month == '2': date = str(random.randint(1, 28)) else: date = str(random.randint(1, 30)) if year == '1992' or year == '1996' or year == '2000' or year == '2004' or year == '2008' and month == '2': date = str(random.randint(1,29)) if len(month) == 1: month = '0' + month if len(date) == 1: date = '0' + date birthdate = year + '-' + month + '-' + date return birthdate # class NO def class_no(): class_number = 'C' first_number_in_the_class_number = str(random.randint(1, 5)) last_number_in_the_class_number = str(random.randint(1, 5)) class_number += first_number_in_the_class_number class_number += '0' class_number += last_number_in_the_class_number return class_number # GPA def GPA(): gpa = round(random.uniform(0.1, 4.0), 2) return gpa # main try: csv_file = open('File_CSV_2.csv', 'w') csv_file.truncate(0) for i in range(1, 5001): a = '{},{},{},{},{},{}\n'.format(student_ID(), fn(), ln(), date_of_birth(), class_no(), GPA()) csv_file.write(a) except FileNotFoundError as fe: print(fe) except Exception as e: print(e) finally: csv_file.close()
""" [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 the UI. A recommended UI design is given below. """ """ score: perfect """ # import tkinter as tk from tkinter import * from tkinter.ttk import Separator def start_counting(mylabel): print("entered start_counting()") counter = 0 def counting(): nonlocal counter counter = counter + 1 if counter > 10: counter = "END" mylabel.config(text=str(counter)) if counter == "END": return mylabel.after(1000, counting) counting() # main program root = Tk() root.title('Python GUI - Label counter') root.geometry("{}x{}+200+240".format(800, 560)) root.configure(bg='#ddddff') # title label object label1 = Label(root, text="Label Counter", bg="blue", fg="white", height=2, width=100, font="Helvetic 35 bold") label1.pack() # separator sep1 = Separator(root, orient=HORIZONTAL) sep1.pack(fill=X) # counter label object digit_label = Label(root, bg="seagreen", fg='white', height=8, width=100, font="Helvetic 30 bold") digit_label.pack() # separator sep1 = Separator(root, orient=HORIZONTAL) sep1.pack(fill=X) # footer label object label2 = Label(root, text="Version 3 | Ze Yue Li | 2021-02-26", bg="red", fg="white", height=2, width=100, font="Helvetic 35 bold") label2.pack() # counting start_counting(digit_label) root.mainloop()
""" 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): prod *= i print("The prod of the sequence is {}".format(prod))
""" 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 range(1, num + 1)} return mydict print(square(5)) print(square(11)) # 3. mydict = {7: 11, 25: 12, 745: 34, 6: 86, 13: 8, 40: 58, 93: 72, 38: 66} def maxandmin(dictionary): return max(mydict.values()), min(mydict.values()) print(maxandmin(mydict))
""" 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): s = x * 2.20462 return s def pound_kilogram(x): s = x * 0.453592 return s def meter_foot(x): s = x * 3.28084 return s def foot_meter(x): s = x * 0.3048 return s print("1: Length or distance") print("2: Temperature") print("3: Weight") print("4: Area") choice = input("choice(1/2/3/4):") if choice =='1': print("1: kilometers to miles:") print("2: miles to kilometers:") choice2 = input("choice(1/2):") if choice2 =='1': c = float(input("a number")) s = kilometers_miles(c) print("the number {} * 0.621371 = {}".format(c, s)) if choice2 =='2': c = float(input("a number")) s = miles_kilometers(c) print("the number {} * 0.1.609344 = {}".format(c, s)) elif choice =='2': print("1: fahrenheit_celsius:") print("2: celsius_fahrenheit:") choice2 = input("choice(1/2):") if choice2 =='1': c = float(input("a number")) s = fahrenheit_celsius(c) print("the number {} - 32 * 5/9 = {}".format(c, s)) if choice2 =='2': c = float(input("a number")) s = celsius_fahrenheit(c) print("the number ({} * 9/5) + 32 = {}".format(c, s)) elif choice == '3': print("1: kilogram_pound:") print("2: pound_kilogram:") choice2 = input("choice(1/2):") if choice2 =='1': c = float(input("a number")) s = kilogram_pound(c) print("the number {} * 2.20462 = {}".format(c, s)) if choice2 =='2': c = float(input("a number")) s = pound_kilogram(c) print("the number {} * 0.453592 = {}".format(c, s)) elif choice == '4': print("1: meter_foot:") print("2: foot_meter:") choice2 = input("choice(1/2):") if choice2 =='1': c = float(input("a number")) s = meter_foot(c) print("the number {} * 3.28084 = {}".format(c, s)) if choice2 =='2': c = float(input("a number")) s = foot_meter(c) print("the number {} * 0.3048 = {}".format(c, s)) else: print("this option does not exist.")
""" 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") content = csvfile1.readlines() + csvfile2.readlines() + csvfile3.readlines() split_content = [] gpas = [] for i in range(len(content)): content[i] = content[i].split(",") for j in content[i]: if content[i][-1] == j: gpas.append(j[:-1]) for i in range(len(gpas)-1): try: gpas[i] = float(gpas[i]) except Exception as e: gpas.pop(i) print(gpas) sum = 0 for i in gpas: try: sum += i except Exception as e: print(e) average = sum / len(gpas) for i in gpas: stugpas.write(str(i)) stugpas.write("\n") stugpas.write(f"The average GPA is {average}") except Exception as e: print(e) finally: csvfile1.close() csvfile2.close() csvfile3.close()
""" 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 a list. There are two given string 'ABC' and 'XYZ' generating a new list like ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] Hints: Using list comprehension """ # 1 list1 = [] for i in range(1,101): list1.append(i) print(list1) result = [i**2 for i in list1 if i %2 == 0] print(result) # 2 # linear algebra string1 = 'ABC' string2 = 'XYZ' result = [] for i1 in string1: for i2 in string2: print(i1+i2) result.append(i1+i2) print(result)
""" """ # 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(list5[:5]) print(list5[5:]) print(list5[:]) # update element in a list list5[0] = 999 print(list5) list5[1:4] = [777,888,999] print(list5) # add elements list5.append('abc') print(list5) list5.extend([123,123,123]) print(list5) # + list6 = [1,2,3] list7 = [4,5,6] print(list6 + list7) print(list7 + list6) # * list6 = [1,2,3] * 3 print(list6) # insert an item list8 = [4,5,6] list8.insert(1,9) print(list8) # insert items list8[2:2] = [7,8,9] print(list8) # remove items del list8[0] print(list8) del list8[1:3] print(list8) # del list8 # print(list8) # clear() list8.clear() print("list8",list8)
""" 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 print('The data type of a is',type(a)) print(isinstance(a, int)) b = 15 print('The data type of a is',type(b)) print(isinstance(b, int)) # complex numbers b = 2+4j print('The data type of b is',type(b)) print(isinstance(b, complex)) c = 1+6j print('The data type of c is',type(c)) print(isinstance(c, complex)) # q4 boolean a = False print('The data of a is',type(a)) print(isinstance(b, bool)) # q5 a = 9 print('The data type of a is',type(a)) print(isinstance(a, int))
""" 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, second=15) # 2019-06-01 t4 = datetime(year=2019, month=6, day=1, hour=9, minute=15, second=19) dt2 = t3 - t4 print(f"delta time is {dt2}") dt3 = t4 - t3 print(f"delta time is {dt3}")
""" 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 - window_width/2) y = int(screenheight/2 - window_height/2) root.geometry(f"{window_width}x{window_height}+{x}+{y}") root.config(bg="saddle brown") # place an image label - png image png1 = PhotoImage(file='./Samoyed.png') text1 = "A .PNG image of a smiley samoyed!!!" label1 = Label(root, width=1100, height=600, bg="red4", # fg="white", # font="Verdana 12 underline", relief="solid", image=png1) label1.pack() label1_txt = Label(root, bg="red4", fg="white", text = text1, font="Verdana 12 underline") label1_txt.pack() # place an image label - gif image gif1 = PhotoImage(file='./GIF SAMOYED.gif') text2="A .GIF image of a smiley samoyed!!!" label2 = Label(root, width=1100, height=600, bg="red4", # fg="white", # font="Verdana 12 underline", relief="solid", image=gif1) label2.pack() root.mainloop()
""" 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 4. output """ # step 1. write sentence sentence = """ Public health officials reported 11 new cases of COVID-19 in Ottawa as of Saturday afternoon, a return to the double-digit case numbers that have become the norm in recent weeks. In total, the nation's capital has had 2,698 confirmed cases of the virus since the start of the pandemic. Around 86 per cent — or 2,316 — of all cases are now considered resolved, with nine of those being resolved since Friday. There are 37 fewer active cases in the city compared to last Saturday. The total number of deaths in Ottawa stands at 264, where it has remained since July 28. Twelve people remain hospitalized in Ottawa and two people are in intensive care. There are also three ongoing outbreaks at city institutions such as long-term care facilities and child-care centres. """ # clean # remove punctuations sentence = sentence.replace('.','') sentence = sentence.replace(',','') sentence = sentence.lower() print(sentence) # step 2. # split() wordlist = sentence.split() # wordset = set(wordlist) # wordset = list(wordset) print(wordlist) # print(wordlist) # step3. count """ append() - add one item to a list """ result = [] wordset = set() for word in wordlist: if word not in wordset: if not word.isnumeric(): wordset.add(word) wordcount = wordlist.count(word) # entry = (word, wordcount) entry = word, wordcount print(entry, type(entry)) result.append(entry) # print(result) # step4. output # remove duplicated items # use a dictionary """ option 1. create a dict, then put each item into the dictionary option 2. convert to dict dict() """ result.sort() print(dict(result))
""" 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") except FileNotFoundError as fe: print(fe) except Exception as e: print(e) file2 = open("homework/myweb.html") content = file2.read(4) print(content) print("=================",end="\n") # read from start file2.seek(9) content2 = file2.read(4) print(content2) print("=================") file.close()
""" 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 clause")
""" 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 program shows a text message (info) box with the words 'login successfully!' otherwise, the program shows a text message (error) box with the words 'wrong username or password!' Due date: by the end of next Friday """ from tkinter import * from tkinter.ttk import Separator def printInfo(): print(f"You've Account: {accountE.get()}"), print(f"You've Password: {passwordE.get()}") root = Tk() root.title("Python GUI - Entry") root.geometry("600x430") user = "Yi" passw = 123 # Head digit_label1 = Label(root, text="Login Form", padx='10', pady='20', font="Helvetic 30 bold") digit_label1.pack() # Separ sep = Separator(root, orient=HORIZONTAL) sep.pack(fill=X, padx=5, pady=40) # Body accountL = Label(root, text="Account :") accountL.pack() passwordL = Label(root, text="Password :") passwordL.pack() accountE = Entry(root) accountE.pack() passwordE = Entry(root, show='*') passwordE.pack() showBtn = Button(root, text='Get Account', command=printInfo) showBtn.pack() # Separ sep = Separator(root, orient=HORIZONTAL) sep.pack(fill=X, padx=5, pady=40) # Foot digit_label3 = Label(root, text="Copyright 2021 Athensoft Inc.", fg='black', font="30") digit_label3.pack() root.mainloop()
""" 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 # for one character str3 = 'C' print(str3) str3 = "C" print(str3) # multiple line string str4 = """this is a multiple line string""" print("str4 = ",str4) str4 = '''this is a multiple line string''' print("str4 = ",str4) # escape character """ \n new line \t tab(able) \' \" \\ """ print("===n===") print("===\n----") print("1,2,3,4,5,6") print("1,\t2,\t3,\t4,\t5,\t6") # using \ to print out ", ', \ print("\"") print('"') print("'") print("\'") print("\\") # unicode string # https://en.wikipedia.org/wiki/Unicode # https://en.wikipedia.org/wiki/List_of_Unicode_characters str5 = "\u00a9" print(str5) str6 = "\u00e9" print(str6)
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 = [] mylist2 = [1] def empty_check(list): if len(list) < 1: return True else: return False print(empty_check(mylist)) print(empty_check(mylist2)) # 4. mylist = [1, 2, 3, 4, 5, 6] mylist2 = [] def clone(list1, list2): for i in list1: list2.append(i) return list2 print(clone(mylist, mylist2)) # 5. words = 'The quick brown fox jumps over the lazy dog' words = words.split() def length_check(list): word_list = [] for i in list: if len(i) > 3: word_list.append(i) return word_list print(length_check(words))
""" 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() print(list(filter(lambda x: x%2 == 0, mylist1)))
""" 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') # 4th greeting("Good morning", 'f4') """ # variable parameter """ # positional argument # keyword argument # f5,f6,f7,f8,f9 # syntax rule # all keyword args stay after positional argument # def greeting1(words="Good morning", name): def greeting1(name, age=15, words="Good morning"): # print("{w}, {a}, {n}!".format(w=words, a=age, n=name)) print("{w}, {a}, {n}!".format(n=name, a=age, w=words )) greeting1('f5') greeting1('f6') greeting1('f7') greeting1('f8') greeting1('f9',words='Good evening') greeting1('f9','Good evening')
""" 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','r','o','b','l','e','m'] my_list.clear() print(my_list) # remove() my_list = ['p','r','o','b','l','e','m'] my_list.remove('p') print(my_list) # my_list.remove('p') # print(my_list) my_list = ['p','r','o','p','l','e','m'] my_list.remove('p') print(my_list) my_list.remove('p') print(my_list) # pop() my_list = ['p','r','o','p','l','e','m'] my_list.pop(0) print(my_list) my_list = ['p','r','o','p','l','e','m'] my_list.pop(3) print(my_list) my_list.pop() print(my_list) my_list.pop() print(my_list) # my_list.pop(30) # print(my_list) my_list = ['p','r','o','p','l','e','m'] my_list[2:5] = [] print(my_list)
""" 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 ZeroDivisionError: print("ZeroDivisionError") print() print("=== end ===")
""" [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 = date_time.strftime("%x") print("Output 2:", d) d = date_time.strftime("%X") print("Output 3:", 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] result = my_list[0:8] print(result) # chengjun res =mylist[0:8] print(res) # case 2. slicing from the(any) middle to the end # from 5..9 res = mylist[4:9] print("mylist[4:9]",res) res = mylist[4:len(mylist)] print("mylist[4:len(mylist)]",res) res = mylist[4:] print("mylist[4:]",res) # res = mylist[4:-1] # print(res) # res = mylist[4:0] # print(res) # youran my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] middle = round(len(my_list)/2) result = my_list[middle:len(my_list)] print(result) # case 3. slicing res = mylist[2:7] print(res) # ex. slicing for 4..6 # youran my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = my_list[3:6] print(result) # leon x = mylist[3:6] print(x) # chengjun res= mylist[3:6] print(res) # slicing for all items res = mylist[:] print("mylist[:]",res) print("mylist ",mylist)
""" 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 x = x + 3 print(x) # x += 3 # x = x + 3 x = 6 x += 3 print(x) # x = 9 # x = x - 3 # please rewrite this statement with compound operator x -= 3 print(x) # x = 6 # x = x * 3 # rewrite it x *= 3 # performance x = 8 x /=8 print(x)
""" 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 necessary message(prompt) """ """ Hint: 1. one task one function, one function per task 2. consider how to input info for option and operand 3. consider how to output properly code quality 4. consider the program structure 5. comment 6. naming convention """ """ plan 1. input 2. how to select an option(add,sub,mul or div) 3. """ def addition(x,y): x + y def subtraction(x,y): x - y def multiplication(x,y): x * y def division(x,y): x / y print("=== Mini calculator ===") print("Please select an option") print("1. addition") print("2. subtraction") print("3. multiplication") print("4. division") while True: choice = input("Enter choice(1/2/3/4): ") if choice in ('1', '2', '3', '4'): x = float(input("Enter first number: ")) y = float(input("Enter second number: ")) if choice == '1': print(x, "+", y, "=", addition(x , y)) elif choice == '2': print(x, "-", y, "=", subtraction(x , y)) elif choice == '3': print(x, "*", y, "=", multiplication(x , y)) elif choice == '4': print(x, "/", y, "=", division(x , y)) break else: print("Invalid")
""" 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(mylist[:])
""" """ 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: print("Everything fine") finally: print("this is finally clause") try: num = int(input('Please enter a number:')) if num <= 0: raise ValueError('That is not a positive integer') except ValueError as ve: print(ve) else: print('enter again') finally: print('This is finally clause') """ try: pass except: pass finally: pass else: pass """
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=font) display_Label.grid(columnspan=4, padx=10, pady=10, sticky=E) def user_input_digit(num): global expression num = num - 1 expression = expression + f"{num}" display_Label.config(text=expression) def clear(): global expression expression = "" display_Label.config(text="") def delete(): global expression expression = expression[:-1] display_Label.config(text=expression) def modulus(): global expression if expression[-1:].isnumeric and expression != "": expression = expression + "%" display_Label.config(text=expression) def division(): global expression if expression[-1:].isnumeric and expression != "": expression = expression + "/" display_Label.config(text=expression) def multiplication(): global expression if expression[-1:].isnumeric and expression != "": expression = expression + "*" display_Label.config(text=expression) def subtraction(): global expression if expression[-1:].isnumeric: expression = expression + "-" display_Label.config(text=expression) def addition(): global expression if expression[-1:].isnumeric and expression != "": expression = expression + "+" display_Label.config(text=expression) def comma(): global expression if expression[-1:].isnumeric() and expression != "": expression = expression + "." display_Label.config(text=expression) def equal(): global expression, expression_answer answer = eval(expression) expression_answer = expression + "\n" + str(answer) display_Label.config(text=expression_answer) row = 2 digits = ['7', '4', '1', '8', '5', '2', '9', '6', '3', '0'] clear_button = Button(root, text='C', relief='raised', height=2, width=15, padx=5, pady=5, font='Times 12', fg='blue', command=clear) clear_button.grid(row=1) delete_B = Button(text="DEL", font=font, width=15, height=2, command=delete) delete_B.grid(row=1, column=1) modulus_button = Button(root, text='%', relief='raised', height=2, width=15, padx=5, pady=5, font='Times 12', command=modulus) modulus_button.grid(row=1, column=2) division_button = Button(root, text='/', relief='raised', height=2, width=15, padx=5, pady=5, font='Times 12', command=division) division_button.grid(row=1, column=3) multiplication_button = Button(root, text='*', relief='raised', height=2, width=15, padx=5, pady=5, font='Times 12', command=multiplication) multiplication_button.grid(row=2, column=3) subtraction_button = Button(root, text='-', relief='raised', height=2, width=15, padx=5, pady=5, font='Times 12', command=subtraction) subtraction_button.grid(row=3, column=3) addition_button = Button(root, text='+', relief='raised', height=2, width=15, padx=5, pady=5, font='Times 12', command=addition) addition_button.grid(row=4, column=3) answer_button = Button(root, text='=', relief='raised', height=2, width=15, padx=5, pady=5, font='Times 12', bg='light goldenrod yellow', command=equal) answer_button.grid(row=5, column=3) expression = "" answer = "" button_list = [] for i in range(10): button = Button(text=i, command=lambda num=i + 1: user_input_digit(num), width=15, height=2, font=font) button_list.append(button) button_list[7].grid(row=2, column=0, pady=5, padx=5) button_list[8].grid(row=2, column=1, pady=5, padx=5) button_list[9].grid(row=2, column=2, pady=5, padx=5) button_list[4].grid(row=3, column=0, pady=5, padx=5) button_list[5].grid(row=3, column=1, pady=5, padx=5) button_list[6].grid(row=3, column=2, pady=5, padx=5) button_list[1].grid(row=4, column=0, pady=5, padx=5) button_list[2].grid(row=4, column=1, pady=5, padx=5) button_list[3].grid(row=4, column=2, pady=5, padx=5) button_list[0].config(width=30) button_list[0].grid(row=5, columnspan=3, pady=5, padx=(5, 0)) root.mainloop()
""" """ # 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 directory: ") # rename file function def rename_file(file, new_name): with open(file, "r") as old_file: content = old_file.readlines() old_file.close() with open(new_name, "x") as new_file: new_file.writelines(content) os.remove(file) # all files in specified directory all_files_directory = list() dir_list = os.listdir(specified_directory) print("These are the following files in the specified directory =") for f in dir_list: print(f) # counter file_num = 0 # main program while True: if not os.path.isdir(specified_directory+os.sep+dir_list[file_num]): print(f"Do you wish to change the name of file {dir_list[file_num]}, y/n") change = input() if change == "y": new_file_name = input("Please enter the new file name, with the extension desired: ") rename_file(specified_directory+os.sep+dir_list[file_num], new_file_name) file_num += 1 if file_num == len(dir_list): break
""" 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>',attack) root.mainloop()
""" 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(): global global_var print() print("Press 1 to convert celsius into fahrenheit.") print("Press 2 to convert fahrenheit into celsius.") user_choice_1 = int(input("Input your choice: ")) global_var = user_choice_1 def weight_choice(): global global_var print() print("Press 1 to convert kg into pounds.") print("Press 2 to convert pounds into kg.") user_choice_1 = int(input("Input your choice: ")) global_var = user_choice_1 def area_choice(): global global_var print() print("Press 1 to convert square meters into acres.") print("Press 2 to convert acres into square meters.") user_choice_1 = int(input("Input your choice: ")) global_var = user_choice_1 def water_volume_choice(): global global_var print() print("Press 1 to convert gallons into liters.") print("Press 2 to convert liters into gallons.") user_choice_1 = int(input("Input your choice: ")) global_var = user_choice_1 def length_converter(): print() user_input_num = float(input("Please enter the quantity of this item to convert: ")) if global_var == 1: print(f"If you convert {user_input_num} meters into inches you get {user_input_num * 39.37} inches.") elif global_var == 2: print(f"If you convert {user_input_num} inches into meter you get {user_input_num / 39.37} meters.") def temperature_converter(): print() user_input_num = float(input("Please enter the quantity of this item to convert: ")) if global_var == 1: print( f"If you convert {user_input_num} celsius into fahrenheit you get {user_input_num * 1.8 + 32} fahrenheit.") elif global_var == 2: print( f"If you convert {user_input_num} fahrenheit into celsius you get {(user_input_num - 32) * (5 / 9)} celsius.") def weight_converter(): print() user_input_num = float(input("Please enter the quantity of this item to convert: ")) if global_var == 1: print(f"If you convert {user_input_num} kg into pounds you get {user_input_num * 2.205} pounds.") elif global_var == 2: print(f"If you convert {user_input_num} pounds into kg you get {user_input_num / 2.205} kg.") def area_converter(): print() user_input_num = float(input("Please enter the quantity of this item to convert: ")) if global_var == 1: print(f"If you convert {user_input_num} square meters into acres you get {user_input_num / 4047} acres.") elif global_var == 2: print( f"If you convert {user_input_num} acres into square meters you get {user_input_num * 4047} square meters.") def water_volume_converter(): print() user_input_num = float(input("Please enter the quantity of this item to convert: ")) if global_var == 1: print(f"If you convert {user_input_num} gallons into liters you get {user_input_num * 4.546} liters.") elif global_var == 2: print(f"If you convert {user_input_num} liters into square gallons you get {user_input_num / 4.546} gallons.") print("==Converter==") print("Press 1 to use length converter.") print("Press 2 to use temperature converter.") print("Press 3 to use weight converter.") print("Press 4 to use area converter.") print("Press 5 to use water volume converter.") user_input = int(input("Please input the number: ")) if user_input == 1: length_choice() length_converter() elif user_input == 2: temperature_choice() temperature_converter() elif user_input == 3: weight_choice() weight_converter() elif user_input == 4: area_choice() area_converter() elif user_input == 5: water_volume_choice() water_volume_converter()
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): s = x * 2.20462 return s def pound_kilogram(x): s = x * 0.453592 return s def meter_foot(x): s = x * 3.28084 return s def foot_meter(x): s = x * 0.3048 return s def metre_milimetre(x): s = x * 1000 return s def milimeter_meter(x): s = x / 1000 return s def milimetrecarre_metrecarre(x): s = x / 10000000 return s def metrecarre_milimetrecarre(x): s = x * 10000000 return s def foot_inch(x): s = x * 12 return s def inch_foot(x): s = x / 12 return s def inch_cm(x): s = x * 2.54 return s def cm_inch(x): s = x / 2.54 return s def inch_mm(x): s = x * 25.4 return s def mm_inch(x): s = x / 25.4 return s def CAD_CNY(x): s = x * 5.34 return s def CNY_CAD(x): s = x / 5.34 return s f = True while (f): print("Converte calculer") print("0: Exit to the converter") print("1: Length or distance") print("2: Temperature") print("3: Weight") print("4: Area") print("5: Currency") choice = input("choice(0/1/2/3/4/5):") if choice == "0": print("Over") break elif choice >= "6": print("this option does not exist.") continue elif choice <= "0": print("this option does not exist.") continue if choice =='1': while True: print("0: exit to main menu:") print("1: kilometers to miles:") print("2: miles to kilometers:") print("3: metre to milimeter:") print("4: milimetre to meter:") print("5: metrecarre to milimetercarre:") print("6: milimetrecarre to metercarre:") print("7: foot to inch:") print("8: inch to foot:") print("9: inch to cm:") print("10: cm to inch:") print("11: inch to mm:") print("12: mm to inch:") choice2 = input("choice(0/1/2/3/4/5/6/7/8/9/10/11/12):") if choice2 =='1': c = float(input("a number:")) km2mile = kilometers_miles(c) print("the number {} * 0.621371 = {}".format(c, km2mile)) if choice2 =='2': c = float(input("a number:")) mile2km = miles_kilometers(c) print("the number {} * 0.1.609344 = {}".format(c, mile2km)) if choice2 =='3': c = float(input("a number:")) m2mili = metre_milimetre(c) print("the number {} * 1000 = {}".format(c, m2mili)) if choice2 == '4': c = float(input("a number")) mili2m = milimeter_meter(c) print("the number {} / 1000 = {}".format(c, mili2m)) if choice2 == '5': c = float(input("a number:")) mc2milic = metrecarre_milimetrecarre(c) print("the number {} * 10000000 = {}".format(c, mc2milic)) if choice2 == '6': c = float(input("a number:")) milic2mc = milimetrecarre_metrecarre(c) print("the number {} / 10000000 = {}".format(c, milic2mc)) if choice2 == '7': c = float(input("a number:")) f2i = foot_inch(c) print("the number {} * 12 = {}".format(c, f2i)) if choice2 == '8': c = float(input("a number:")) i2f = inch_foot(c) print("the number {} / 12 = {}".format(c, i2f)) if choice2 == '9': c = float(input("a number:")) i2cm = inch_cm(c) print("the number {} * 2.54 = {}".format(c, i2cm)) if choice2 == '10': c = float(input("a number:")) cm2i = cm_inch(c) print("the number {} / 2.54 = {}".format(c, cm2i)) if choice2 == '11': c = float(input("a number:")) i2mm = inch_mm(c) print("the number {} * 25.4 = {}".format(c, i2mm)) if choice2 == '12': c = float(input("a number:")) mm2i = mm_inch(c) print("the number {} / 25.4 = {}".format(c, mm2i)) if choice2 == "0": break elif choice =='2': print("0: exit to main menu:") print("1: fahrenheit_celsius:") print("2: celsius_fahrenheit:") choice2 = input("choice(0/1/2):") if choice2 =='1': c = float(input("a number:")) f2c = fahrenheit_celsius(c) print("the number {} - 32 * 5/9 = {}".format(c, f2c)) if choice2 =='2': c = float(input("a number:")) c2f = celsius_fahrenheit(c) print("the number ({} * 9/5) + 32 = {}".format(c, c2f)) if input == "0": break elif choice == '3': print("0: exit to main menu:") print("1: kilogram_pound:") print("2: pound_kilogram:") choice2 = input("choice(0/1/2):") if choice2 =='1': c = float(input("a number:")) k2p = kilogram_pound(c) print("the number {} * 2.20462 = {}".format(c, k2p)) if choice2 =='2': c = float(input("a number:")) p2k = pound_kilogram(c) print("the number {} * 0.453592 = {}".format(c, p2k)) if input == "0": break elif choice == '4': print("0: exit to main menu:") print("1: meter_foot:") print("2: foot_meter:") choice2 = input("choice(0/1/2):") if choice2 =='1': c = float(input("a number:")) m2f = meter_foot(c) print("the number {} * 3.28084 = {}".format(c, m2f)) if choice2 =='2': c = float(input("a number:")) f2m = foot_meter(c) print("the number {} * 0.3048 = {}".format(c, f2m)) if input == "0": break elif choice == "5": print("0: exit to main menu:") print("1: CAD_CNY") print("2: CNY_CAD") choice2 = input("choice(0/1/2):") if choice2 =='1': c = float(input("a number:")) CAD2CNY = CAD_CNY(c) print("the number {} * 5.34 = {}".format(c, CAD2CNY)) if choice2 =='2': c = float(input("a number:")) CNY2CAD = CNY_CAD(c) print("the number {} / 5.34 = {}".format(c, CNY2CAD)) if input == "0": break else: print("this option does not exist.")
""" 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 statements stay in one line a = 1 ; b = 2 # multi-line statement # one statement which spans multiple lines # \ - line continuation character result = 1+ 2+ 3 + 4 + 5 + \ 6 + 7 + 8 + 9 + \ 10 + 11 print(result) a = (1, 2, 3, # quarter 1 4, 5, 6, # quarter 2 7, 8, 9) # quarter 3 print(a) b = {1, 2, 3, 4, 5, 6} print(b) c = [1, 2, 3, 4, 5, 6] print(c)
""" 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 celsius_fahrenheit(x): return (x * 1.8) + 32 def celsius_kelvin(x): return x + 273.15 def fahrenheit_celsius(x): return (x - 32) * 1.8 def fahrenheit_kelvin(x): return (x - 32) * 1.8 + 273.15 def kelvin_celsius(x): return x - 273.15 def kelvin_fahrenheit(x): return (x - 273.15) * 1.8 + 32 # Weight def kg_g(x): return x * 1000 def kg_pound(x): return x * 2.205 def g_kg(x): return x / 1000 def g_pound(x): return x / 1000 * 2.205 def pound_kg(x): return x / 2.205 def pound_g(x): return x / 2.205 * 1000 # Time choice def time(): print() print("===Time converter===") print("Press 1 for minute to hour") print("Press 2 for minute to second") print("Press 3 for hour to minute") print("Press 4 for hour to second") print("Press 5 for second to hour") print("Press 6 for second to minute") choice_2 = int(input("Now please input you choice: ")) if choice_2 == 1: user_input = float(input("Please input the amount of minutes to convert: ")) print(f"If you convert {user_input} minutes into hours you get {min_hour(user_input)} hours.") elif choice_2 == 2: user_input = float(input("Please input the amount of minutes to convert: ")) print(f"If you convert {user_input} minutes into seconds you get {min_sec(user_input)} seconds.") elif choice_2 == 3: user_input = float(input("Please input the amount of hours to convert: ")) print(f"If you convert {user_input} hours into minutes you get {hour_min(user_input)} minutes.") elif choice_2 == 4: user_input = float(input("Please input the amount of hours to convert: ")) print(f"If you convert {user_input} hours into seconds you get {hour_sec(user_input)} seconds.") elif choice_2 == 5: user_input = float(input("Please input the amount of seconds to convert: ")) print(f"If you convert {user_input} seconds into minutes you get {sec_min(user_input)} minutes.") elif choice_2 == 6: user_input = float(input("Please input the amount of seconds to convert: ")) print(f"If you convert {user_input} seconds into hours you get {sec_hour(user_input)} hours.") else: print("Error") # Temperature choice def temperature(): print() print("===Temperature converter===") print("Press 1 for celsius to fahrenheit") print("Press 2 for celsius to kelvin") print("Press 3 for fahrenheit to celsius") print("Press 4 for fahrenheit to kelvin") print("Press 5 for kelvin to celsius") print("Press 6 for kelvin to fahrenheit") choice_2 = int(input("Now please input you choice: ")) if choice_2 == 1: user_input = float(input("Please input the amount of kg to convert: ")) print( f"If you convert {user_input} celsius into fahrenheit you get {celsius_fahrenheit(user_input)} fahrenheit.") elif choice_2 == 2: user_input = float(input("Please input the amount of kg to convert: ")) print(f"If you convert {user_input} celsius into kelvin you get {celsius_kelvin(user_input)} kelvin.") elif choice_2 == 3: user_input = float(input("Please input the amount of g to convert: ")) print(f"If you convert {user_input} fahrenheit into celsius you get {fahrenheit_celsius(user_input)} celsius.") elif choice_2 == 4: user_input = float(input("Please input the amount of g to convert: ")) print(f"If you convert {user_input} fahrenheit into kelvin you get {fahrenheit_kelvin(user_input)} kelvin.") elif choice_2 == 5: user_input = float(input("Please input the amount of pounds to convert: ")) print(f"If you convert {user_input} kelvin into celsius you get {kelvin_celsius(user_input)} celsius.") elif choice_2 == 6: user_input = float(input("Please input the amount of pounds to convert: ")) print(f"If you convert {user_input} kelvin into fahrenheit you get {kelvin_fahrenheit(user_input)} fahrenheit.") else: print("Error") # Weight choice def weight(): print() print("===Weight converter===") print("Press 1 for kg to g") print("Press 2 for kg to pound") print("Press 3 for g to kg") print("Press 4 for g to pound") print("Press 5 for pound to kg") print("Press 6 for pound to g") choice_2 = int(input("Now please input you choice: ")) if choice_2 == 1: user_input = float(input("Please input the amount of kg to convert: ")) print(f"If you convert {user_input} kg into g you get {kg_g(user_input)} g.") elif choice_2 == 2: user_input = float(input("Please input the amount of kg to convert: ")) print(f"If you convert {user_input} kg into pounds you get {kg_pound(user_input)} pounds.") elif choice_2 == 3: user_input = float(input("Please input the amount of g to convert: ")) print(f"If you convert {user_input} g into kg you get {g_kg(user_input)} kg.") elif choice_2 == 4: user_input = float(input("Please input the amount of g to convert: ")) print(f"If you convert {user_input} g into pounds you get {g_pound(user_input)} pounds.") elif choice_2 == 5: user_input = float(input("Please input the amount of pounds to convert: ")) print(f"If you convert {user_input} pounds into kg you get {pound_kg(user_input)} kg.") elif choice_2 == 6: user_input = float(input("Please input the amount of pounds to convert: ")) print(f"If you convert {user_input} pounds into g you get {pound_kg(user_input)} g.") else: print("Error") print("===Simple Converter===") print("Press 1 for time conversion") print("Press 2 for temperature conversion") print("Press 3 for weight conversion") choice_1 = int(input("Please input your choice: ")) if choice_1 == 1: time() elif choice_1 == 2: temperature() elif choice_1 == 3: weight() else: print("Error")
""" 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 tuple # access element (char) print(str1[0]) print(str1[-1]) # slice str2 = str1[1:3] print(str2) # length print(len(str1)) print(len(str2)) # change a string # TypeError: 'str' object does not support item assignment # str1[0] = 'H' # h -> H # reassign str2 = 'abc' print(str2)
""" 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 Python String isupper() [yes] returns if all characters are uppercase characters Python String upper() [yes] returns uppercased string Python String lower() [yes] returns lowercased string Python String swapcase() [yes] swap uppercase characters to lowercase; vice versa Python String title() [yes] Returns a Title Cased String """ # string1 = 'abc' # print(string1.islower()) # # string1 = 'ABC' # print(string1.islower()) def mycase(mystr): print("1. upper()") result = mystr.upper() print(result) print() print("2. lower()") result = mystr.lower() print(result) print() print("4. islower()") result = mystr.islower() print(result) print() # main str1 = 'xyZ' print(f"Original string is {str1}\n") mycase(str1)
""" 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: ")) except ValueError: print("Invalid characters. Please try again.") else: try: if num < 1: raise NumberTooSmallError("The number is not in the given range. It should be smaller.") elif num > 100: raise NumberTooBigError("The number is not in the given range. It should be bigger.") except NumberTooBigError as ntb: print(ntb) except NumberTooSmallError as nts: print(nts) else: valid = True if num == randint: print("Congratulations! You found the right number.") break elif guess == 8: pass else: if num < randint: print("That is not the right number. Please try again. The number is higher.") else: print("That is not the right number. Please try again. The number is lower.") print() if num != randint: print(f"Sorry, that was your last chance! The number was {randint}")
""" 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(1) pos_2 = tuple1.index(2) print(pos_1) print(pos_2) # how to find the 2nd item in a tuple
""" 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 dict2 = { 1: 'a', 2: 'a', 3: 'a' } print(dict2) # overwriting key-value pair dict3 ={ 1: 'a', 2: 'a', 3: 'a', 3: 'b' } print(dict3) dict3b ={ 1: 'a', 2: 'a', 3: 'b', 3: 'a' } print(dict3b) # the case that a key is None dict4a = { 1: 'a', 2: 'b', 3: 'c', None: 'no value' } print(dict4a) dict4a2 = { 1: 'a', 2: 'b', 3: 'c', None: 'no value 1', None: 'no value 2' } print(dict4a2) # the case that a value is None dict4b = { 1: 'a', 2: 'b', 3: 'c', 4: None, 5: None } print(dict4b)
""" 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 # access element by index # item, element print('The #0 item of list is', array_odd[0]) print('The #1 item of list is', array_odd[1]) print('The #2 item of list is', array_odd[2]) print('The #3 item of list is', array_odd[3]) print('The #4 item of list is', array_odd[4]) # update value of item in a list array_odd[5] = 11 print(array_odd) a = 1 a = 2
""" 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 program shows a text message (info) box with the words 'login successfully!' otherwise, the program shows a text message (error) box with the words 'wrong username or password!' Due date: by the end of next Friday """ from tkinter import * from tkinter import messagebox as msg root = Tk() root.title("Python GUI - Entry") root.geometry("300x160") def showPwd(): entryobj = passwordE entryobj['show'] = '' def hidePwd(): entryobj = passwordE entryobj['show'] = '*' def getInfo(): logininfo = accountE.get() passwordinfo = passwordE.get() title = 'login information' if logininfo == username and passwordinfo == password: text = 'login successfully' msg.showinfo(title, text) else: text = 'wrong username or password!' msg.showerror(title, text) username = 'admin' password = '123456' accountL = Label(root, text="Account ") accountL.grid(row=2, padx=(50, 5), sticky='e') passwordL = Label(root, text="Password ") passwordL.grid(row=3, padx=(50, 5), sticky='e') accountE = Entry(root) accountE.grid(row=2, column=1, padx=(5, 50)) passwordE = Entry(root, show='*') passwordE.grid(row=3, column=1, padx=(5, 50)) showBtn = Button(root, text='Show password', command=showPwd) showBtn.grid(row=4, column=1) showBtn = Button(root, text='Hide password', command=hidePwd) showBtn.grid(row=5, column=1) loginbtn = Button(root, text="login", command=getInfo) loginbtn.grid(row=6, column=1) root.mainloop()
""" 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 widget: ")) sw = root.winfo_screenwidth() sh = root.winfo_screenheight() top_left_x = int(sw / 2 - w_width / 2) top_left_y = int(sh / 2 - w_height / 2) root.geometry(f"{w_width}x{w_height}+{top_left_x}+{top_left_y}") # root.configure(background="purple") # root.configure(bg="purple") root.config(bg='purple') root.wm_attributes("-topmost", True) root.maxsize(1600, 900) root.minsize(300, 200) root.resizable(1, 1) label1 = tkinter.Label(root, text="This is a normal sized label :)", fg="pink", bg="gray", font=12, width=20, height=1) label1.pack() label2 = tkinter.Label(root, text="Big Label (:", fg="gold", bg="blue", font=16, width=80, height=20) label2.pack() label3 = tkinter.Label(root, text="tiny", fg="white", bg="black", font=5, width=2, height=1) label3.pack() label3 = tkinter.Label(root, text="You may resize the window (you have 10 secs), " "the new dimension will be echoed in console" , fg="green", bg="pink") label3.pack() root.update() time.sleep(10) root.update() print("Your window's width =", root.winfo_width()) print("Your window's height =", root.winfo_height()) root.mainloop()
""" [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 sort a dictionary by value in both ascending and descending order. """
""" 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 one and sort, then set the key back mylist2 = [[4,'a'],[8,'c'],[2,'b'],[1,'d']] for i in mylist2: i.reverse() print(mylist2) mylist2.sort() for i in mylist2: i.reverse() print(mylist2) print() # solution 2. insert the target key to the first place # insert mylist3 = [[4,10,'a',5],[8,9,'c',4],[2,8,'b',3],[1,7,'d',0]] for item in mylist3: item.insert(0, item[2]) print(item) mylist3.sort() for item in mylist3: item.pop(0) print(mylist3) print() # solution 3. lambda mylist4 = [[4,10,'a',5],[8,9,'c',4],[2,8,'b',3],[1,7,'d',0]] mylist4.sort(key=lambda item: item[2], reverse=True) print(mylist4)
""" 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','w') file2.write(content) except FileNotFoundError as fe: print(fe) except IOError as ioe: print(ioe) except Exception as e: print(e) finally: file1.close() file2.close()
""" 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', 'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July', 'Aug': 'August', 'Sep': 'September', 'Oct': 'October', 'Nov': 'November', 'Dec': 'December'} # pop() value = months.pop("Dec") print(value) print(months) # popitem() item = months.popitem() print(item, type(item)) # clear() months.clear() print(months) months = {'Jan': 'January', 'Feb': 'February', 'Mar': 'March', 'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July', 'Aug': 'August', 'Sep': 'September', 'Oct': 'October', 'Nov': 'November', 'Dec': 'December'} # del keywords # del key,value (item) # del dict del months['Oct'] print(months) del months # print(months) # NameError
""" 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)) # boolean, 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 a multiline string with more than one line code.''' print(multiline_str2)
""" 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 err.TooBigError elif num < 1: raise err.TooSmallError except err.TooBigError as tbe: print("Too big! please input a number which is less than 100.") except err.TooSmallError as tse: print("Too small! please input a number which is greater than 1.") except Exception as e: print(e) print("continue to execute.")
""" 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 = { 'c1' : 45, 'c2' : 50 } # state C vote_state_c = { 'c1' : 70, 'c2' : 40 } # calculate number of ticket for every candidate result = Counter(vote_state_a) + Counter(vote_state_b) + Counter(vote_state_c) print(result) result = dict(result) print() # trail result = Counter(vote_state_a) - Counter(vote_state_b) print(result)
""" 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') # show on screen label1.grid(row=0, column=0, columnspan=2) label2.grid(row=1, column=0) label3.grid(row=1, column=1) root.mainloop()
""" [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 import time root = tk.Tk() root.title("Python GUI - Center") # root.iconbitmap("IMG_2408.ico") width = 640 height = 480 rightpos = int(root.winfo_screenwidth() / 2 - width/2 ) downpos = int(root.winfo_screenheight() / 2 - height/2 ) root.maxsize(900, 600) root.minsize(100, 70) root.geometry(f"{width}x{height}+{rightpos}+{downpos}") root.update() time.sleep(1) root.update() root.configure() time.sleep(1) root.update() root.configure() time.sleep(1) root.update() root.configure()
""" [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, improper size of font (-2) """ from tkinter import * from tkinter.ttk import Separator import datetime def count(): clock_label.config(text=datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]) clock_label.after(1, count) # main program root = Tk() root.title('Python GUI - Label clock') root.geometry("{}x{}+200+240".format(640, 540)) root.configure(bg='#ddddff') # title label object label1 = Label(root, text="Label Clock", bg="blue", fg="white", height=2, width=100, font="Helvetic 35 bold") label1.pack() # separator sep1 = Separator(root, orient=HORIZONTAL) sep1.pack(fill=X) # clock label object clock_label = Label(root, bg="seagreen", fg='white', height=8, width=100, font="Helvetic 30 bold") clock_label.pack() # separator sep1 = Separator(root, orient=HORIZONTAL) sep1.pack(fill=X) # footer label object label2 = Label(root, text="Version 1 | Ze Yue Li | 2021-03-08", bg="red", fg="white", height=2, width=100, font="Helvetic 35 bold") label2.pack() count() root.mainloop()
""" [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" from the matrix print(a[1][1]) # printing the element 2 from the matrix
""" 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)) # Leonj print('my screen resolution is {my_width} x {my_height}'.format(my_width=width, my_height=height)) # Yiding print('my screen resolution is {my_width} x {my_height}'.format(my_width=width, my_height=height)) # Kevin width = 2560 height = 1600 # solution 2 print("My screen resolution is {0} x {1}".format(width, height)) # solution 3 print("My screen resolution is {my_width} x {my_height}".format(my_width=width, my_height=height)) print("My screen resolution is {width} x {height}".format(width=width, height=height))
""" [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 Tree") root.iconbitmap("./Tree.ico") window_width = 1200 window_height = 600 screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() x = int(screenwidth/2 - window_width/2) y = int(screenheight/2 - window_height/2) root.geometry(f"{window_width}x{window_height}+{x}+{y}") root.maxsize(1600, 900) root.minsize(320, 180) root.resizable(1, 1) my_label = tk.Label(root, text="Please do not close this window before it becomes black!", width=100, height=3, bg="white", fg="cyan3", anchor="e", font="Gabriola 18 italic") my_label.pack() my_label = tk.Label(root, text="Thanks!", width=60, height=4, bg="red", fg="orange", anchor="se", font="Times 15 underline") my_label.pack() my_label = tk.Label(root, text="Have a wonderful day!", width=45, height=4, bg="green", fg="lime", anchor="w", font="Algerian 20 bold italic") my_label.pack() my_label = tk.Label(root, text="See you next time.", width=60, height=5, bg="blue", fg="yellow", anchor=tk.NW, font='"Courier New" 18 bold') my_label.pack() my_btn = tk.Button(root, text="Close", width=15, height=2, bg="brown", font="Harrington 15 bold overstrike", command=root.destroy) my_btn.pack() root.attributes("-topmost", True) root.config(bg="black") root.update() time.sleep(1.5) root.config(bg="coral1") root.update() time.sleep(1.5) root.config(bg="coral2") root.update() time.sleep(1.5) root.config(bg="coral3") root.update() time.sleep(1.5) root.config(bg="PaleVioletRed1") root.update() time.sleep(1.5) root.config(bg="PaleVioletRed2") root.update() time.sleep(1.5) root.config(bg="PaleVioletRed3") root.update() time.sleep(1.5) root.config(bg="MediumPurple1") root.update() time.sleep(1.5) root.config(bg="MediumPurple2") root.update() time.sleep(1.5) root.config(bg="MediumPurple3") root.update() time.sleep(1.5) root.config(bg="black") root.update() time.sleep(3) root.iconify() root.mainloop()
""" 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 = '' while True: 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)) break return x inputValidNumber()
""" 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 dictionaries to create a new one. Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} 4. Write a Python script to check whether a given key already exists in a dictionary. 5. Write a Python program to iterate over dictionaries using for loops. 6. Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). Sample Dictionary ( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} """ # Question 1 my_dict = {'a': 37, 'b': 45, 'c': 39} list1 = [] for i in list(my_dict): list1.append(my_dict[i]) list2 = sorted(list1) print(list2) dict2 = {'1': list2[0], '2': list2[1], '3': list2[2]} print(dict2) my_dict = {'a': 37, 'b': 45, 'c': 39} list1 = [] for i in list(my_dict): list1.append(my_dict[i]) list2 = sorted(list1, reverse=True) print(list2) dict2 = {'1': list2[0], '2': list2[1], '3': list2[2]} print(dict2) # Question 2 my_dict = {1: 10, 2: 20} my_dict[3] = 30 print(my_dict) # Question 3 dict1 = {1:10, 2:20} dict2 = {3:30, 4:40} dict3 = {5:50, 6:60} dict4 = {} for i in list(dict1): dict4[i] = dict1[i] for i in list(dict2): dict4[i] = dict2[i] for i in list(dict3): dict4[i] = dict3[i] print(dict4) # Question 4 dict3 = {5:50, 6:60} print(5 in dict3) # Question 5 dict3 = {5:50, 6:60, 7:70, 8:80, 9:90} for i in dict3: print(i, dict3[i]) # Question 6 num = 5 dict1 = {} for i in range(1, num+1): dict1[i] = i*i print(dict1)
""" 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("{} students of {} students got A.".format(a_num,num_people))
""" 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', width=50, height=3, anchor='nw') label1.pack() # create a Label label2 = tk.Label(root, text='My Text Label 2',width=30, height=5, anchor=tk.NW) label2.pack() root.mainloop()
""" 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 comprehension newlist = [x * 2 for x in mylist] print(newlist) # case 2. list comprehension and filter # for, if, [] # [1,3,5,7,9] newlist2 = [x for x in range(1,11)] print(newlist2) newlist2 = [x for x in range(1,11) if x % 2 == 1] print(newlist2)
""" 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, 70) root.geometry(f"{win_width}x{win_height}+{positionRight}+{positionDown}") mytext = 'MyText Label 6' label1 = Label(root, text=mytext, width=30, height=7, bg='blue', fg='#ffffff', anchor=N) lable2 = Label(root,bg = 'green',bitmap = 'info', padx = 20, pady = 10) label1.pack() lable2.pack() root.update() root.configure(bg='#ffdddd') # create a label with image in .gif bgimg = PhotoImage(file='./img/pimon.gif') label3 = Label(root, image=bgimg) # center on screen label3.pack() root.mainloop()
""" [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 GUI - Homework") root.geometry("640x480+0+0") label1 = Label(root, text='label_A', font=('Time', 20), fg='black', bg="#F0F0EC") label2 = Label(root, text='Label_B', font=('Time', 20), bg='yellow') label3 = Label(root, text='Label_C', font=('Time', 20), fg='white', bg='#83b5dd') label1.pack(side=LEFT) label2.pack(side=LEFT) label3.pack(side=LEFT) label1.after(2000, hide(label1)) label1.after(2000, show(label1)) root.mainloop()
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: 'tuba', 8: 'flute'} print(type(instrument_dict)) print(instrument_dict) num = len(instrument_dict) print("there are", num, "instrument in the dictionary")
""" 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 print("The student {} is at stulist[{}]".format(stu_no,stulist.index(stu_no))) stulist = [101,102,103,104,201,202,203,204,205,301,302,303,304,101,102,103,104,201,202,203,204,205,301,302,303,304] # get the index of 2nd item of 201 stu_no = 201 current_index = stulist.index(stu_no) print("The 1st student {} is at stulist[{}]".format(stu_no,current_index)) print("The 2nd student {} is at stulist[{}]".format(stu_no,stulist.index(stu_no,current_index+1)))
""" 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) > smallerthan > -1: num = input(message) while not num.isdigit(): num = input(message) return num def possible_nums(num_range): pos_nums = [] for i in range(num_range[0], num_range[1] + 1): pos_nums.append(i) return pos_nums def guess(pos_nums, num_to_guess): guess = pos_nums[len(pos_nums) // 2] guesses = 1 while guess != num_to_guess: guesses += 1 if guess > num_to_guess: pos_nums2 = pos_nums.copy() pos_nums.clear() for i in range(pos_nums2[0], guess): pos_nums.append(i) else: pos_nums2 = pos_nums.copy() pos_nums.clear() for i in range(guess + 1, pos_nums2[-1] + 1): pos_nums.append(i) guess = pos_nums[len(pos_nums) // 2] print(guess) print('The AI guessed {} times'.format(guesses)) num_to_guess = int(input_num('Input an integer for the computer to guess:')) num_range_start = input_num("Input the first number of a range covering your number:", num_to_guess) num_range_end = input_num("Input the second number of the range", -1, num_to_guess) num_range = [int(num_range_start), int(num_range_end)] pos_nums = possible_nums(num_range) guess(pos_nums, num_to_guess)
""" 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 elif chance in range(889, 988): print('rare') rare += 1 elif chance in range(989, 998): print('legendary') legendary += 1 elif chance in range(999, 1000): print('ancient legendary') ancient_legendary += 1 print(f'normal: {normal}, magic: {magic}, rare: {rare}, legendary: {legendary}, ancient legendary: {ancient_legendary}')
""" 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 notation (uppercase E) f Displays fixed point number (Default: 6) F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN' g General format. Rounds number to p significant digits. (Default precision: 6) G Same as 'g'. Except switches to 'E' if the number is large. % Percentage. Multiples by 100 and puts % at the end. """ # d n = 123 print("The number is {:d}".format(n)) # n = 123.45 # print("The number is {:d}".format(n)) # c # char = u'\u0039' # print("The character is {:c}".format(char)) char = 65 print("The character is {:c}".format(char)) char = 97 print("The character is {:c}".format(char)) # b b = 101 print("The number is 0b{:b}".format(b)) b1 = 0b1100101 b1 = bin(b) # o o = 0x10 print("The number is 0o{:o} >>>".format(o)) # x x = 246 print("The number is 0x{:x}".format(x)) x_uppercase = 76 print("The number is 0x{:X}".format(x_uppercase)) # n n = 12300000 print("The number is {:n}".format(n)) n = 134596 print("The number is {:n}".format(n)) e = 81 print("The number is {:e}".format(e)) e = 81 print("The number is {:E}".format(e)) # f f = 2378.32556234 print("The number is {:F}".format(f)) # g g = 1895.8923456 print("The number is {:g}".format(g)) g = 319.347721949 print("The number is {:G}".format(g)) # % percentage = 0.178 print("The percentage is {:.2%}".format(percentage))
""" 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 --> done d. User can input a validation code (usually an integer) generated randomly by the System, and that code (or number) should display on the window. If the user inputs the wrong code (or number), registration will fail and a messagebox should popup on the screen to warn the user. --> done e. A text title for this application should be set properly on the interface. Note: It is not the title of the main window. --> done f. A Button is required to perform registration once User finishes all inputs. Proper messages or information is required to display in both cases of 'success' and 'failed'. --> done g. A second Button is required to perform reset (or clear all inputs on the window) --> done h. Another Button is required to perform closing window and exit --> done Hints: Any layout manager is free to use. To make a clean and concise layout for your GUI application. Make a wireframe (or draft design) for your GUI Assuming your application (program) is designed for a real scenario, therefore think about what previous experience you had in other online registration processes. """ from tkinter import * from tkinter import messagebox as msg import random def login(): if entry2.get() == entry3.get() and code == entry4.get(): msg.showinfo("Form Result", "Login successfully.") else: msg.showerror("Form Result", "Wrong password, username or validation code. Please try again.") def clearInfo(): entry1.delete(0, END) entry2.delete(0, END) entry3.delete(0, END) entry4.delete(0, END) root = Tk() root.title("Form") root.geometry("500x500") root.configure(bg="black") root.iconbitmap("./img/login.ico") code = str(random.randint(1000, 9999)) # title title = Label(root, text="Account Registration", bg="black", fg="white", font="verdana 24") title.pack(anchor=CENTER) blank_space_0 = Label(root, bg="black") blank_space_0.pack() # entry of account accountL = Label(root, text="Account:", bg="black", fg="white") accountL.pack() entry1 = Entry(root) entry1.pack() blank_space = Label(root, bg="black") blank_space.pack() # entry of password passwordL = Label(root, text="Password:", bg="black", fg="white") passwordL.pack() entry2 = Entry(root, show="*") entry2.pack() blank_space_2 = Label(root, bg="black") blank_space_2.pack() # entry of password 2 password2L = Label(root, text="Confirm password:", bg="black", fg="white") password2L.pack() entry3 = Entry(root, show="*") entry3.pack() blank_space_3 = Label(root, bg="black") blank_space_3.pack() # validation code validation_code = Label(root, text=f"Your validation code: {code}", bg="black", fg="white", font="verdana 12") validation_code.pack(anchor=CENTER) confirm_code = Label(root, text="Confirm validation code:", bg="black", fg="white") confirm_code.pack() # entry of validation code entry4 = Entry(root) entry4.pack() blank_space_4 = Label(root, bg="black") blank_space_4.pack() # button of login login_btn = Button(root, text='Login', command=login, bg="white", fg="black") login_btn.pack() blank_space_5 = Label(root, bg="black") blank_space_5.pack() # button of clear clear_btn = Button(root, text="Clear", bg="white", fg="black", command=clearInfo) clear_btn.pack() blank_space_5 = Label(root, bg="black") blank_space_5.pack() # button of exit quit_btn = Button(root, text="Exit", bg="white", fg="black", command=root.destroy) quit_btn.pack() root.mainloop()
""" 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 + new_students print(namelist) # old_students = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6', 'name7', 'name8'] new_students = ['nm1','nm2','nm3'] for new in new_students: old_students.append(new) print(old_students) # repeating a list # * operator list1 = [1,2,3] newlist = list1 * 3 print(newlist) newlist = list1 * 0 print(newlist) newlist = list1 * -1 print(newlist)
""" 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("stem1403_ccj") image = False if image: root.iconbitmap(image) print("enter a 16:9 ratio dimension for your widget, ") w_width = int(input("enter the desired width for your widget: ")) w_height = int(input(" enter the desired height for your widget: ")) while w_width/w_height != 16/9 or w_width > 1600 or w_height > 900: print("Please enter a 16:9 ratio dimension for your widget (ex: 1600x900 or 800x450, etc...)" "\nMust be equal or smaller than 1600x900") w_width = int(input("Please enter the desired width for your widget: ")) w_height = int(input("Please enter the desired height for your widget: ")) sw = root.winfo_screenwidth() sh = root.winfo_screenheight() top_left_x = int(sw/2 - w_width/2) top_left_y = int(sh/2 - w_height/2) root.geometry(f"{w_width}x{w_height}+{top_left_x}+{top_left_y}") root.configure(background="bleu") root.wm_attributes("-topmost", True) root.maxsize(1600, 900) root.minsize(300, 200) root.resizable(1, 1) root.update() print(root.winfo_width(), "= initial width") print(root.winfo_height(), "= initial height") time.sleep(2) w_width = 500 w_height = 350 top_left_x = int(sw/2 - w_width/2) top_left_y = int(sh/2 - w_height/2) root.geometry(f"{w_width}x{w_height}+{top_left_x}+{top_left_y}") root.update()
""" 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 window label1.pack() root.mainloop()
""" 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("=================") # solution 2 result = [[c1+c2 for c1 in string1] for c2 in string2] print(result) result = [c1+c2 for c1 in string1 for c2 in string2] print(result)
""" 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 like this can enter the price of the product to use dictionary. (missing: when to use) 3. No, because some float in python can have some deviation, like I know this two are equal, but python say it is not equal. 4. Lambda function is very easy to uss, because the syntax of lambda function is easy than normal. But we can use just only one times, so we don't need to write for names. Last one, we can pass function as an argument. 5. Multi-module program is have many python file, so I can write one part in one python document. SO I think we can just use it in one small program. Multi-package program is have many python package, so I can write one part in one python packages, in one part, I write some programs in this parts. And I Think multi-package program is better for one teams. 6. Recursive function: def example(condition): if condition == 1: result = True else: result = False return result print(example(1)) We use return to return the answer. Drawbacks: If we use recursive function to do one big question mathematic, like the result of 80th number of Fibonacci, use the recursive function to know this result is very slow. (wrong example) 7. We can makes some note in the program, like use #, and you can write : a is for all apple's number. (missing: using variables or constants) 8. I think: The syntax of your program and the syntax of your statement to output. Can be readable, understandable, because this is very important for teamwork, so, if it isn't understandable, your teams can't understand the program you wrote. Also, the program must be fast and can did everything. 9. First: Write one welcome sentence. And write what do you want doing. And when he is finished, I will say Good buy. (misunderstanding) 10. The program is very neat. Aligned. Use the Comment. Thoughtful. (missing: separation of concerns) """
""" 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: print("Your level is invalid.") break; if level <10: print("buy a knife") elif level < 20: print("buy an armor") elif level < 30: print("buy a pair shoes") elif level < 40: print("buy a pendent") elif level < 50: print("buy an earing") elif level < 60: print("buy a ring") elif level < 70: print("buy a sword") else: print("can go to arena") print("bye-bye")