본문 바로가기
Web development/Algorithm

Python Basic Syntax

by 자몬다 2023. 8. 22.

arithmatic operators

1 + 3
>> 4

1 - 3
>> -2

1 / 3
>> 0.3333333

5 // 2 # quotator
>> 2

5 % 2 # remainder
>> 1

divmod(5, 2) # quotator and remainder at once
>> (2, 1)

division by 0 occurs ZeroDivisionError

 

if

if a % 2 === 0 or a > 10:
	print("")
elif a > b and a // b > 1: # // is for get the quotient
	print()
else:
	print()

# tenary operator
'짝수' if a % 2 == 0 else '홀수'

 

 

for문

for x in family:
  print(x, len(x))

list(range(2,7)) # [2,3,4,5,6] including 2, less than 7

for i in range(2,7):
  print(i)

for i in range(0,10):
  if i > 5:
		break
else:
	print(1) # it'll not printed out because of break

# if it doesn't break, else will be executed after for loop
# same as while

 

while

while num<100:
	print(num)
	num += 1
	if num > 10:
		break

 

List

a = [1, 2, 3]
a = [x for x in range(1,4)]
len(a) # 3

# remove item
a.remove(1) # [2, 3]

 

match-case (switch)

for n in range(1, 101):
    match (n % 3, n % 5):
        case (0, 0):
            print("FizzBuzz")
        case (0, _): # _ means it allows any value
            print("Fizz")
        case (_, 0):
            print("Buzz")
        case _:
            print(n)

 

type converting

 

# number -> string
str(13)
repr(123.123)

# string -> number
int(123) # 123
float(123) # 123.0

# formatting
"{}{}".format(123, "ab") # "123ab"
f'{123}{ab}' # "123ab"

'{}' works same as '${}' in javascript

 

filter

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

# make a list with including "a"
newlist = [x for x in fruits if "a" in x] 

# uppercase list
newlist = [x.upper() for x in fruits]

# orange instead of banana
newlist = [x if x != "banana" else "orange" for x in fruits]

 

댓글