Python Tutorial - Part 5 By P4RS

Dolyetyus

Özel Üye
21 Nis 2020
1,207
676
Delft
Welcome TurkHackTeam family, after a long time, I decided to write the 5th part of the Python tutorials. Because of my exams, I couldn't write much about the subject, but now I'm back. I will write topics again in my spare time.

If you want to take a look at previous tutorials:

Python Tutorial- Part 1 //"P4RS

Python Tutorial- Part 2 //"P4RS

Python Tutorial- Part 3 //"P4RS

Python Tutorial- Part 4 //"P4RS
These links go to Turkish tutorials.


I had the first 4 tutorials done quickly because it was planned for something different, I had stocked up. However, it has been a long time since I could not stock this 5th series. I extended it a lot, let's go to the subject now.



Let's start with the dictionary data type.

Dictionaries will make our work easier, just like the types of data we saw in past lessons. As with other data types, the dictionary data type also has its own methods. First, let's talk about how dictionaries are defined.

How to Define the Dictionary?

The dictionary in Python is like the language dictionary we use in real life. So when you search for the word tree in the dictionary, it will extract the word tree.


C8yG9n.png


Kod:
>>> sozluk = {"ağaç" : "tree"}

Please take a look at how we define it. The important part here is the fancy brackets. To see the data type as an example:

Kod:
>>> type(sozluk)
<class 'dict'>

C8yDvh.png


As you can see it said dict so, dictionary. I think the real bomb is here because most people think that this dictionary consists of two elements. However, it does not consist of two elements. It consists of a single item.

C8ypTM.png


Kod:
>>> len(sozluk)
1

For example, we can create our dictionary from more than one item.

C8ysdy.png


Kod:
>>> sozluk = {"ağaç" : "tree", "araba" : "car"}
>>> len(sozluk)
2

As you can see, our dictionary consists of two items here, too. But if you add more than one item to your dictionary and write them side by side like I did, it will look bad. Instead, I recommend using it like this:

C8yiUp.png


Kod:
>>> sozluk = {"ağaç" : "tree",
	      "araba" : "car",
	      "bilgisayar" : "computer",
	      "film afişi" : "movie poster"}
>>> len(sozluk)
4

If you write in this way, you will understand what is what when you look at your codes in the future, and when you share your codes publicly, the people who examine your codes will not have difficulty understanding.

Now we have created our dictionary, but how do we access the dictionary? Let's take a look at this.


Accessing the Dictionary

If you want, let's continue with our dictionary above. Now, let's recall one item from our dictionary.

C8yvC8.png


Kod:
>>> print(sozluk["ağaç"])
tree

As you can see, we called one item from our dictionary, so here's what we'll understand, to call items in dictionaries:

dictionary [item_name_in_dictionary]

If you try to call an item that is not in the dictionary, it will throw "KeyError" error.

C8yzsj.png


Kod:
>>> print(sozluk["deneme"])
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    print(sozluk["deneme"])
KeyError: 'deneme'

Let's make an example with you so that we can consolidate the event a little more. As an example, let's create address information as dictionary structure.

C8y1Fo.png


Kod:
adres = {"Ahmet" : "Esentepe mahallesi, Atatürk caddesi, 134. Sokak, 3 / 5, Üsküdar / Istanbul",
	     "Mehmet" : "Esentepe mahallesi, Atatürk caddesi, 130. Sokak, 3 / 8, Üsküdar / Istanbul",
	     "Ali" : "Gündoğan mahallesi, Yeşildere caddesi, 40. sokak, 5 / 6, Karesi / Balıkesir"}

isim = input("Adresini öğrenmek istediğiniz kişi: ")

if isim in adres:
    cevap = "{} isimli kişinin adresi: {}"
    print(cevap.format(isim, adres[isim]))
else:
    print("Böyle bir kişinin adresi yoktur.")

This is how we created a dictionary. Now let's run the code we wrote and enter a name.

C8yqVU.png


Kod:
Adresini öğrenmek istediğiniz kişi: Ali
Ali isimli kişinin adresi: Gündoğan mahallesi, Yeşildere caddesi, 40. sokak, 5 / 6, Karesi / Balıkesir

He gave us the address because there was such a person in the dictionary. So if there is no such person, what will it return?

C8y2jH.png


Kod:
Adresini öğrenmek istediğiniz kişi: Alara
Böyle bir kişinin adresi yoktur.

Of course it will return the code block we wrote with else.

We have always used strings here, but you can also use integers. You won't get any error on this. As an example:

Kod:
>>> sayılar = {"Sıfır" : 0,
	       "Bir" : 1,
	       "İki" : 2}
>>> print(sayılar["Sıfır"])
0

C8yUUA.png


We learned how to create a dictionary and print the items in the dictionaries, now let's take a look at adding items to the dictionaries.

Adding Items to Dictionaries

It is easy to add items to dictionaries. Now the logic is as follows:

dictionary[word] = data

So if I need to explain on an example,

C8yWd1.png


Kod:
>>> sayılar["Dört"] = 4
>>> print(sayılar["Dört"])
4

C8y3YI.png


Let's see if you want to change the items as we see adding items.

Changing Items in the Dictionary

Continuing with our dictionary of numbers, let's change the numerical data together in the "dört" item here.

C8y8vf.png


Kod:
>>> sayılar["Dört"] = 5
>>> print(sayılar)
{'Sıfır': 0, 'Bir': 1, 'İki': 2, 'Dört': 5}

As you can see, we changed the numerical data in item "Dört".



Dictionaries have their own unique methods like other data types. For example;

keys()
clear()
copy()
get()
items()
values()


etc. I want to show you the use of some of them. Let's start with keys() first.

Keys()

Dictionaries work as key data. So the first part we define in the first dictionaries is the key and the next is the data. It is very easy to use.

C86LBG.png


Kod:
>>> print(sayılar.keys())
dict_keys(['Sıfır', 'Bir', 'İki', 'Dört'])

It just brings us the keys.

Values()

The keys() method gives the keys to the dictionary, while the values ​​() method gives us the data.

C86HSf.png


Kod:
>>> print(sayılar.values())
dict_values([0, 1, 2, 5])

It gives us directly the data.


clear()

clear() method deletes the items in the dictionary we created.
Let's create a dictionary again


C86YfI.png

C86Tz1.png


Kod:
>>> print(sozluk)
{'araba': 'car', 'ağaç': 'tree', 'film': 'movie'}
>>> sozluk.clear()
>>> print(sozluk)
{}

As you can see, it cleared the items inside the dictionary we created.

All the methods I'll show are these. If you are wondering about the uses of the other methods:
https://www.w3schools.com/python/python_ref_dictionary.asp You can use this link for further reading.

Functions

We have talked about many functions until our current lesson. An example is the function type(). Of course, we did not talk about a single type() function, we were introduced to str(), int() functions. Now let's talk about what is a function and what is it for us.

What Is a Function? What Does It Do?

Functions allow us to combine multiple and difficult operations and perform them in a single move. Using functions, it allows us to combine several steps into a single name.
Now let's reinforce the function structure with a few examples.

CFEFPe.png


Kod:
>>> print("P4RS", "THT")
P4RS THT

You remember the print() function. It is used to display the values ​​taken from us on the screen. However, the important point here is that although the print() function seems to have a single function, there is a space between the parameters we press on the screen. Normally he could write on the screen like this:

Kod:
P4RSTHT
veya
Kod:
THTP4RS

The print() function first left a space between the parameters (sep), then passed the bottom line (end ="\n") after printing the last parameter on the screen, displaying the outputs (file=sys.stdout). So we can do more than one operation with a single function.

So far you have understood and in your mind, "okay, how is it different from writing it as a normal variable? It's the same thing right?" There may be a question in style. Let me explain this with an example.

CFEMaN.png


Kod:
ad = "Ahmet"
soyad = "Veli"
sehir = "İstanbul"

print("İsminiz: ",ad)
print("Soyadınız: ",soyad)
print("Yaşadığınız Şehir: ",sehir)


Now when we print it on the screen, it prints the user's information directly. But are we going to do this method over and over again when we want to change this person? So it can be done, but isn't it automating the programming logic in a little bit? I think it would be nice if we had a kullanıcı_olustur() function like print(). Let's create this together.

Creating and Using Functions

It's not something that pops up in creating a function. It is shaped by certain rules. Let's define an example function altogether.

CFEleR.png


Kod:
def kullanici_olustur(ad,soyad,sehir):

    print("İsmi: ",ad)
    print("Soyadı: ",soyad)
    print("Yaşadığı Şehir: ",sehir)

Now when you first look at it, you may not understand something, but I'll tell you one by one. First of all, we created a function like print(), type(). We will use this function in the same way as we use other functions.
What I want to draw your attention to here is that in IDLE I use, a facilitator shows us the methods we use in our event function.

CFE3nt.png


CFE8Xc.png


Kod:
def kullanici_olustur(ad,soyad,sehir):

    print("İsmi: ",ad)
    print("Soyadı: ",soyad)
    print("Yaşadığı Şehir: ",sehir)
    print("*"*15)


kullanici_olustur("Ahmet","Veli","İstanbul")
kullanici_olustur("Alara","Deniz","Bursa")

Now we have seen that it gives us the following data as output:

CFEZ1P.png


Normally, if we did this one by one, it would correspond to 15-20 lines, but now we have finished with 7 lines. Now when you look at these codes, it may seem a bit complicated, but it has a very simple structure. Here are what we can deduce from the code structure:

1- Functions start with def.
2- We give a name to our function.
3- We open parentheses and enter the arguments we want.
4- We end the function that starts with def by putting ":".
5- When you press Enter, we see that there is an indented space.
6- It is outside the indented space in the part written as kullanici_olustur(değer1,değer2,değer3).



You can understand all 6 items with your own observations. Now there are two important points, the recessed part and the non-recessed part, so the indented part

Kod:
def kullanici_olustur(ad,soyad,sehir):

    print("İsmi: ",ad)
    print("Soyadı: ",soyad)
    print("Yaşadığı Şehir: ",sehir)
    print("*"*15)
burası fonksiyonun tanım kısmıdır yani function definition ikinci kısım yani girintisiz kısım
kullanici_olustur("Ahmet","Veli","İstanbul")
kullanici_olustur("Alara","Deniz","Bursa")

This is where we call the function, the function call. So functions consist of two parts. The first part is creating the function, the second part is calling the function.
The functions we have learned so far are called "builtin functions" embedded in type (), print () functions. They got this name because they are already installed in Python.


Function Structure

We use the word def to describe functions.

Kod:
def kullanici_olustur(ad,soyad,sehir):

def indicates that we are defining a function. kullanici_olustur indicates the name of the function. We use this name when calling the function. At the end of the function: it passes to an indented (4-line space) line at the end. Here we write what to do with the function.
Now we created the function but we didn't call it. Let's run our code and what will it print out on the screen?

CFrpnb.png


Of course it won't give any output because we didn't call our function. Consider the functions print(), type(), we call these functions and print something on the screen. We have to call the function after leaving the indented part.

CFrsMS.png


Let's reinforce it with another example. Let's do the addition process with you. First, let's define a function named addition. Next, let's enter the parameters. Then, let's enter the indented line after putting a colon. Let's specify what we want to do with the function, since I will add here, we declare that we want to add the parameters we specified by typing print ("Toplamları:", sayi1 + number2 + number3).
Next, let's exit the body of the function, get out of the function and call the function.

CFriBG.png


Kod:
def toplama(sayi1,sayi2,sayi3):
    print("Toplamları: ",sayi1+sayi2+sayi3)

toplama(20,233,214)

I explained the function structure and creation. Through these structures here, you can write more complicated functions.

I was talking about the concepts of arguments and parameters from the beginning. Let's explain them now.


What are Arguments and Parameters?

Parameters are the parts we define in parentheses that we define in functions. For example:

CFuNQf.png


Kod:
def toplama(sayi1,sayi2,sayi3):
    print("Toplamları: ",sayi1+sayi2+sayi3)

We have defined a function named toplama() and added three parameters. These are sayi1, sayi2, sayi3. These parameters are used in variables in the body of the function. It will be shaped according to the values ​​entered by the person who will run the function.
It would be better if the names you give parameters are shaped by what it does. In other words, the person running the function will have no difficulty understanding the operation of the function.
Now let's call the function:

Kod:
toplama(20,233,214)

We called the function and it gave us the sum of three as output. The numbers we call values ​​here are arguments. But generally the two are used interchangeably. So it is not paid much attention.

Sequence is very important in functions. So when you enter the first argument, it identifies with the first parameter, when you enter the second argument, it identifies with the second parameter. So you have to do the order correctly or things will get messy.
Although it doesn't seem much difference in the addition function, let's create a record function and see the difference.

CFuOgG.png


Kod:
def kayit_olusturma(ad,soyad,sehir):

    print("Ad: ",ad)
    print("Soyad: ",soyad)
    print("Şehir: ",sehir)

kayit_olusturma("İstanbul","Can","Veli")

Ad:  İstanbul
Soyad:  Can
Şehir:  Veli

As you can see, the output is mixed. Such parameters are called sequential parameters. We also have sequential parameters. Even if the order is mixed in these, it is not a problem because it shows you which parameter will correspond.

CFuj8S.png


Kod:
def kayit_olusturma(ad,soyad,sehir):

    print("Ad: ",ad)
    print("Soyad: ",soyad)
    print("Şehir: ",sehir)

kayit_olusturma(ad="Can", sehir="Ankara", soyad="Veli")

He gave the output in a sequential manner. As you can see, it gave the arguments properly.

This tutorial ends here. We will continue the functions in the next tutorial. Have Good Forums :))


CFui0t.png






Source: https://www.turkhackteam.org/python/1928053-python-egitimi-part-5-a.html
Translator: Dolyetyus

 
Son düzenleme:
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.