Python์ with ๊ฐ๋ ์ ๊ณต๋ถํ๋ค๊ฐ ๋ฌธ๋ฉ ๊ถ๊ธํ ์ ์ด ์๊ฒผ๋ค.
์๋์ ์ฝ๋์์ contents์ my_file ๊ฐ์ด with ๊ตฌ๋ฌธ์ ๋ฒ์ด๋๋ ์ฝํ๊น?
with open("text.txt", "r") as my_file:
contents = my_file.read()
print(my_file) # <_io.TextIOWrapper name='text.txt' mode='r' encoding='UTF-8'>
print(contents) # <class 'str'> hello
๋งค์ฐ ์ ์ฝํ๋ค... ์์ง๐ค
https://stackoverflow.com/questions/45100271/scope-of-variable-within-with-statement
Scope of variable within "with" statement?
I am reading only firstline from python using : with open(file_path, 'r') as f: my_count = f.readline() print(my_count) I am bit confused over scope of variable my_count. Although prints work...
stackoverflow.com
def hello():
for i in range(10):
print("hi")
try:
print(i)
except IndexError as e:
print(e)
hello()
hello ํจ์ ๋ด๋ถ์ i๋ฅผ ๋ณด๋ฉด ๋ง์น ์ง์ญ๋ณ์๋ผ์ IndexError๊ฐ ๋ฐ์ํ ๊ฒ ๊ฐ๋ค.
๊ทธ๋ฌ๋ print(i)๋ ์ ์์ ์ผ๋ก 9๊ฐ ์ถ๋ ฅ๋๋ค.
A with statement does not create a scope (like if, for and while do not create a scope either).
As a result, Python will analyze the code and see that you made an assignment in the with statement, and thus that will make the variable local (to the real scope).
์ฆ, ์ ์์ ์์ ๋๋ local variable i๋ฅผ ์ ์ธํ ๊ฒ์ด ๋๋ค.(hello ํจ์ ๋ด๋ถ์)
StackOverflow์์ ์๋์ ๊ธ์ ๋ณด๋ฉด ๊ตณ์ด for loop์ control variable์ ์ด๋ ค๋ ํ์๊ฐ ์๋๋์ ๋ํ ํ ๋ก ์ด ๊ฝค ์๋ ๋ฏํ๋ค.
https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops
Scoping in Python 'for' loops
I'm not asking about Python's scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intende...
stackoverflow.com
๊ทธ๋ฌ๋, ๋๋ค์๋ Python์ ๊ฐ๋จํ ๋ฌธ๋ฒ์ ๋ํด ํฐ ์ค๋ฅ ์์ด ๋ง์กฑํ๊ณ ์๋ค๊ณ ํ๋ค.
๊ฒฐ๋ก
Python์ ๋ณ์ ์ค์ฝํ๋ ํจ์ ๋ฒ์์ด๋ค.
if, for, while, with์ ์ค์ฝํ๋ฅผ ์์ฑํ์ง ์๋๋ค. ์ฆ, C/C++/Java๋ฅผ ์ฌ์ฉํ๋ฉด์ ์ง์ญ๋ณ์์ผ ๊ฒ์ด๋ผ๊ณ ์์ํ๊ณ ์ ์ธํ ๋ณ์๊ฐ ์ฌ์ ํ ์ ํจํ ์๋ ์๋ค๋ ๊ฒ์ด๋ค.
Python์ผ๋ก ์ฝ๋ฉํ ๋ ์ด์ ์ ์ ์ํด์ผ๊ฒ ๋ค.
'Languages > Python ๐' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] Handling (Exception, File, Directory, Data) (0) | 2021.01.22 |
---|---|
[Python] Python์ ์๋ฃ๊ตฌ์กฐ (0) | 2021.01.21 |
[Python] Immutable ๊ฐ์ฒด์ Mutable ๊ฐ์ฒด (0) | 2021.01.19 |