Ana sayfa Genel Python – Global ve Yerel Değişkenler

Python – Global ve Yerel Değişkenler

1526
86
PAYLAŞ

Global ve Yerel değişkenler

Bu konuda global ve yerel (local) değişkenleri öğrenmeye çalışacağız.

Pythonda her bir değişkenin, fonksiyonun ve ileride göreceğimiz sınıfların(class) aslında bir kapsamı(scope) bulunur ve Python herbir değişkeni bir isim alanında (namespace) tanımlar. Değişkenlerin İsim alanı ise, bu değişkenlerin nerelerde var olduğunu ve nerelerde kullanılabileceğini gösterir.

Pythonda fonksiyonlarda tanımlanan değişkenler Python tarafından Yerel (Local) değişkenler olarak tanımlanırlar. Yani bir fonksiyon bloğunda oluşturulan değişkenler fonksiyona özgüdür ve fonksiyon çalışmasını bitirdikten sonra bu değişkenler bellekten silinir ve yok olur. Böylelikle , fonksiyon içinde tanımlanmış bir değişkene başka bir yerden erişilemez.

Pythonda en genel kapsama sahip değişkenler ise Global değişkenler olarak tanımlanırlar ve global değişkenlere tanımlandığı andan itibaren programın her yerinden ulaşabiliriz.

Yerel değişkenleri anlamak için bir tane fonksiyon tanımlayalım.

Burada fonksiyon içinde tanımlanan a değişkeni fonksiyon çağrıldığında bellekte oluşur ve fonksiyon bloğunu çalıştırdıktan sonra yok olur. Yani, a değişkeni burada bir yerel değişkendir.

Global Değişkenleri anlamak içinse şöyle bir örnek yapalım.

Peki şöyle bir kodda nasıl bir sıkıntı çıkıyor ?

Peki şöyle bir durumda kodumuz nasıl bir çıktı verecek ?

Kodumuz çalıştığında ilk olarak c isimli global değişken oluşuyor. fonksiyon çağrıldığında ise c isimli başka bir yerel değişken oluşuyor gibi düşünebilirsiniz. Böyle bir durumda elimizden iki tane c değişkeni var. Python bu durumda global c değişkeni yerine kendi yerel c değişkenini kullanıyor.

Global Deyimi

Peki bir fonksiyonda globalde tanımlanmış bir değişkeni nasıl kullanacağız ? Bunun için Pythonda global ifadesi bulunmaktadır. Şimdi aşağıdaki kodu beraber inceleyelim.

Bu durumda kodumuz ne yapıyor ? İlk olarak program başladığı zaman, bir tane global d değişkeni oluşuyor ve fonksiyonumuz çağrıldığında global d ifadesiyle globaldeki d değişkenini kullanmak istediğimizi söylüyoruz. Böyle d = 4 ifadesiyle bir tane daha d değişkeni oluşturmuyoruz. Böylelikle d =4 ifadesiyle globaldeki değişkeninin değerini değiştirmiş oluyoruz.

İşte Global ve Yerel değişkenler bu şekilde düşünülebilir. Burada gördüğümüz gibi, Yerel değişkenler bir fonksiyon bloğunda içinde tanımlanır. Peki bir if veya while bloğunda yerel bir değişken tanımlanır mı hemen bakalım.

Burada gördüğümüz gibi, if ve while bloklarında tanımlanan değişkenler yerel bir değişken yerine global bir değişken olmaktadır.

Bir sonraki konuda lambda ifadelerini öğrenmeye çalışacağız.

86 YORUMLAR

  1. Reparaciones: los materiales y mano de obra de las reparaciones efectuadas por el Servicio Oficial Siemens están garantizados durante un plazo de 2 años (garantía legal obligatoria solo 3 meses). Los repuestos originales son una garantía más de la calidad y fiabilidad de nuestras reparaciones. Nuestros repuestos son originales de fábrica y tenemos una alta disponibilidad de todos ellos, incluso para aparatos antiguos. Es posible concertar la reparación del electrodoméstico con un servicio VIP donde te atenderemos en menos de dos horas.

  2. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  3. Greetings from Colorado! I’m bored to death at work so I decided to browse your site on my iphone during lunch break. I love the info you present here and can’t wait to take a look when I get home. I’m shocked at how fast your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyhow, wonderful blog!

  4. Thank you for the auspicious writeup. It in fact was a amusement account it.

    Look advanced to more added agreeable from you! However, how can we communicate?

  5. Dentro de la ciudad de Madrid nos desplazamos a cualquier barrio de la ciudad como por ejemplo Fuencarral, El Pardo, Moncloa, Aravaca, Tetuán, Hortaleza, Chamartí, Ciudad Lineal, Chamberí, San Blas, Barajas, Centro, Retiro, Arganzuela, Moratalaz, Villaverde, Usera, Latina, Carabanchel, Vicálvaro Vallecas entre muchos otros. Es por ello que a diferencia del resto de empresas no cobramos ni desplazamiento, ni presupuesto, su bienestar equivale al nuestro. Nuestro Servicio de Reparación Teka atiende en los principales barrios de Madrid.

  6. Existe una oficina en la Capital, Santiago de Chile, que contrata servicios técnicos externos, es decir, ellos no tienen técnicos propios, todo se demora además una semana el arreglo estando a 120 kilómetros de distancia. Hace 10 años estuve en las instalaciones de HAIER en China, por mi condición de responsable de la posventa de esta Marca en España, en unión del e resto de responsables de todos los países europeos. Por esa razón, puedes tener problemas con esa marca respecto a recambios y Servicio Técnico.

  7. Hemos mantenido un nivel estándar de Cualificación para brindarle un mejor y más completo Servicio técnico sat a Nuestros Clientes en el hogar, comercio, negocios u oficina. Contamos con TécnicosCualificados a la altura estándar Europea y Experiencia a tales efectos, para brindarle una mejor Atención yAsistencia Técnica, así como la solución de cualquier problema Técnico. Ofrecemos Servicios de mantenimiento y reparación a empresas y particulares en el hogar y la industria.

  8. Donde Ch es el coste horario, incluyendo el coste de la mano de obra directa, amortización de instalaciones, mantenimiento, etc; tnp es el tiempo no productivo, que incluye los tiempos de preparación de la máquina (tiempo de fase); top es el tiempo de operación, Cf es el coste de los filos de corte, que es el coste de las plaquitas en caso de utilizar plaquitas intercambiables, el coste de toda la herramienta en el caso de herramientas enterizas; trf es el tiempo de reposición de los filos de corte; tm es el tiempo de maquinado, es decir, el tiempo durante el cual la herramienta está cortando; y T es la duración tiempo de vida de la herramienta.

  9. Ahora se va imponiendo y es fácil observar este proceso en talleres de todo tipo, por ejemplo del mencionado anteriormente, el decoletaje , que es la industria que se dedica a la fabricación de todo tipo de tornillería y similares para otras empresas.

  10. El objetivo de MEFABI S.L. es proporcionar a nuestros clientes un servicio completo y personalizado para la obtención de un producto final de la máxima calidad, con costes competitivos gracias a la continua actualización de nuestros procesos y medios de producción.

  11. you are actually a just right webmaster. The site loading pace is incredible. It kind of feels that you’re doing any unique trick. Also, The contents are masterwork. you’ve done a wonderful task on this subject!

  12. I have been exploring for a little for any high quality articles or blog posts on this kind of area . Exploring in Yahoo I at last stumbled upon this website. Reading this info So i’m happy to convey that I have a very good uncanny feeling I discovered just what I needed. I most certainly will make certain to don’t forget this web site and give it a glance regularly.

  13. Just about all of whatever you articulate is supprisingly precise and that makes me ponder the reason why I had not looked at this in this light before. This particular article really did turn the light on for me as far as this particular topic goes. But there is actually just one factor I am not really too comfy with so whilst I make an effort to reconcile that with the actual main idea of the point, allow me see just what the rest of your readers have to say.Nicely done.

  14. Whats up very cool blog!! Guy .. Excellent .. Wonderful .. I’ll bookmark your blog and take the feeds also…I am happy to find so many helpful info here in the publish, we’d like develop extra strategies on this regard, thanks for sharing. . . . . .

  15. I’ve been exploring for a bit for any high-quality articles
    or weblog posts in this kind of area . Exploring in Yahoo I finally stumbled upon this website.
    Reading this info So i am glad to exhibit that I’ve an incredibly excellent uncanny feeling I
    discovered just what I needed. I such a lot undoubtedly
    will make sure to don?t disregard this site and give it a glance regularly.

  16. I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to construct my own blog and would like to find out where u got this from. appreciate it

  17. Hiya! I know this is kinda off topic however I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?
    My site goes over a lot of the same subjects as yours and I feel we could greatly benefit from each other.
    If you are interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Excellent blog by the
    way!

  18. Hiya, I am really glad I’ve found this info. Today bloggers publish only about gossips and net and this is really irritating. A good website with interesting content, that’s what I need. Thanks for keeping this web site, I will be visiting it. Do you do newsletters? Can’t find it.

  19. There are some attention-grabbing points in time on this article but I don’t know if I see all of them center to heart. There’s some validity however I will take hold opinion till I look into it further. Good article , thanks and we wish more! Added to FeedBurner as effectively

  20. I have learn some excellent stuff here. Certainly value bookmarking for revisiting. I surprise how much attempt you set to create this type of great informative web site.

  21. Good day! I could have sworn I’ve been to this website before but after browsing through some of the post I realized it’s new to me. Nonetheless, I’m definitely delighted I found it and I’ll be bookmarking and checking back often!

  22. Whats Happening i’m new to this, I stumbled upon this I have found It absolutely useful and it has helped me out loads. I hope to give a contribution & aid different customers like its helped me. Good job.

  23. You really make it seem so easy with your presentation but I find this topic to be actually something that I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  24. Nice post. I was checking constantly this blog and I’m impressed! Extremely useful info specifically the last part 🙂 I care for such info a lot. I was looking for this particular info for a very long time. Thank you and good luck.

  25. Good – I should certainly pronounce, impressed with your website. I had no trouble navigating through all the tabs as well as related information ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Excellent task.

  26. Great – I should certainly pronounce, impressed with your site. I had no trouble navigating through all the tabs as well as related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your client to communicate. Excellent task..

  27. I have been surfing on-line greater than 3 hours these days, yet I never found any interesting article like yours. It is lovely value sufficient for me. In my opinion, if all website owners and bloggers made just right content as you did, the internet can be much more useful than ever before.

  28. It’s appropriate time to make some plans for the future and it’s time to be happy.
    I have read this post and if I could I wish to suggest
    you few interesting things or suggestions.

    Perhaps you can write next articles referring to this article.
    I wish to read even more things about it!

  29. I?¦ve read a few just right stuff here. Certainly value bookmarking for revisiting. I surprise how a lot effort you put to make one of these wonderful informative web site.

  30. Nice post. I learn something more difficult on totally different blogs everyday. It is going to all the time be stimulating to learn content material from other writers and follow a little one thing from their store. I’d favor to make use of some with the content on my blog whether or not you don’t mind. Natually I’ll give you a link on your internet blog. Thanks for sharing.

  31. Along with almost everything that appears to be building throughout this particular area, your opinions are actually rather stimulating. Nonetheless, I am sorry, because I can not give credence to your entire theory, all be it radical none the less. It appears to everyone that your remarks are generally not completely rationalized and in fact you are your self not thoroughly confident of the argument. In any event I did enjoy reading through it.

  32. 通過水光療程抑制黑色素細胞生長的成分注射到真皮層,減少黑色素形成,淡化黑斑色素沉澱,從而達到美白祛斑的效果 療程特色 :可配搭多元化產品來量身訂做不同療​​程計算機化規格,操作方便,容易控制可調節進針深度,精準注射於目標的肌膚層 每針的注射劑量相等,達到均勻注射 一次平均5點注射,可縮短療程時間 採用31號細針頭,幾乎看不到入針點 降低疼痛、瘀血、腫脹及不適感 使用靈活度高,可複合式搭配針劑,量身訂製療程

  33. Hello there, simply turned into aware of your blog via Google, and found that it is truly informative. I am going to be careful for brussels. I will be grateful in case you proceed this in future. Numerous folks shall be benefited out of your writing. Cheers!

  34. Wow! This could be one particular of the most beneficial blogs We’ve ever arrive across on this subject. Basically Great. I am also a specialist in this topic therefore I can understand your hard work.

  35. I’ve recently started a website, the info you provide on this web site has helped me tremendously. Thanks for all of your time & work. “So full of artless jealousy is guilt, It spills itself in fearing to be spilt.” by William Shakespeare.

  36. Hiya, I am really glad I’ve found this information. Nowadays bloggers publish only about gossips and internet and this is actually frustrating. A good web site with interesting content, this is what I need. Thank you for keeping this site, I’ll be visiting it. Do you do newsletters? Can not find it.

  37. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You clearly know what youre talking about, why throw away your intelligence on just posting videos to your blog when you could be giving us something enlightening to read?

  38. Heya! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing several weeks of hard work due to no back up. Do you have any methods to protect against hackers?

  39. Great ?V I should definitely pronounce, impressed with your site. I had no trouble navigating through all the tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your customer to communicate. Excellent task..

BİR CEVAP BIRAK

Lütfen yorumunuzu giriniz
Buraya isminizi giriniz