4-1주차: 5/22/2023 - 5/28/2023
students = ['Kim', 'Shin', 'Park', 'Choi', 'Hwang']
for i in range(5):
if i % 2 == 0:
print('even index -> students[{}]: {}'.format(i, students[i]))
else:
print('odd index -> students[{}]: {}'.format(i, students[i]))
students = ['Hong', 'Park', 'Lee']
sLength = len(students)
print('Length of students: {}'.format(sLength))
for i in range(len(students)):
print('i: {}'.format(i))
print(students[i])
str = 'Hello python'
print(len(str))
myFavoriteSports = ['Swimming', 'Volleyball', 'Baseball']
for i in range(len(myFavoriteSports)):
print(myFavoriteSports[i])
for item in myFavoriteSports:
print(item)
n = 0
while n < len(myFavoriteSports):
print(myFavoriteSports[n])
n += 1
cars = ['BMW', 'Mercedes', 'Toyota']
for i in range(len(cars)):
print(cars[i])
for car in cars:
print(car)
studentCnts = [[1, 19], [2, 20], [3, 22], [4, 18], [5, 21]]
for i in range(len(studentCnts)):
print('Number of students in class {}: {}'.format(studentCnts[i][0], studentCnts[i][1]))
for classNo, cnt in studentCnts:
print('Number of students in class {}: {}'.format(classNo, cnt))
# Exercise
studentCnts = [[1, 18], [2, 19], [3, 23], [4, 21], [5, 20], [6, 22], [7, 17]]
sum = 0
avg = 0
for classNo, cnt in studentCnts:
print('Number of students in class {}: {}'.format(classNo, cnt))
sum += cnt
print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
minScore = 60
scores = [['Korean', 58],
['English', 77],
['Math', 89],
['Science', 99],
['History', 50]]
for item in scores:
if item[1] < minScore:
print('Failed class: {}, score: {}'.format(item[0], item[1]))
for subject, score in scores:
if score < minScore:
print('Failed class: {}, score: {}'.format(subject, score))
for subject, score in scores:
if score >= minScore: continue
print('Failed class: {}, score: {}'.format(subject, score))
students = [['Class 1', 18],
['Class 2', 19],
['Class 3', 23],
['Class 4', 21],
['Class 5', 20],
['Class 6', 22],
['Class 7', 17]]
minClassNum = 0
minStudentNum = 0
maxClassNum = 0
maxStudentNum = 0
for classNum1, studentNum in students:
if minStudentNum == 0 or minStudentNum > studentNum:
minClassNum = classNum1
minStudentNum = studentNum
if maxStudentNum == 0 or maxStudentNum < studentNum:
maxClassNum = classNum1
maxStudentNum = studentNum
print('Class with the least students (number of students): {}({})'.format(minClassNum, minStudentNum))
print('Class with the most students (number of students): {}({})'.format(maxClassNum, maxStudentNum))
cars = ['Toyota', 'BMW', 'Mercedes']
n = 0
while n < len(cars):
print(cars[n])
n += 1
n = 0
flag = True
while flag:
print(cars[n])
n += 1
if n == len(cars):
flag = False
n = 0
while True:
print(cars[n])
n += 1
if n == len(cars):
break
# Exercise
studentCnts = [[1, 18], [2, 19], [3, 23], [4, 21], [5, 20], [6, 22], [7, 17]]
sum = 0
avg = 0
n = 0
while n < len(studentCnts):
classNo = studentCnts[n][0]
cnt = studentCnts[n][1]
print('Number of students in Class {}: {}'.format(classNo, cnt))
sum += cnt
n += 1
print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
studentCnts = [[1, 18],
[2, 19],
[3, 23],
[4, 21],
[5, 20],
[6, 22],
[7, 17]]
minClassNo = 0; maxClassNo = 0
minCnt = 0; maxCnt = 0
n = 0
while n < len(studentCnts):
if minCnt == 0 or minCnt > studentCnts[n][1]:
minClassNo = studentCnts[n][0]
minCnt = studentCnts[n][1]
if maxCnt == 0 or maxCnt < studentCnts[n][1]:
maxClassNo = studentCnts[n][0]
maxCnt = studentCnts[n][1]
n += 1
print('Class with the most students (number of students): Class {} ({})'.format(maxClassNo, maxCnt))
print('Class with the least students (number of students): Class {} ({})'.format(minClassNo, minCnt))
enumerate()
message = input('Input message: ')
cnt = 0
for idx, value in enumerate(message):
if value == ' ':
cnt += 1
print('Number of spaces: {}'.format(cnt))
append()
myFamilyAge = [['Dad', 40], ['Mom', 38], ['Me', 9]]
print(myFamilyAge)
myFamilyAge.append(['Brother', 1])
print(myFamilyAge)
for name, age in myFamilyAge:
print('Age of {}: {}'.format(name, age))
insert()
numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
inputNumber = int(input('Input an integer: '))
insertIdx = 0
for idx, number in enumerate(numbers):
print(idx, number)
if insertIdx == 0 and inputNumber < number:
insertIdx = idx
numbers.insert(insertIdx, inputNumber)
print('numbers: {}'.format(numbers))
pop()
pop(3)
: delete the item with the index 3 and moves the items on the right to the leftplayerScores = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
print('playerScores: {}'.format(playerScores))
minScore = 0; maxScore = 0
minScoreIdx = 0; maxScoreIdx = 0
for idx, score in enumerate(playerScores):
if minScoreIdx == 0 or minScore > score:
minScoreIdx = idx
minScore = score
print('minScore: {}, minScoreIdx: {}'.format(minScore, minScoreIdx))
playerScores.pop(minScoreIdx)
for idx, score in enumerate(playerScores):
if maxScoreIdx == 0 or maxScore < score:
maxScoreIdx = idx
maxScore = score
print('maxScore: {}, maxScoreIdx: {}'.format(maxScore, maxScoreIdx))
playerScores.pop(maxScoreIdx)
print('playerScores: {}'.format(playerScores))
remove()
subjects = ['Korean', 'English', 'Math', 'Science', 'History']
print('Test subjects: {}'.format(subjects))
removeSubject = input('Input a subject to remove: ')
while removeSubject in subjects:
subjects.remove(removeSubject)
print('Test subjects: {}'.format(subjects))
extend()
myFavoriteNumbers = [1, 3, 5, 6, 7]
friendFavoriteNumbers = [2, 3, 5, 8, 10]
print('myFavoriteNumbers: {}'.format(myFavoriteNumbers))
print('friendFavoriteNumbers: {}'.format(friendFavoriteNumbers))
addList = myFavoriteNumbers + friendFavoriteNumbers
print('addList: {}'.format(addList))
result = []
for number in addList:
if number not in result:
result.append(number)
print('result: {}'.format(result))
sort()
sort(reverse=True)
: sort items in a descending orderplayerScore = [9.5, 8.9, 9.2, 9.8, 8.8, 9.0]
print('playerScore = {}'.format(playerScore))
playerScore.sort()
print('playerScore = {}'.format(playerScore))
playerScore.pop(0)
playerScore.pop(len(playerScore)-1)
print('playerScore = {}'.format(playerScore))
sum = 0
avg = 0
for score in playerScore:
sum += score
avg = sum / len(playerScore)
print('sum: %.2f' % sum)
print('avg: %.2f' % avg)
reverse()
secret = '27156231'
secretList = []
solvedList = ''
for cha in secret:
secretList.append(int(cha))
secretList.reverse()
print('secretList: {}'.format(secretList))
val = secretList[0] * secretList[1]
secretList.insert(2, val)
val = secretList[3] * secretList[4]
secretList.insert(5, val)
val = secretList[6] * secretList[7]
secretList.insert(8, val)
val = secretList[9] * secretList[10]
secretList.insert(11, val)
print('secretList: {}'.format(secretList))
students = ['Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung']
print('students: {}'.format(students))
print('students: {}'.format(students[2:4]))
print('students: {}'.format(students[:4]))
print('students: {}'.format(students[2:]))
print('students: {}'.format(students[2:-2]))
print('students: {}'.format(students[-5:-2]))
numbers = [2, 50, 0.12, 1, 9, 7, 17, 35, 100, 3.14]
print('numbers: {}'.format(numbers))
print('numbers: {}'.format(numbers[2:-2]))
print('numbers: {}'.format(numbers[2:-2:2]))
print('numbers: {}'.format(numbers[:-2:2]))
print('numbers: {}'.format(numbers[::2]))
students = ['Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung']
print('students: {}'.format(students))
students[1:4] = ['John Hong', 'Kevin Park', 'Jack Kim']
print('students: {}'.format(students))
students = ['Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung']
print('students: {}'.format(students))
print('students: {}'.format(students[slice(2, 4)]))
print('students: {}'.format(students[slice(4)]))
print('students: {}'.format(students[slice(2, len(students))]))
index(item)
index(item, 2, 6)
: find the item with the index between 2 and 5import random
sampleList = random.sample(range(1, 11), 10)
selectIdx = int(input('Input the index of 7: '))
searchIdx = sampleList.index(7)
if searchIdx == selectIdx:
print('Correct')
else:
print('Wrong')
print('sampleList: {}'.format(sampleList))
print('searchIdx: {}'.format(searchIdx))
count()
students = ['Hong', 'Kang', 'Park', 'Lee', 'Kim', 'Park']
print('students: {}'.format(students))
searchCnt = students.count('Park')
print('searchCnt: {}'.format(searchCnt))
del
del list[i]
: delete the item with index i in the liststudents = ['Hong', 'Kang', 'Park', 'Lee', 'Kim', 'Park']
del students[1]
print('students: {}'.format(students))
students = ['Hong', 'Kang', 'Park', 'Lee', 'Kim', 'Park']
del students[1:4]
print('students: {}'.format(students))
inputNum = int(input('Input an integer > 1: '))
listA = []
listB = []
for n in range(1, inputNum+1):
if n == 1:
listA.append(n)
else:
if inputNum % n == 0:
listA.append(n)
for number in range(2, inputNum+1):
flag = True
for n in range(2, number):
if number % n == 0:
flag = False
break
if flag:
listB.append(number)
print('listA: {}'.format(listA))
print('listB: {}'.format(listB))
numbers = [2, 22, 7, 8, 9, 2, 7, 3, 5, 2, 7, 1, 3]
print(f'numbers = {numbers}')
idx = 0
while True:
if idx >= len(numbers):
break
if numbers.count(numbers[idx]) >= 2:
numbers.remove(numbers[idx])
continue
idx += 1
print(f'numbers = {numbers}')
students = ['Hong', 'Kim', 'Park', 'Lee', 'Choi', 'Chung']
print('--Students with even indices--')
for idx, student in enumerate(students):
if idx % 2 == 0:
print('student[{}]: {}'.format(idx, student))
print('--Students with odd indices--')
for idx, student in enumerate(students):
if idx % 2 != 0:
print('student[{}]: {}'.format(idx, student))
in, not in
in
: True if the item is in the tuple, list, str, etc.not in
: True if the item is not in the tuple, list, str, etc.studentsTuple = ('Hong', 'Kim', 'Park', 'Lee')
searchName = input('Input student name: ')
if searchName in studentsTuple:
print('{} is in our class.'.format(searchName))
else:
print('{} is not in our class.'.format(searchName))
len(tuple)
myFavoriteSports = ('Swimming', 'Soccer', 'Volleyball', 'Baseball')
for i in range(len(myFavoriteSports)):
print('myFavoriteSports[{}]: {}'.format(i, myFavoriteSports[i]))
n = 0
fLength = len(myFavoriteSports)
while n < len(myFavoriteSports):
print('myFavoriteSports[{}]: {}'.format(n, myFavoriteSports[n]))
n += 1
for f in myFavoriteSports:
print('myFavoriteSports: {}'.format(f))
tuple3 = tuple1 + tuple2
myNumbers = (1, 3, 5, 6, 7)
friendNumbers = (2, 3, 5, 8, 10)
print('myNumbers = {}'.format(myNumbers))
print('friendNumbers = {}'.format(friendNumbers))
for number in friendNumbers:
if number not in myNumbers:
myNumbers += (number, )
print('myNumbers = {}'.format(myNumbers))
students = ['Hong', 'Kim', 'Park', 'Lee', 'Chung', 'Choi']
print('students: {}'.format(students))
students[1:4] = ('John Hong', 'Jack Kim', 'Steve Park')
print('students: {}'.format(students))
print(type(students))
playerScore = (9.5, 8.9, 9.2, 9.8, 8.8, 9.0)
print('playerScore: {}'.format(playerScore))
print('playerScore type: {}'.format(type(playerScore)))
playerScore = list(playerScore)
print('playerScore type: {}'.format(type(playerScore)))
playerScore.sort()
print('playerScore: {}'.format(playerScore))
playerScore.pop(0)
playerScore.pop(len(playerScore) - 1)
print('playerScore: {}'.format(playerScore))
playerScore = tuple(playerScore)
print('playerScore: {}'.format(playerScore))
sorted()
students = ('Hong', 'Park', 'Lee', 'Kim', 'Choi', 'Chung')
sortedStudents = sorted(students)
print('sortedStudents type: {}'.format(type(sortedStudents)))
print('sortedStudents: {}'.format(sortedStudents))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)
sum = 0
avg = 0
for classNo, cnt in studentCnts:
print('Number of students in Class {}: {}'.format(classNo, cnt))
sum += cnt
print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)
minClassNo = 0; maxClassNo = 0
minCnt = 0; maxCnt = 0
for classNo, cnt in studentCnts:
if minCnt == 0 or minCnt > cnt:
minClassNo = classNo
minCnt = cnt
if maxCnt == 0 or maxCnt < cnt:
maxClassNo = classNo
maxCnt = cnt
print('Class with the least students (number of students): Class {} ({} students)'.format(minClassNo, minCnt))
print('Class with the most students (number of students): Class {} ({} students)'.format(maxClassNo, maxCnt))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)
sum = 0
avg = 0
n = 0
while n < len(studentCnts):
classNo = studentCnts[n][0]
cnt = studentCnts[n][1]
print('Number of students in Class {}: {}'.format(classNo, cnt))
sum += cnt
n += 1
print('Total number of students: {}'.format(sum))
print('Average number of students: {}'.format(sum / len(studentCnts)))
studentCnts = (1, 18), (2, 19), (3, 23), (4, 21), (5, 20), (6, 22), (7, 17)
minClassNo = 0; maxClassNo = 0
minCnt = 0; maxCnt = 0
n = 0
while n < len(studentCnts):
if minCnt == 0 or minCnt > studentCnts[n][1]:
minClassNo = studentCnts[n][0]
minCnt = studentCnts[n][1]
if maxCnt == 0 or maxCnt < studentCnts[n][1]:
maxClassNo = studentCnts[n][0]
maxCnt = studentCnts[n][1]
n += 1
print('Class with the least students: Class {} with {} students'.format(minClassNo, minCnt))
print('Class with the most students: Class {} with {} students'.format(maxClassNo, maxCnt))
tuple1 = (1, 3, 2, 6, 12, 5, 7, 8)
tuple2 = (0, 5, 2, 9, 8, 6, 17, 3)
tempUnion = list(tuple1)
tempInter = list()
for n in tuple2:
if n not in tempUnion:
tempUnion.append(n)
else:
tempInter.append(n)
tempUnion = tuple(sorted(tempUnion))
tempInter = tuple(sorted(tempInter))
print(f'Union: {tempUnion}')
print(f'Intersection: {tempInter}')
fruits = ({'Watermelon':8}, {'Grape':13}, {'Cantaloupe':7}, {'Apple':17}, {'Plum':19}, {'Grapefruit':15})
fruits = list(fruits)
cIdx = 0; nIdx = 1
eIdx = len(fruits) - 1
flag = True
while flag:
cDic = fruits[cIdx]
nDic = fruits[nIdx]
cDicCnt = list(cDic.values())[0]
nDicCnt = list(nDic.values())[0]
if nDicCnt < cDicCnt:
fruits.insert(cIdx, fruits.pop(nIdx))
nIdx = cIdx + 1
continue
nIdx += 1
if nIdx > eIdx:
cIdx += 1
nIdx = cIdx + 1
if cIdx == 5:
flag = False
fruits = tuple(fruits)
print(fruits)
get()
None
)factorialDic = {}
for i in range(11):
if i == 0:
factorialDic[i] = 1
else:
for j in range(1, i+1):
factorialDic[i] = factorialDic[i-1] * j
print(f'factorialDic: {factorialDic}')
myBodyInfo = {'name': 'John', 'weight': 83.0, 'height': 1.8}
myBMI = myBodyInfo['weight'] / myBodyInfo['height'] ** 2
print(f'myBodyInfo: {myBodyInfo}')
print(f'myBMI: {round(myBMI, 2)}')
date = 0
while True:
date += 1
myBodyInfo['weight'] = round(myBodyInfo['weight'] - 0.3, 2)
print('weight: {}'.format(myBodyInfo['weight']))
myBodyInfo['height'] = round(myBodyInfo['height'] + 0.001, 3)
print('height: {}'.format(myBodyInfo['height']))
myBMI = myBodyInfo['weight'] / myBodyInfo['height'] ** 2
if date >= 30:
break
print(f'myBodyInfo: {myBodyInfo}')
print(f'myBMI: {round(myBMI, 2)}')
keys()
: return an iterable collection of keysvalues()
: return an iterable collection of valuesitems()
: return an iterable collection of itemsmemInfo = {'name':'Hong', 'email':'hong@gmail.com', 'year':3, 'hobby':['basketball', 'swimming']}
ks = memInfo.keys()
print(f'ks: {ks}')
print(f'ks type: {type(ks)}')
vs = memInfo.values()
print(f'vs: {vs}')
print(f'vs type: {type(vs)}')
items = memInfo.items()
print(f'items: {items}')
print(f'items type: {type(items)}')
list()
memInfo = {'name':'Hong', 'email':'hong@gmail.com', 'year':3, 'hobby':['basketball', 'swimming']}
ks = memInfo.keys()
ks = list(ks)
print(f'ks: {ks}')
print(f'ks type: {type(ks)}')
del
: delete an itempop()
: delete an item and return the deleted itemmemInfo = {'name':'Hong', 'email':'john@gmail.com', 'year':3, 'hobby':['basketball', 'swimming']}
print(f'memInfo: {memInfo}')
returnValue = memInfo.pop('name')
print(f'memInfo: {memInfo}')
print(f'returnValue: {returnValue}')
print(f'returnValue type: {type(returnValue)}')
in
: True if in keysnot in
: True if not in keyslen()
: length of a dictclear()
: delete all items in a dictimport string
import random
def randomPassword(length=7):
password_characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(password_characters) for i in range(length))
def randomID(length=5):
id_characters = string.ascii_uppercase
return ''.join(random.choice(id_characters) for i in range(length))
members = {}
n = 0
flag = True
while flag:
members[randomID()] = randomPassword()
n += 1
if n >= 10:
flag = False
for key, value in members.items():
print(key, ': ', value)
memID = input('Input ID: ')
memPW = input('Input PW: ')
if memID in members:
if members[memID] == memPW:
print('Login successful')
else:
print('Check your password')
else:
print('Check your ID')
members = {}
n = 1
while n < 6:
email = input('Input email: ')
pw = input('Input password: ')
if email in members:
print('This email is already being used')
continue
else:
members[email] = pw
n += 1
for key in members.keys():
print(f'{key}: {members[key]}')
while True:
delMail = input('Input email to delete: ')
if delMail in members:
delPw = input('Input password: ')
if members[delMail] == delPw:
del members[delMail]
print(f'{delMail} has been deleted')
break
else:
print('Check your password')
else:
print('Check your email')
for key in members.keys():
print(f'{key}: {members[key]}')
students = {
'S21-0001': {'name': 'Choi',
'gender': 'M',
'major': 'design',
'phone': '010-1234-5678',
'email': 'choi@gmail.com',
'hobby': ['Basketball', 'Music']},
'S21-0002': {'name': 'Kim',
'gender': 'F',
'major': 'economics',
'phone': '010-1234-5678',
'email': 'kim@gmail.com',
'hobby': ['Soccer', 'Weightlifting']},
'S21-0003': {'name': 'Park',
'gender': 'F',
'major': 'history',
'phone': '010-1234-5678',
'email': 'park@gmail.com',
'hobby': ['Game', 'MMA']}
}
for k1 in students.keys():
print('-' * 40)
print('Student ID: {}'.format(k1))
student = students[k1]
for k2 in student.keys():
print('{}: {}'.format(k2, student[k2]))
print('-' * 40)
studentID = input('Input student ID: ')
student = students[studentID]
for k3 in student.keys():
print('{}: {}'.format(k3, student[k3]))