W2D1 221127 Python 기본

Jin Bae·2022년 11월 22일
0

스파르타코딩클럽

목록 보기
4/35

Python 기본 기능을 복습하자!

String 문자열

  • Strings are an array of character
    - Can be indexed
    • Can be sliced
# Indexing 인덱싱
f="abcdefghijklmnopqrstuvwxyz"
f[1]	# b

# Slicing 슬라이싱
f[4:15]  # efghijklmno From f[4] to f[15]
  • Can be split with split()
email = 'abc@abc.com'
domain = email.split('@)[1]		# abc.com
domain = email.split('@)[1].split('.')[0]	# abc

List

  • Lists are an ordered list of values
    - Its length can be determined by len()
    • Can be sliced similar to string
    • Lists can be inside lists
    • Add values using append() or an operator
a = [1, 2, 3]
a.append(4)		# a = [1, 2, 3, 4]

a += 5 			# a = [1, 2, 3, 4, 5]
  • Can be sorted using sort()
a = [2, 5, 3]
a.sort()
print(a)   # [2, 3, 5]

a.sort(reverse=True)
print(a)   # [5, 3, 2]
  • Find values using in
a = [2, 1, 4, "2", 6]
print(1 in a)      # True
print("1" in a)    # False
print(0 not in a)  # True

Dictonary

  • Made up of a key and value
dict = {'key':'someKey', value: 0}
  • Can be made using dict = {} or dict = dict()
  • Can be made up of a dictionary inside of a dictionary
  • Use in to dermine if a key is in the dict (returns Boolean)
  • Use indexes similar to a list

If, else, elif

  • if executes code if True
  • When if is False, use elif to execute code if True
  • When if and elif are False, execute else
if condition == True :
	print("if executed")
elif condition2 == True:
	print("if is False, elif executed")
else:
	print("if and elif are False, else executed")

For

  • Runs through every element
fruits = ['사과', '배', '감', '귤']

for fruit in fruits:
    print(fruit)

Enumerate

  • Returns (index, value)
for index, value in enumerate(list):
	print(index,value)

Break

  • Stops for loop, usually when some if condition is triggered

Function

  • Create a function using def funcName(input):

Tuple

  • Similar to lists, but cannot be changed (similar to const vs. var)
  • Tuples are created using (), as opposed to list []

Set

  • Removes duplicates if converting a list into a set
a = [1,2,3,4,5,3,4,2,1,2,4,2,3,1,4,1,5,1]

a_set = set(a)

print(a_set)	# {1,2,3,4,5}

# Intersection, union, and difference using sets
a = ['사과','감','수박','참외','딸기']
b = ['사과','멜론','청포도','토마토','참외']

a = set(a)
b = set(b)
print(a & b)  # 교집합 Intersection
print(a | b)  # 합집합 Union
print(a - b)  # 차집합 Difference

f-string

  • Strings can be written in f-string to use variables directly in the string and improve readability
  • Write f in front of ' to create a f-string
# Without f-string
print(name+'는 '+score+'점 입니다')

# With f-string
print(f'{name}{score}점입니다')

Try, except

  • Used to figure out errors
try:
	function()
# if function() throws an error, except is executed
except:
	print('Error')

Read a file

If there is a Python file in the same directory and you would like to use its functions, use: from diffFile import *

Map, filter, lambda

people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]

def check_adult(person):
    if person['age'] > 20:
        return '성인'
    else:
        return '청소년'

# Run every index in 'people' with function 'check_adult' with map
# then print map in a list
result = map(check_adult,people)

# Change function check_adult into lambda form
result = map(lambda person: ('성인' if person['age'] > 20 else '청소년'), people)
print(list(result))

#Filter is similar to map, but picks values that are True
result = filter(lambda person: person['age'] > 20, people)

0개의 댓글