round()
(number[, ndigits])number 를 소수점 다음에 ndigits 정밀도로 반올림한 값을 돌려줍니다. ndigits 가 생략되거나 None
이면, 입력에 가장 가까운 정수를 돌려줍니다.
round()
를 지원하는 내장형의 경우, 값은 10의 -ndigits 거듭제곱의 가장 가까운 배수로 반올림됩니다; 두 배수가 똑같이 가깝다면, 반올림은 짝수를 선택합니다 (예를 들어, round(0.5)
와 round(-0.5)
는 모두 0
이고, round(1.5)
는 2
입니다). 모든 정숫값은 ndigits 에 유효합니다 (양수, 0 또는 음수). ndigits 가 생략되거나 None
이면, 반환 값은 정수입니다. 그렇지 않으면 반환 값은 number 와 같은 형입니다.
일반적인 파이썬 객체 number
의 경우, round
는 number.__round__
에 위임합니다.
참고
float에 대한 round()
의 동작은 예상과 다를 수 있습니다: 예를 들어, round(2.675, 2)
는 2.68
대신에 2.67
을 제공합니다. 이것은 버그가 아닙니다: 대부분의 십진 소수가 float로 정확히 표현될 수 없다는 사실로부터 오는 결과입니다. 자세한 정보는 부동 소수점 산술: 문제점 및 한계 를 보세요.
a == b
| a
equal to b
| a != b
| a
not equal to b
a < b
| a
less than b
| a > b
| a
greater than b
a <= b
| a
less than or equal to b
| a >= b
| a
greater than or equal to b
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
if total_candies == 1:
print("Splitting 1 candy")
else:
print("Splitting", total_candies, "candies")
print("Splitting", total_candies, "candy" if total_candies == 1 else "candies")
def is_negative(number):
if number < 0:
return True
else:
return False
def concise_is_negative(number):
return True if number < 0 else False # Your code goes here (try to keep it to one line!)
# 5a
def wants_all_toppings(ketchup, mustard, onion):
"""Return whether the customer wants "the works" (all 3 toppings)
"""
return True if ketchup == True and mustard == True and onion == True else False
# 5b
def wants_plain_hotdog(ketchup, mustard, onion):
"""Return whether the customer wants a plain hot dog with no toppings."""
return not ketchup and not mustard and not onion
We can also "factor out" the nots to get:
return not (ketchup or mustard or onion)
# 5c
def exactly_one_sauce(ketchup, mustard, onion):
"""Return whether the customer wants either ketchup or mustard, but not both.
(You may be familiar with this operation under the name "exclusive or")
"""
return ketchup ^ mustard
and
, or
and not
, but using boolean-to-integer conversion gives us this short solution:return (int(ketchup) + int(mustard) + int(onion)) == 1
Fun fact: we don't technically need to call int
on the arguments. Just by doing addition with booleans, Python implicitly does the integer conversion. So we could also write...
return (ketchup + mustard + onion) == 1
x = 12
# x is a real number, so its imaginary part is 0.
print(x.imag)
# Here's how to make a complex number, in case you've ever been curious:
c = 12 + 3j
print(c.imag)
# help 예시
help(x.bit_length)
# pop 마지막 삭제 후 반환
`list.pop` removes and returns the last element of a list
# Searching lists
# Where does Earth fall in the order of planets? We can get its index using the `list.index` method
planets.index('Earth')
# Is Earth a planet?
"Earth" in planets
>>> True
# 실습
def select_second(L):
"""Return the second element of the given list. If the list has no second
element, return None.
"""
return L[1] if len(L) > 2 else None
# 실습2
def losing_team_captain(teams):
"""Given a list of teams, where each team is a list of names, return the 2nd player (captain)
from the last listed team
"""
return teams[-1][1]
# 실습3
def purple_shell(racers):
"""Given a list of racers, set the first place racer (at the front of the list) to last
place and vice versa.
>>> r = ["Mario", "Bowser", "Luigi"]
>>> purple_shell(r)
>>> r
["Luigi", "Bowser", "Mario"]
"""
temp = racers[0]
racers[0] = racers[-1]
racers[-1] = temp
# 실습4
def fashionably_late(arrivals, name):
"""Given an ordered list of arrivals to the party and a name, return whether the guest with that
name was fashionably late.
"""
order = arrivals.index(name)
return order >= len(arrivals) / 2 and order != len(arrivals) - 1
Tuples are almost exactly the same as lists. They differ in just two ways.
1: The syntax for creating them uses parentheses instead of square brackets
1: 생성 구문은 대괄호 대신 괄호를 사용합니다. ()
2: They cannot be modified (they are immutable).
2: 수정할 수 없습니다(변경할 수 없음).
튜플은 여러 반환 값이 있는 함수에 자주 사용됩니다.
예를 들어 float 객체의 as_integer_ratio() 메서드는 분자와 분모를 튜플 형식으로 반환합니다.
x = 0.125
x.as_integer_ratio()
>>> (1, 8)
이러한 여러 반환 값은 다음과 같이 개별적으로 할당할 수 있습니다.
numerator, denominator = x.as_integer_ratio()
print(numerator / denominator)
>>> 0.125
a = 1
b = 0
a, b = b, a
print(a, b)
>>> 0 1