{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Bu dersteki bütün IPython Notebook'lar adresinde https://github.com/sinanonur/Python-Lectures mevcuttur ve [bu adres](https://github.com/rajathkumarmp/Python-Lectures)teki içerik Türkçe'ye çevirilerek hazırlanmıştır. Bazı kısımlarda değişiklik yapılmıştır." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Fonksiyonlar" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Çoğu zaman bir algoritmada tekrar eden ifadeler olacaktır ve bunu her seferinde yazmak oldukça zor olacaktır birsürü bellek harcayacaktır ve etkili olmayacaktır. Çözüm fonksiyonlarda.icient. Enter Functions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bir fonksiyonun söz dizimi aşşağıdaki gibidir:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "def fonksiyonadi(arg1, arg2,... argN):\n", " \n", " ''' Document String'''\n", "\n", " ifadeler(statements)\n", "\n", "\n", " return <deger>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yukarıdaki ifade şu şekilde okunaiblir; 'fonksiyonadi' isminde bir bir fonksiyon \"arg1,arg2,....argN\" parametrelerini alır ve dökümantasyonu '''Document String''' şeklindedir. Çalıştıktan sonra bir \"deger\" döndürür." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selam!\n", "Naber?\n" ] } ], "source": [ "print \"Selam!\"\n", "print \"Naber?\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yukarıdaki iki ifadeyi her seferinde yazmak yerine bir fonksiyon tanımlanaral aynı iş tek bir satırda yapabilir." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def ilk_fonksiyon():\n", " print \"Selam!\"\n", " print \"Naber?\" " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selam!\n", "Naber?\n" ] } ], "source": [ "ilk_fonksiyon()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**ilk_fonksiyon()** her çalıştığında kullanıcıya sadece bu mesajı gösterir. **ilk_fonksiyon()**'a bir parametre ekleyerek bir isme hitap etmesini sağlayabiliriz. Parametre gösterildiği gibi eklenir:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def ilk_fonksiyon(isim):\n", " print \"Selam\", isim, '!'\n", " print \"Naber\", isim, '?'" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Lütfen isminizi girin:Sinan\n" ] } ], "source": [ "isim1 = raw_input('Lütfen isminizi girin:')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "girdiğiniz isim isim1 içinde saklanır. Bu değişkeni **ilk_fonksiyon()** a argüman olarak verebiliriz." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selam Sinan !\n", "Naber Sinan ?\n" ] } ], "source": [ "ilk_fonksiyon(isim1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Kullanıcıdan bir isim alıp bunu **ilk_fonksiyon()**a parametre olarak gönderen diğer bir **ikinci_fonksiyon()** ekleyerek işleri daha basit hale getirebiliriz." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def ilk_fonksiyon(isim):\n", " print \"Selam\", isim, '!'\n", " print \"Naber\", isim, '?'\n", "def ikinci_fonksiyon():\n", " isim = raw_input(\"Lütfen isminizi girin: \")\n", " ilk_fonksiyon(isim)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Lütfen isminizi girin: Sinan\n", "Selam Sinan !\n", "Naber Sinan ?\n" ] } ], "source": [ "ikinci_fonksiyon()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Return ifadesi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bir fonksiyon bir değer hesapladığında ve bu değer bir değişken içinde saklanması gerektiğinde bu değerin döndürülmesi gerekir. Bunun için return ifadesi kullanılır." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def carp(x,y):\n", " z = x*y\n", " return z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yukarıda tanımlanan **kere( )** fonksiyonu 2 argüman alarak sonuç olan z değişkeninin değerini döndürür.carp" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n" ] } ], "source": [ "c = carp(4,5)\n", "print c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "z değeri c değişkeninde saklanarak diğer işlemler için kullanılabilir." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Başka bir değişken tanımlamadan return ifadesi aşşağıdaki şekilde de yazılabilir." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def carp(x,y):\n", " '''iki argümanı birbiriyle çarpar'''\n", " return x*y" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n" ] } ], "source": [ "c = carp(4,5)\n", "print c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**carp( )** fonksiyonunu tanımladığımıza göre yukarıda görüldüğü gibi dökümante edebiliriz. **carp( )** tanımlı olduğuna göre artık **help( )** kullanarak dökümantasyonu görüntüleyebiliriz." ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function carp in module __main__:\n", "\n", "carp(x, y)\n", " iki argümanı birbiriyle çarpar\n", "\n" ] } ], "source": [ "help(carp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Birden fazla değişken de döndürülebilir fakat sırasına dikkat edin." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": true }, "outputs": [], "source": [ "liste = [10,50,30,12,6,8,100]" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def egfunc(liste):\n", " en_cok = max(liste)\n", " en_az = min(liste)\n", " ilk = eglist[0]\n", " son = eglist[-1]\n", " return en_cok,en_az,ilk,son" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Eğer fonksiyonun dönen değeri bir değişkene atanmamışsa bir tuple şeklinde döner. Fakat değişkenler kullanılırsa döndürme sırasına göre değişkenlere değerler atanır." ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(100, 6, 10, 100)" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "egfunc(liste)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " a = 100 \n", " b = 6 \n", " c = 10 \n", " d = 100\n" ] } ], "source": [ "a,b,c,d = egfunc(liste)\n", "print ' a =',a,'\\n b =',b,'\\n c =',c,'\\n d =',d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dahili argümanlar" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Eğer bir fonksiyonun bir argümanı çoğu durum için aynıysa dahili (implicit) argüman kullanılır." ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def dahili_ekle(x,y=3):\n", " return x+y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**dahili_ekle( )** iki argüman alan bir fonksiyondur. Fakat çoğu zaman ilk argümana sadece 3 eklenecektir bu yüzden 3 dahili argümandır." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Eğer fonksiyon çağrılırken ikinci argüman belirtilmemişse 3 olduğu varsayılır." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dahili_ekle(4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fakat ikinci argüman verilirse dahili değerin üstüne yazar." ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dahili_ekle(4,4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sınırsız sayıda argüman" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Eğer bir fonksiyon tarafından kabul edilecek parametrelerin sayısı tam olarak bilinmiyorsa argümandan önce yıldız sembolü koyulur." ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def n_ekle(*args):\n", " sonuc = 0\n", " sonuc_liste = []\n", " for i in args:\n", " sonuc_liste.append(i)\n", " print sonuc_liste\n", " return sum(sonuc_liste)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yukarıdaki fonksiyon her sayıda argüman kabul eder, bir liste oluşturur ve bunların toplamını döndürür." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5]\n" ] }, { "data": { "text/plain": [ "15" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n_ekle(1,2,3,4,5)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n" ] }, { "data": { "text/plain": [ "6" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n_ekle(1,2,3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Global and Lokal değişkenler" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Eğer bir değişken bir fonksiyon içinde tanımlanmışsa yerel değişken, dışında tanımlanmışsa global değişkendir." ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [], "source": [ "o1 = [1,2,3,4,5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Aşşağıdaki örnekte fonksiyonun içerisinde bir listeye bir eleman ekliyoruz. fonksiyonun içinde tanımlanan o2 lokaa değişkendir." ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def ornek_fonksiyon():\n", " def ucuncu_fonksiyon(arg1):\n", " o2 = arg1[:]\n", " o2.append(6)\n", " print \"Bu fonksiyonun içinde oluyor:\", o2 \n", " print \"Bu fonksiyonçağırılmadan oluyor: \", o1\n", " ucuncu_fonksiyon(o1)\n", " print \"Bu fonksiyonun dışında oluyor :\", o1 \n", " print \"İçeride tanımlanmış bir değişkene dışarıdan erişmeye çalışmak :\" , o2" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Bu fonksiyonçağırılmadan oluyor: [1, 2, 3, 4, 5]\n", "Bu fonksiyonun içinde oluyor: [1, 2, 3, 4, 5, 6]\n", "Bu fonksiyonun dışında oluyor : [1, 2, 3, 4, 5]\n", "İçeride tanımlanmış bir değişkene dışarıdan erişmeye çalışmak :" ] }, { "ename": "NameError", "evalue": "global name 'o2' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m<ipython-input-41-f9681853e4a8>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mornek_fonksiyon\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m<ipython-input-40-e382e4cafe79>\u001b[0m in \u001b[0;36mornek_fonksiyon\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mucuncu_fonksiyon\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mo1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0;34m\"Bu fonksiyonun dışında oluyor :\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mo1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0;34m\"İçeride tanımlanmış bir değişkene dışarıdan erişmeye çalışmak :\"\u001b[0m \u001b[0;34m,\u001b[0m \u001b[0mo2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: global name 'o2' is not defined" ] } ], "source": [ "ornek_fonksiyon()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a **global** variable is defined as shown in the example below then that variable can be called from anywhere." ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": false }, "outputs": [], "source": [ "o3 = [1,2,3,4,5]" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def ornek_fonksiyon2():\n", " def ucuncu_fonksiyon(arg1):\n", " o3 = arg1[:]\n", " o3.append(6)\n", " print \"Bu fonksiyonun içinde oluyor:\", o3 \n", " print \"Bu fonksiyonçağırılmadan oluyor: \", o3\n", " ucuncu_fonksiyon(o1)\n", " print \"Bu fonksiyonun dışında oluyor :\", o1 \n", " print \"İçeride tanımlanmış bir değişkene dışarıdan erişmeye çalışmak :\" , o3" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Bu fonksiyonçağırılmadan oluyor: [1, 2, 3, 4, 5]\n", "Bu fonksiyonun içinde oluyor: [1, 2, 3, 4, 5, 6]\n", "Bu fonksiyonun dışında oluyor : [1, 2, 3, 4, 5]\n", "İçeride tanımlanmış bir değişkene dışarıdan erişmeye çalışmak : [1, 2, 3, 4, 5]\n" ] } ], "source": [ "ornek_fonksiyon2()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lambda Fonksiyonlar" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bu ufak fonksiyonlar bir isim olmadan tanımlanırlar ve sonucu döndürüler basit bir ifade taşırlar. Genellikle listelerle işlem yaparken çok kullanışlılardır. **lambda** anahtar sözcüğü ardından değişken iki nokta ve ilgili ifade şeklinde yazılırlar." ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "collapsed": true }, "outputs": [], "source": [ "z = lambda x: x * x" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "64" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z(8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### map" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**map( )** fonksiyonu belirtilen fonksiyonu listenin her elemanı için ayrı ayrı uygular." ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": true }, "outputs": [], "source": [ "list1 = [1,2,3,4,5,6,7,8,9]" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 4, 5, 6, 7, 8, 9, 10, 11]\n" ] } ], "source": [ "eg = map(lambda x:x+2, list1)\n", "print eg" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Aynı zamanda iki liste ekleyebilirsiniz." ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list2 = [9,8,7,6,5,4,3,2,1]" ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[10, 10, 10, 10, 10, 10, 10, 10, 10]\n" ] } ], "source": [ "eg2 = map(lambda x,y:x+y, list1,list2)\n", "print eg2" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "sadece lambda ile değil var olan fonksiyonlarla beraber de kullanılabilirler." ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['10', '10', '10', '10', '10', '10', '10', '10', '10']\n" ] } ], "source": [ "eg3 = map(str,eg2)\n", "print eg3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### filter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**filter( )** fonksiyonu bir listedeki elemanları filtrelemek için kullanılır. Bu fonksiyon sonuçları yeni bir listede döndürür." ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "collapsed": true }, "outputs": [], "source": [ "list1 = [1,2,3,4,5,6,7,8,9]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "5'ten küçük olan elemanalrı almak için:" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "filter(lambda x:x<5,list1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "aynı durumda **map()** kullanıldığında ne olduğuna dikkat edin." ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[True, True, True, True, False, False, False, False, False]" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "map(lambda x:x<5, list1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Yani diyebiliriz ki **map()** için True döndüren değerler **filter( )**kullanıldığında döndürülecektir." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "filter(lambda x:x%4==0,list1)" ] } ], "metadata": { "kernelspec": { "display_name": "Python [default]", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.12" } }, "nbformat": 4, "nbformat_minor": 0 }