def set_list_vals(list_arg):
assert isinstance(list_arg, list), 'arg must be a list'
assert len(list_arg) >= 3, 'list argument too short'
list_arg[0] = 100
list_arg[1] = 200
list_arg[2] = 150
total = 0.0
while True:
s = input('Enter number: ')
if not s: # 빈-문자열이 들어오면 탈출한다.
break
total += float(s) # s가 빈-문자열이 아닐 때만 실행된다.
print(total)
Enter number: 1 Enter number: 2 Enter number: 3.0
class Dog:
pass
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
my_pt = Point(10, 20) # my_pt.x = 10, my_pt.y = 20
class foo:
x = y = 0 # class vars
@classmethod
def set_xy(cls, n, m):
cls.x = n
cls.y = m
@staticmethod
def bar():
return 100
foo.set_xy(10, 20)
foo.x, foo.y
(10, 20)
foo.bar()
100
for let in 'You moved Dover!':
if let == 'D' or let == 'd':
continue
print(let, end='')
You move over!
def hypotenuse(side1, side2):
total = side1 * side1 + side2 * side2
return total ** 0.5 # total의 제곱근 반환
def floopy():
return 100
print(floopy()) # floopy 호출, 인수는 없다! 100 출력
print(hypotenuse(3, 5))
100 5.830951894845301
a_list = [1, 2, 3]
b_list = a_list # 리스트의 별칭(alias)을 만든다
del a_list # 심볼 테이블에서 a_list 제거
print(b_list) # 리스트 참조는 여전히 존재
[1, 2, 3]
# 비틀즈 멤버를 분리된 줄에 출력한다.
beat_list = ['John', 'Paul', 'George', 'Ringo']
for guy in beat_list:
print(guy)
# 1 * 2 * ... n를 계산하는 함수 정의
def factorial(n):
prod = 1
for n in range(1, n + 1):
prod *= n
return(prod)
John Paul George Ringo
account = 1000
def clear_account():
account = 0 # 앗, 신규 지역 변수를 만든다
clear_account()
print(account) # 1000 출력, 에러다!
1000
account = 1000
def clear_account():
global account # account를 지역 변수로 만들지 않는다.
account = 0 # 저녁 변수를 0으로 설정한다!
clear_account()
print(account) # 1000이 아닌 0 출력
0
age = int(input('Enter your age: '))
if 12 < age < 20:
print('You are a teenager.')
Enter your age: 15 You are a teenager.
age = int(input('Enter age: '))
if age < 13:
print('Hello, spring chicken!')
elif age < 20:
print('You are a teenager.')
print('Do not trust x, if x > 30.')
else:
print('My, my. ')
print('We are not getting any younger are we?')
Enter age: 40 My, my. We are not getting any younger are we?
class Dog:
pass # 이 클래스는 아직 메소드가 없다.
raise
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-79-9c9a2cba73bf> in <module> ----> 1 raise RuntimeError: No active exception to reraise
def div_me(x, y):
try:
quot = x / y
except ZeroDivisionError as e:
print("Bad division! Text:", e)
else:
print("Quotient is %s." % quot)
finally:
print("Execution complete!")
div_me(2, 1)
Quotient is 2.0. Execution complete!
div_me(2, 0)
Bad division! Text: division by zero Execution complete!
div_me("2", "3")
Execution complete!
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-82-ba39a37269d3> in <module> ----> 1 div_me("2", "3") <ipython-input-80-dec61223562c> in div_me(x, y) 1 def div_me(x, y): 2 try: ----> 3 quot = x / y 4 except ZeroDivisionError as e: 5 print("Bad division! Text:", e) TypeError: unsupported operand type(s) for /: 'str' and 'str'
try:
f = open('silly.txt', 'r')
text = f.read()
print(text)
except IOError as e:
print('Problem opening file:', e)
except Exception as e:
print('That was a Bozo no-no.')
print('Error text:',e)
Problem opening file: [Errno 2] No such file or directory: 'silly.txt'
n = 10
while n > 0:
print(n, end=' ')
n -= 1 # n에서 1을 감소시킨다.
10 9 8 7 6 5 4 3 2 1
n = 10
while n:
print(n, end=' ')
n -= 1 # n에서 1을 감소시킨다.
10 9 8 7 6 5 4 3 2 1
with open('stuff.txt', 'r') as f:
print(f.read()) # 파일 내용을 출력한다.
I have added this file. The contents will be printed!!