1
0
mirror of https://github.com/adambard/learnxinyminutes-docs.git synced 2025-08-06 23:06:49 +02:00

Variables and Collections

This commit is contained in:
Eray Aydın
2015-03-25 20:34:27 +02:00
parent c5c8004450
commit 46273c1ffe

View File

@@ -17,119 +17,119 @@ Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [bur
```python ```python
# Single line comments start with a number symbol. # Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır.
""" Multiline strings can be written """ Çok satırlı olmasını istediğiniz yorumlar
using three "s, and are often used üç adet tırnak(") işareti ile
as comments yapılmaktadır
""" """
#################################################### ####################################################
## 1. Primitive Datatypes and Operators ## 1. Temel Veri Türleri ve Operatörler
#################################################### ####################################################
# You have numbers # Sayılar
3 # => 3 3 # => 3
# Math is what you would expect # Tahmin edebileceğiniz gibi matematik
1 + 1 # => 2 1 + 1 # => 2
8 - 1 # => 7 8 - 1 # => 7
10 * 2 # => 20 10 * 2 # => 20
# Except division which returns floats by default # Bölme işlemi varsayılan olarak onluk döndürür
35 / 5 # => 7.0 35 / 5 # => 7.0
# Result of integer division truncated down both for positive and negative. # Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar
5 // 3 # => 1 5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too 5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir
-5 // 3 # => -2 -5 // 3 # => -2
-5.0 // 3.0 # => -2.0 -5.0 // 3.0 # => -2.0
# When you use a float, results are floats # Onluk kullanırsanız, sonuç da onluk olur
3 * 2.0 # => 6.0 3 * 2.0 # => 6.0
# Modulo operation # Kalan operatörü
7 % 3 # => 1 7 % 3 # => 1
# Exponentiation (x to the yth power) # Üs (2 üzeri 4)
2**4 # => 16 2**4 # => 16
# Enforce precedence with parentheses # Parantez ile önceliği değiştirebilirsiniz
(1 + 3) * 2 # => 8 (1 + 3) * 2 # => 8
# Boolean values are primitives # Boolean(Doğru-Yanlış) değerleri standart
True True
False False
# negate with not # 'değil' ile terse çevirme
not True # => False not True # => False
not False # => True not False # => True
# Boolean Operators # Boolean Operatörleri
# Note "and" and "or" are case-sensitive # "and" ve "or" büyük küçük harf duyarlıdır
True and False #=> False True and False #=> False
False or True #=> True False or True #=> True
# Note using Bool operators with ints # Bool operatörleri ile sayı kullanımı
0 and 2 #=> 0 0 and 2 #=> 0
-5 or 0 #=> -5 -5 or 0 #=> -5
0 == False #=> True 0 == False #=> True
2 == True #=> False 2 == True #=> False
1 == True #=> True 1 == True #=> True
# Equality is == # Eşitlik kontrolü ==
1 == 1 # => True 1 == 1 # => True
2 == 1 # => False 2 == 1 # => False
# Inequality is != # Eşitsizlik Kontrolü !=
1 != 1 # => False 1 != 1 # => False
2 != 1 # => True 2 != 1 # => True
# More comparisons # Diğer karşılaştırmalar
1 < 10 # => True 1 < 10 # => True
1 > 10 # => False 1 > 10 # => False
2 <= 2 # => True 2 <= 2 # => True
2 >= 2 # => True 2 >= 2 # => True
# Comparisons can be chained! # Zincirleme şeklinde karşılaştırma da yapabilirsiniz!
1 < 2 < 3 # => True 1 < 2 < 3 # => True
2 < 3 < 2 # => False 2 < 3 < 2 # => False
# Strings are created with " or ' # Yazı(Strings) " veya ' işaretleri ile oluşturulabilir
"This is a string." "Bu bir yazı."
'This is also a string.' 'Bu da bir yazı.'
# Strings can be added too! But try not to do this. # Yazılar da eklenebilir! Fakat bunu yapmanızı önermem.
"Hello " + "world!" # => "Hello world!" "Merhaba " + "dünya!" # => "Merhaba dünya!"
# A string can be treated like a list of characters # Bir yazı(string) karakter listesi gibi işlenebilir
"This is a string"[0] # => 'T' "Bu bir yazı"[0] # => 'B'
# .format can be used to format strings, like this: # .format ile yazıyı biçimlendirebilirsiniz, şu şekilde:
"{} can be {}".format("strings", "interpolated") "{} da ayrıca {}".format("yazılar", "işlenebilir")
# You can repeat the formatting arguments to save some typing. # Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz.
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") "{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu")
#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" #=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir"
# You can use keywords if you don't want to count. # Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz.
"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" "{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor"
# If your Python 3 code also needs to run on Python 2.5 and below, you can also # Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız,
# still use the old style of formatting: # eski stil formatlamayı kullanabilirsiniz:
"%s can be %s the %s way" % ("strings", "interpolated", "old") "%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir")
# None is an object # Hiçbir şey(none) da bir objedir
None # => None None # => None
# Don't use the equality "==" symbol to compare objects to None # Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın
# Use "is" instead. This checks for equality of object identity. # Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir.
"etc" is None # => False "vb" is None # => False
None is None # => True None is None # => True
# None, 0, and empty strings/lists/dicts all evaluate to False. # None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü.
# All other values are True # Diğer veriler ise True değeri döndürür
bool(0) # => False bool(0) # => False
bool("") # => False bool("") # => False
bool([]) #=> False bool([]) #=> False
@@ -137,164 +137,163 @@ bool({}) #=> False
#################################################### ####################################################
## 2. Variables and Collections ## 2. Değişkenler ve Koleksiyonlar
#################################################### ####################################################
# Python has a print function # Python bir yazdırma fonksiyonuna sahip
print("I'm Python. Nice to meet you!") print("Ben Python. Tanıştığıma memnun oldum!")
# No need to declare variables before assigning to them. # Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok.
# Convention is to use lower_case_with_underscores # Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin
some_var = 5 bir_degisken = 5
some_var # => 5 bir_degisken # => 5
# Accessing a previously unassigned variable is an exception. # Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır.
# See Control Flow to learn more about exception handling. # Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz.
some_unknown_var # Raises a NameError bir_bilinmeyen_degisken # NameError hatası oluşturur
# Lists store sequences # Listeler ile sıralamaları tutabilirsiniz
li = [] li = []
# You can start with a prefilled list # Önceden doldurulmuş listeler ile başlayabilirsiniz
other_li = [4, 5, 6] diger_li = [4, 5, 6]
# Add stuff to the end of a list with append # 'append' ile listenin sonuna ekleme yapabilirsiniz
li.append(1) # li is now [1] li.append(1) # li artık [1] oldu
li.append(2) # li is now [1, 2] li.append(2) # li artık [1, 2] oldu
li.append(4) # li is now [1, 2, 4] li.append(4) # li artık [1, 2, 4] oldu
li.append(3) # li is now [1, 2, 4, 3] li.append(3) # li artık [1, 2, 4, 3] oldu
# Remove from the end with pop # 'pop' ile listenin son elementini kaldırabilirsiniz
li.pop() # => 3 and li is now [1, 2, 4] li.pop() # => 3 ve li artık [1, 2, 4]
# Let's put it back # Çıkarttığımız tekrardan ekleyelim
li.append(3) # li is now [1, 2, 4, 3] again. li.append(3) # li yeniden [1, 2, 4, 3] oldu.
# Access a list like you would any array # Dizi gibi listeye erişim sağlayın
li[0] # => 1 li[0] # => 1
# Look at the last element # Son elemente bakın
li[-1] # => 3 li[-1] # => 3
# Looking out of bounds is an IndexError # Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur
li[4] # Raises an IndexError li[4] # IndexError hatası oluşturur
# You can look at ranges with slice syntax. # Bir kısmını almak isterseniz.
# (It's a closed/open range for you mathy types.)
li[1:3] # => [2, 4] li[1:3] # => [2, 4]
# Omit the beginning # Başlangıç belirtmezseniz
li[2:] # => [4, 3] li[2:] # => [4, 3]
# Omit the end # Sonu belirtmesseniz
li[:3] # => [1, 2, 4] li[:3] # => [1, 2, 4]
# Select every second entry # Her ikişer objeyi seçme
li[::2] # =>[1, 4] li[::2] # =>[1, 4]
# Revert the list # Listeyi tersten almak
li[::-1] # => [3, 4, 2, 1] li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices # Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz
# li[start:end:step] # li[baslangic:son:adim]
# Remove arbitrary elements from a list with "del" # "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz
del li[2] # li is now [1, 2, 3] del li[2] # li artık [1, 2, 3] oldu
# You can add lists # Listelerde de ekleme yapabilirsiniz
# Note: values for li and for other_li are not modified. # Not: değerler üzerinde değişiklik yapılmaz.
li + other_li # => [1, 2, 3, 4, 5, 6] li + diger_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()" # Listeleri birbirine bağlamak için "extend()" kullanılabilir
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu
# Check for existence in a list with "in" # Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir
1 in li # => True 1 in li # => True
# Examine the length with "len()" # Uzunluğu öğrenmek için "len()" kullanılabilir
len(li) # => 6 len(li) # => 6
# Tuples are like lists but are immutable. # Tüpler listeler gibidir fakat değiştirilemez.
tup = (1, 2, 3) tup = (1, 2, 3)
tup[0] # => 1 tup[0] # => 1
tup[0] = 3 # Raises a TypeError tup[0] = 3 # TypeError hatası oluşturur
# You can do all those list thingies on tuples too # Diğer liste işlemlerini tüplerde de uygulayabilirsiniz
len(tup) # => 3 len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2) tup[:2] # => (1, 2)
2 in tup # => True 2 in tup # => True
# You can unpack tuples (or lists) into variables # Tüpleri(veya listeleri) değişkenlere açabilirsiniz
a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3
# Tuples are created by default if you leave out the parentheses # Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur
d, e, f = 4, 5, 6 d, e, f = 4, 5, 6
# Now look how easy it is to swap two values # 2 değeri birbirine değiştirmek bu kadar kolay
e, d = d, e # d is now 5 and e is now 4 e, d = d, e # 'd' artık 5 ve 'e' artık 4
# Dictionaries store mappings # Sözlükler anahtar kodlarla verileri tutar
empty_dict = {} bos_sozl = {}
# Here is a prefilled dictionary # Önceden doldurulmuş sözlük oluşturma
filled_dict = {"one": 1, "two": 2, "three": 3} dolu_sozl = {"bir": 1, "iki": 2, "uc": 3}
# Look up values with [] # Değere bakmak için [] kullanalım
filled_dict["one"] # => 1 dolu_sozl["bir"] # => 1
# Get all keys as a list with "keys()". # Bütün anahtarları almak için "keys()" kullanılabilir.
# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. # Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz.
# Note - Dictionary key ordering is not guaranteed. # Not - Sözlük anahtarlarının sıralaması kesin değildir.
# Your results might not match this exactly. # Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir.
list(filled_dict.keys()) # => ["three", "two", "one"] list(dolu_sozl.keys()) # => ["uc", "iki", "bir"]
# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. # Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor
# Note - Same as above regarding key ordering. # Not - Sıralama değişebilir.
list(filled_dict.values()) # => [3, 2, 1] list(dolu_sozl.values()) # => [3, 2, 1]
# Check for existence of keys in a dictionary with "in" # Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz
"one" in filled_dict # => True "bir" in dolu_sozl # => True
1 in filled_dict # => False 1 in dolu_sozl # => False
# Looking up a non-existing key is a KeyError # Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır.
filled_dict["four"] # KeyError dolu_sozl["dort"] # KeyError hatası oluşturur
# Use "get()" method to avoid the KeyError # "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz
filled_dict.get("one") # => 1 dolu_sozl.get("bir") # => 1
filled_dict.get("four") # => None dolu_sozl.get("dort") # => None
# The get method supports a default argument when the value is missing # "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz.
filled_dict.get("one", 4) # => 1 dolu_sozl.get("bir", 4) # => 1
filled_dict.get("four", 4) # => 4 dolu_sozl.get("dort", 4) # => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present # "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip
# Adding to a dictionary # Sözlüğe ekleme
filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4}
#filled_dict["four"] = 4 #another way to add to dict #dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu
# Remove keys from a dictionary with del # Sözlükten anahtar silmek için 'del' kullanılabilir
del filled_dict["one"] # Removes the key "one" from filled dict del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir
# Sets store ... well sets # Setler ... set işte :D
empty_set = set() bos_set = set()
# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. # Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm.
some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4}
# Can set new variables to a set # Sete yeni setler ekleyebilirsiniz
filled_set = some_set dolu_set = bir_set
# Add one more item to the set # Sete bir diğer öğe ekleme
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu
# Do set intersection with & # Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz
other_set = {3, 4, 5, 6} diger_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5} dolu_set & diger_set # => {3, 4, 5}
# Do set union with | # '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz
filled_set | other_set # => {1, 2, 3, 4, 5, 6} dolu_set | diger_set # => {1, 2, 3, 4, 5, 6}
# Do set difference with - # Farklılıkları almak için "-" kullanabilirsiniz
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} {1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Check for existence in a set with in # Bir değerin olup olmadığının kontrolü için "in" kullanılabilir
2 in filled_set # => True 2 in dolu_set # => True
10 in filled_set # => False 10 in dolu_set # => False
#################################################### ####################################################