Belajar Python: Dari Zero hingga Hero

Pertama sekali, apa itu Python? Menurut penciptanya, Guido van Rossum, Python adalah:

"Bahasa pengaturcaraan tahap tinggi, dan falsafah reka bentuk utamanya adalah mengenai kebolehbacaan kod dan sintaks yang membolehkan pengaturcara mengekspresikan konsep dalam beberapa baris kod."

Bagi saya, sebab pertama untuk belajar Python adalah bahawa sebenarnya, itu indahbahasa pengaturcaraan. Adalah wajar untuk menuliskannya dan meluahkan pemikiran saya.

Sebab lain ialah kita dapat menggunakan pengekodan di Python dengan pelbagai cara: sains data, pengembangan web, dan pembelajaran mesin semuanya bersinar di sini. Quora, Pinterest dan Spotify semuanya menggunakan Python untuk pengembangan web backend mereka. Oleh itu mari kita belajar sedikit mengenainya.

Asas-asas

1. Pemboleh ubah

Anda boleh memikirkan pemboleh ubah sebagai perkataan yang menyimpan nilai. Semudah itu.

Dalam Python, sangat mudah untuk menentukan pemboleh ubah dan menetapkan nilai padanya. Bayangkan anda mahu menyimpan nombor 1 dalam pemboleh ubah yang disebut "satu". Mari lakukannya:

one = 1

Seberapa mudah itu? Anda baru sahaja memberikan nilai 1 pada pemboleh ubah "satu".

two = 2 some_number = 10000

Dan anda boleh memberikan nilai lain untuk apa sahaja pemboleh ubah lain yang anda mahukan. Seperti yang anda lihat dalam jadual di atas, pemboleh ubah " dua " menyimpan bilangan bulat 2 , dan " beberapa_nombor " menyimpan 10.000 .

Selain bilangan bulat, kita juga dapat menggunakan booleans (True / False), string, float, dan banyak jenis data lain.

# booleans true_boolean = True false_boolean = False # string my_name = "Leandro Tk" # float book_price = 15.80

2. Aliran Kawalan: pernyataan bersyarat

" Jika " menggunakan ungkapan untuk menilai sama ada pernyataan itu Benar atau Salah. Sekiranya benar, ia melaksanakan apa yang ada di dalam pernyataan “if”. Sebagai contoh:

if True: print("Hello Python If") if 2 > 1: print("2 is greater than 1")

2 lebih besar daripada 1 , jadi kod " cetak " dijalankan.

The " pun " kenyataan akan dilaksanakan jika " jika " bersuara adalah palsu .

if 1 > 2: print("1 is greater than 2") else: print("1 is not greater than 2")

1 tidak lebih besar dari 2 , jadi kod di dalam pernyataan " lain " akan dijalankan.

Anda juga boleh menggunakan pernyataan " elif ":

if 1 > 2: print("1 is greater than 2") elif 2 > 1: print("1 is not greater than 2") else: print("1 is equal to 2")

3. Gelung / Iterator

Di Python, kita boleh melakukan lelaran dalam pelbagai bentuk. Saya akan bercakap mengenai dua: sementaradan untuk .

While Looping: sementara pernyataan itu Benar, kod di dalam blok akan dijalankan. Jadi, kod ini akan mencetak nombor dari 1 hingga 10 .

num = 1 while num <= 10: print(num) num += 1

The manakala gelung memerlukan " keadaan gelung. "Jika tetap Benar, ia terus berulang. Dalam contoh ini, apabila numadalah 11yang keadaan gelung setaraf False.

Bit kod asas lain untuk memahaminya dengan lebih baik:

loop_condition = True while loop_condition: print("Loop Condition keeps: %s" %(loop_condition)) loop_condition = False

Keadaan gelung adalah Truesehingga ia terus berulang - sehingga kita menetapkannya False.

Untuk Looping : anda menggunakan pemboleh ubah " num " ke blok, dan pernyataan " untuk " akan mengulanginya untuk anda. Kod ini akan dicetak sama seperti kod sementara : dari 1 hingga 10 .

for i in range(1, 11): print(i)

Lihat? Ia sangat mudah. Julat bermula dengan 1dan pergi hingga 11elemen ke-( 10adalah 10elemen ke-3).

Senarai: Koleksi | Susunan | Struktur Data

Bayangkan anda mahu menyimpan bilangan bulat 1 dalam pemboleh ubah. Tetapi mungkin sekarang anda mahu menyimpan 2. Dan 3, 4, 5…

Adakah saya mempunyai cara lain untuk menyimpan semua bilangan bulat yang saya mahukan, tetapi tidak dalam berjuta-juta pemboleh ubah ? Anda meneka - memang ada cara lain untuk menyimpannya.

Listadalah koleksi yang boleh digunakan untuk menyimpan senarai nilai (seperti bilangan bulat yang anda mahukan). Oleh itu mari kita gunakan:

my_integers = [1, 2, 3, 4, 5]

Ia sangat sederhana. Kami membuat array dan menyimpannya di my_integer .

Tetapi mungkin anda bertanya: "Bagaimana saya dapat memperoleh nilai dari array ini?"

Soalan hebat. Listmempunyai konsep yang disebut indeks . Elemen pertama mendapat indeks 0 (sifar). Yang kedua mendapat 1, dan seterusnya. Anda mendapat idea.

Untuk menjadikannya lebih jelas, kita dapat mewakili susunan dan setiap elemen dengan indeksnya. Saya boleh melukisnya:

Menggunakan sintaks Python, juga mudah difahami:

my_integers = [5, 7, 1, 3, 4] print(my_integers[0]) # 5 print(my_integers[1]) # 7 print(my_integers[4]) # 4

Bayangkan bahawa anda tidak mahu menyimpan bilangan bulat. Anda hanya mahu menyimpan tali, seperti senarai nama saudara anda. Milik saya akan kelihatan seperti ini:

relatives_names = [ "Toshiaki", "Juliana", "Yuji", "Bruno", "Kaio" ] print(relatives_names[4]) # Kaio

Ia berfungsi dengan cara yang sama seperti bilangan bulat. Bagus.

We just learned how Lists indices work. But I still need to show you how we can add an element to the List data structure (an item to a list).

The most common method to add a new value to a List is append. Let’s see how it works:

bookshelf = [] bookshelf.append("The Effective Engineer") bookshelf.append("The 4 Hour Work Week") print(bookshelf[0]) # The Effective Engineer print(bookshelf[1]) # The 4 Hour Work Week

append is super simple. You just need to apply the element (eg. “The Effective Engineer”) as the append parameter.

Well, enough about Lists. Let’s talk about another data structure.

Dictionary: Key-Value Data Structure

Now we know that Lists are indexed with integer numbers. But what if we don’t want to use integer numbers as indices? Some data structures that we can use are numeric, string, or other types of indices.

Let’s learn about the Dictionary data structure. Dictionary is a collection of key-value pairs. Here’s what it looks like:

dictionary_example = { "key1": "value1", "key2": "value2", "key3": "value3" }

The key is the index pointing to thevalue. How do we access the Dictionaryvalue? You guessed it — using the key. Let’s try it:

dictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian" } print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk print("And by the way I'm %s" %(dictionary_tk["nationality"])) # And by the way I'm Brazilian

I created a Dictionary about me. My name, nickname, and nationality. Those attributes are the Dictionarykeys.

As we learned how to access the List using index, we also use indices (keys in the Dictionary context) to access the value stored in the Dictionary.

In the example, I printed a phrase about me using all the values stored in the Dictionary. Pretty simple, right?

Another cool thing about Dictionary is that we can use anything as the value. In the DictionaryI created, I want to add the key “age” and my real integer age in it:

dictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian", "age": 24 } print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk print("And by the way I'm %i and %s" %(dictionary_tk["age"], dictionary_tk["nationality"])) # And by the way I'm Brazilian

Here we have a key (age) value (24) pair using string as the key and integer as the value.

As we did with Lists, let’s learn how to add elements to a Dictionary. The keypointing to avalue is a big part of what Dictionary is. This is also true when we are talking about adding elements to it:

dictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian" } dictionary_tk['age'] = 24 print(dictionary_tk) # {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'} 

We just need to assign a value to a Dictionarykey. Nothing complicated here, right?

Iteration: Looping Through Data Structures

As we learned in the Python Basics, the List iteration is very simple. We Pythondevelopers commonly use For looping. Let’s do it:

bookshelf = [ "The Effective Engineer", "The 4-hour Workweek", "Zero to One", "Lean Startup", "Hooked" ] for book in bookshelf: print(book)

So for each book in the bookshelf, we (can do everything with it) print it. Pretty simple and intuitive. That’s Python.

For a hash data structure, we can also use the for loop, but we apply the key :

dictionary = { "some_key": "some_value" } for key in dictionary: print("%s --> %s" %(key, dictionary[key])) # some_key --> some_value

This is an example how to use it. For each key in the dictionary , we print the key and its corresponding value.

Another way to do it is to use the iteritems method.

dictionary = { "some_key": "some_value" } for key, value in dictionary.items(): print("%s --> %s" %(key, value)) # some_key --> some_value

We did name the two parameters as key and value, but it is not necessary. We can name them anything. Let’s see it:

dictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian", "age": 24 } for attribute, value in dictionary_tk.items(): print("My %s is %s" %(attribute, value)) # My name is Leandro # My nickname is Tk # My nationality is Brazilian # My age is 24

We can see we used attribute as a parameter for the Dictionarykey, and it works properly. Great!

Classes & Objects

A little bit of theory:

Objects are a representation of real world objects like cars, dogs, or bikes. The objects share two main characteristics: data and behavior.

Cars have data, like number of wheels, number of doors, and seating capacity They also exhibit behavior: they can accelerate, stop, show how much fuel is left, and so many other things.

We identify data as attributes and behavior as methods in object-oriented programming. Again:

Data → Attributes and Behavior → Methods

And a Class is the blueprint from which individual objects are created. In the real world, we often find many objects with the same type. Like cars. All the same make and model (and all have an engine, wheels, doors, and so on). Each car was built from the same set of blueprints and has the same components.

Python Object-Oriented Programming mode: ON

Python, as an Object-Oriented programming language, has these concepts: class and object.

A class is a blueprint, a model for its objects.

So again, a class it is just a model, or a way to define attributes and behavior (as we talked about in the theory section). As an example, a vehicle class has its own attributes that define what objects are vehicles. The number of wheels, type of tank, seating capacity, and maximum velocity are all attributes of a vehicle.

With this in mind, let’s look at Python syntax for classes:

class Vehicle: pass

We define classes with a class statement — and that’s it. Easy, isn’t it?

Objects are instances of a class. We create an instance by naming the class.

car = Vehicle() print(car) # 

Here car is an object (or instance) of the classVehicle.

Remember that our vehicle class has four attributes: number of wheels, type of tank, seating capacity, and maximum velocity. We set all these attributes when creating a vehicle object. So here, we define our class to receive data when it initiates it:

class Vehicle: def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity): self.number_of_wheels = number_of_wheels self.type_of_tank = type_of_tank self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity

We use the initmethod. We call it a constructor method. So when we create the vehicle object, we can define these attributes. Imagine that we love the Tesla Model S, and we want to create this kind of object. It has four wheels, runs on electric energy, has space for five seats, and the maximum velocity is 250km/hour (155 mph). Let’s create this object:

tesla_model_s = Vehicle(4, 'electric', 5, 250)

Four wheels + electric “tank type” + five seats + 250km/hour maximum speed.

All attributes are set. But how can we access these attributes’ values? We send a message to the object asking about them. We call it a method. It’s the object’s behavior. Let’s implement it:

class Vehicle: def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity): self.number_of_wheels = number_of_wheels self.type_of_tank = type_of_tank self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity def number_of_wheels(self): return self.number_of_wheels def set_number_of_wheels(self, number): self.number_of_wheels = number

This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first gets the attribute value, and the second sets a new value for the attribute.

In Python, we can do that using @property (decorators) to define getters and setters. Let’s see it with code:

class Vehicle: def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity): self.number_of_wheels = number_of_wheels self.type_of_tank = type_of_tank self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity @property def number_of_wheels(self): return self.__number_of_wheels @number_of_wheels.setter def number_of_wheels(self, number): self.__number_of_wheels = number

And we can use these methods as attributes:

tesla_model_s = Vehicle(4, 'electric', 5, 250) print(tesla_model_s.number_of_wheels) # 4 tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2 print(tesla_model_s.number_of_wheels) # 2

This is slightly different than defining methods. The methods work as attributes. For example, when we set the new number of wheels, we don’t apply two as a parameter, but set the value 2 to number_of_wheels. This is one way to write pythonicgetter and setter code.

But we can also use methods for other things, like the “make_noise” method. Let’s see it:

class Vehicle: def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity): self.number_of_wheels = number_of_wheels self.type_of_tank = type_of_tank self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity def make_noise(self): print('VRUUUUUUUM')

Apabila kita memanggil kaedah ini, ia hanya mengembalikan rentetan " VRRRRUUUUM. "

tesla_model_s = Vehicle(4, 'electric', 5, 250) tesla_model_s.make_noise() # VRUUUUUUUM

Encapsulation: Menyembunyikan Maklumat

Encapsulation adalah mekanisme yang menyekat akses langsung ke data dan kaedah objek. Tetapi pada masa yang sama, ia memudahkan operasi pada data tersebut (kaedah objek).

"Encapsulation dapat digunakan untuk menyembunyikan data anggota dan fungsi anggota. Di bawah definisi ini, enkapsulasi bermaksud bahawa perwakilan dalaman suatu objek umumnya tersembunyi dari pandangan di luar definisi objek. " - Wikipedia

Semua perwakilan dalaman objek tersembunyi dari luar. Hanya objek yang dapat berinteraksi dengan data dalamannya.

Pertama, kita perlu memahami bagaimana publicdan non-publiccontoh pembolehubah dan kaedah kerja.

Pemboleh ubah Instance Awam

For a Python class, we can initialize a public instance variable within our constructor method. Let’s see this:

Within the constructor method:

class Person: def __init__(self, first_name): self.first_name = first_name

Here we apply the first_name value as an argument to the public instance variable.

tk = Person('TK') print(tk.first_name) # => TK

Within the class:

class Person: first_name = 'TK'

Here, we do not need to apply the first_name as an argument, and all instance objects will have a class attribute initialized with TK.

tk = Person() print(tk.first_name) # => TK

Cool. We have now learned that we can use public instance variables and class attributes. Another interesting thing about the public part is that we can manage the variable value. What do I mean by that? Our object can manage its variable value: Get and Set variable values.

Keeping the Person class in mind, we want to set another value to its first_name variable:

tk = Person('TK') tk.first_name = 'Kaio' print(tk.first_name) # => Kaio

Di sana kami pergi. Kami hanya menetapkan nilai lain ( kaio) ke first_namepemboleh ubah instance dan ia mengemas kini nilainya. Semudah itu. Oleh kerana ia adalah publicpemboleh ubah, kita boleh melakukannya

Pembolehubah Instance Bukan Umum

Kami tidak menggunakan istilah "peribadi" di sini, kerana tidak ada atribut yang benar-benar peribadi di Python (tanpa jumlah pekerjaan yang tidak diperlukan). - PEP 8

Sebagai public instance variable, kita boleh menentukan non-public instance variablekeduanya dalam kaedah konstruktor atau dalam kelas. Perbezaan sintaks adalah: untuk non-public instance variables, gunakan garis bawah ( _) sebelum variablenamanya.

Pemboleh ubah contoh 'peribadi' yang tidak dapat diakses kecuali dari dalam objek tidak ada di Python. Walau bagaimanapun, terdapat konvensyen yang diikuti oleh kebanyakan kod Python: nama yang diawali dengan garis bawah (contohnya _spam) harus dianggap sebagai bahagian bukan umum dari API (sama ada fungsi, kaedah atau anggota data) " - Yayasan Perisian Python

Inilah contohnya:

class Person: def __init__(self, first_name, email): self.first_name = first_name self._email = email

Adakah anda melihat emailpemboleh ubah? Ini adalah bagaimana kita menentukan non-public variable:

tk = Person('TK', '[email protected]') print(tk._email) # [email protected]
Kita boleh mengakses dan mengemas kini. Non-public variableshanyalah sebuah konvensyen dan harus dianggap sebagai bahagian bukan umum dari API.

Oleh itu, kami menggunakan kaedah yang membolehkan kami melakukannya mengikut definisi kelas kami. Mari kita laksanakan dua kaedah ( emaildan update_email) untuk memahaminya:

class Person: def __init__(self, first_name, email): self.first_name = first_name self._email = email def update_email(self, new_email): self._email = new_email def email(self): return self._email

Sekarang kita boleh mengemas kini dan mengakses non-public variablesmenggunakan kaedah tersebut. Mari lihat:

tk = Person('TK', '[email protected]') print(tk.email()) # => [email protected] # tk._email = '[email protected]' -- treat as a non-public part of the class API print(tk.email()) # => [email protected] tk.update_email('[email protected]') print(tk.email()) # => [email protected]
  1. We initiated a new object with first_name TK and email [email protected]
  2. Printed the email by accessing the non-public variable with a method
  3. Tried to set a new email out of our class
  4. We need to treat non-public variable as non-public part of the API
  5. Updated the non-public variable with our instance method
  6. Success! We can update it inside our class with the helper method

Public Method

With public methods, we can also use them out of our class:

class Person: def __init__(self, first_name, age): self.first_name = first_name self._age = age def show_age(self): return self._age

Let’s test it:

tk = Person('TK', 25) print(tk.show_age()) # => 25

Great — we can use it without any problem.

Non-public Method

But with non-public methods we aren’t able to do it. Let’s implement the same Person class, but now with a show_agenon-public method using an underscore (_).

class Person: def __init__(self, first_name, age): self.first_name = first_name self._age = age def _show_age(self): return self._age

And now, we’ll try to call this non-public method with our object:

tk = Person('TK', 25) print(tk._show_age()) # => 25
Kita boleh mengakses dan mengemas kini. Non-public methodshanyalah sebuah konvensyen dan harus dianggap sebagai bahagian bukan umum dari API.

Inilah contoh bagaimana kita boleh menggunakannya:

class Person: def __init__(self, first_name, age): self.first_name = first_name self._age = age def show_age(self): return self._get_age() def _get_age(self): return self._age tk = Person('TK', 25) print(tk.show_age()) # => 25

Di sini kita mempunyai _get_agenon-public methoddan show_agepublic method. Yang show_ageboleh digunakan oleh objek kami (di luar kelas kami) dan satu- _get_agesatunya yang digunakan di dalam definisi kelas kami ( show_agekaedah dalam ). Tetapi sekali lagi: sebagai perkara konvensyen.

Ringkasan Encapsulation

Dengan enkapsulasi kita dapat memastikan bahawa perwakilan dalaman objek tersembunyi dari luar.

Warisan: tingkah laku dan ciri

Objek tertentu mempunyai beberapa persamaan: tingkah laku dan ciri-cirinya.

Sebagai contoh, saya mewarisi beberapa ciri dan tingkah laku daripada ayah saya. Saya mewarisi mata dan rambutnya sebagai ciri, dan ketidaksabaran dan kegilaannya sebagai tingkah laku.

In object-oriented programming, classes can inherit common characteristics (data) and behavior (methods) from another class.

Let’s see another example and implement it in Python.

Imagine a car. Number of wheels, seating capacity and maximum velocity are all attributes of a car. We can say that anElectricCar class inherits these same attributes from the regular Car class.

class Car: def __init__(self, number_of_wheels, seating_capacity, maximum_velocity): self.number_of_wheels = number_of_wheels self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity

Our Car class implemented:

my_car = Car(4, 5, 250) print(my_car.number_of_wheels) print(my_car.seating_capacity) print(my_car.maximum_velocity)

Once initiated, we can use all instance variables created. Nice.

In Python, we apply a parent class to the child class as a parameter. An ElectricCar class can inherit from our Car class.

class ElectricCar(Car): def __init__(self, number_of_wheels, seating_capacity, maximum_velocity): Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity)

Simple as that. We don’t need to implement any other method, because this class already has it (inherited from Car class). Let’s prove it:

my_electric_car = ElectricCar(4, 5, 250) print(my_electric_car.number_of_wheels) # => 4 print(my_electric_car.seating_capacity) # => 5 print(my_electric_car.maximum_velocity) # => 250

Beautiful.

That’s it!

We learned a lot of things about Python basics:

  • How Python variables work
  • How Python conditional statements work
  • How Python looping (while & for) works
  • How to use Lists: Collection | Array
  • Dictionary Key-Value Collection
  • How we can iterate through these data structures
  • Objects and Classes
  • Attributes as objects’ data
  • Methods as objects’ behavior
  • Using Python getters and setters & property decorator
  • Encapsulation: hiding information
  • Inheritance: behaviors and characteristics

Congrats! You completed this dense piece of content about Python.

If you want a complete Python course, learn more real-world coding skills and build projects, try One Month Python Bootcamp. See you there ☺

For more stories and posts about my journey learning & mastering programming, follow my publication The Renaissance Developer.

Have fun, keep learning, and always keep coding.

My Twitter & Github. ☺