Python'da Fonksiyon Yazımı
Shayne Miel
Software Architect @ Duo Security
def copy(src, dst): """Bir dosyanın içeriğini diğerine kopyalar. Args: src (str): Kopyalanacak dosyanın adı. dst (str): Yeni dosyanın yazılacağı yer. """# Kaynak dosyayı aç ve içeriği oku with open(src) as f_src: contents = f_src.read() # Hedef dosyayı aç ve içeriği yaz with open(dst, 'w') as f_dst: f_dst.write(contents)
with open('my_file.txt') as my_file:
for line in my_file:
# do something
def copy(src, dst): """Bir dosyanın içeriğini diğerine kopyalar. Args: src (str): Kopyalanacak dosyanın adı. dst (str): Yeni dosyanın yazılacağı yer. """# Her iki dosyayı aç with open(src) as f_src: with open(dst, 'w') as f_dst:# Satır satır oku ve yaz for line in f_src: f_dst.write(line)
def get_printer(ip): p = connect_to_printer(ip) yield # Bu MUTLAKA çağrılmalı, yoksa # başka kimse yazıcıya bağlanamaz p.disconnect() print('disconnected from printer')doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
printer.print_page(doc['txt'])
KeyError: 'txt'
try: # code that might raise an error except: # do something about the errorfinally: # this code runs no matter what
def get_printer(ip): p = connect_to_printer(ip) try: yield finally: p.disconnect() print('disconnected from printer')doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
disconnected from printer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
printer.print_page(doc['txt'])
KeyError: 'txt'
| Aç | Kapat |
| Kilitle | Serbest bırak |
| Değiştir | Sıfırla |
| Gir | Çık |
| Başlat | Durdur |
| Kurulum | Söküm |
| Bağlan | Bağlantıyı kes |
Python'da Fonksiyon Yazımı