Learning Python: From Zero to Hero
Først av alt, hva er Python? I følge skaperen, Guido van Rossum, er Python en:
"Høyt nivå programmeringsspråk, og dens kjerne designfilosofi handler om kodelesbarhet og en syntaks som lar programmerere uttrykke konsepter i noen få kodelinjer."For meg var den første grunnen til å lære Python at den faktisk er en vakkerprogrammeringsspråk. Det var veldig naturlig å kode i det og uttrykke tankene mine.
En annen grunn var at vi kan bruke koding i Python på flere måter: datavitenskap, nettutvikling og maskinlæring skinner her. Quora, Pinterest og Spotify bruker alle Python for deres webutvikling. Så la oss lære litt om det.
Det grunnleggende
1. Variabler
Du kan tenke på variabler som ord som lagrer en verdi. Så enkelt som det.
I Python er det veldig enkelt å definere en variabel og sette en verdi til den. Tenk deg at du vil lagre nummer 1 i en variabel kalt “one”. La oss gjøre det:
one = 1
Hvor enkelt var det? Du tildelte akkurat verdien 1 til variabelen "en".
two = 2 some_number = 10000
Og du kan tilordne hvilken som helst annen verdi til hvilke andre variabler du vil ha. Som du ser i tabellen over, lagrer variabelen “ to ” heltallet 2 , og “ noe_nummer ” lagrer 10.000 .
Foruten heltall, kan vi også bruke booleans (True / False), strenger, float og så mange andre datatyper.
# booleans true_boolean = True false_boolean = False # string my_name = "Leandro Tk" # float book_price = 15.80
2. Control Flow: betingede uttalelser
" Hvis " bruker et uttrykk for å evaluere om en påstand er sann eller usann. Hvis det er sant, utfører det det som er inne i "hvis" -utsagnet. For eksempel:
if True: print("Hello Python If") if 2 > 1: print("2 is greater than 1")
2 er større enn 1 , så “ utskriftskoden ” kjøres.
Uttrykket " annet " vil bli utført hvis " hvis " -uttrykket er feil .
if 1 > 2: print("1 is greater than 2") else: print("1 is not greater than 2")
1 er ikke større enn 2 , så koden i " annet " -uttalelsen vil bli utført.
Du kan også bruke en " elif " -uttalelse:
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. Looping / Iterator
I Python kan vi gjenta i forskjellige former. Jeg snakker om to: mensog for .
While Looping: mens utsagnet er sant, vil koden i blokken kjøres. Så denne koden vil skrive ut tallet fra 1 til 10 .
num = 1 while num <= 10: print(num) num += 1
Den mens sløyfen er behov for en “ sløyfe tilstand. ”Hvis det forblir sant, fortsetter det å gjenta. I dette eksempel, når num
er 11
den løkke tilstand lik False
.
En annen grunnleggende kode for å forstå den bedre:
loop_condition = True while loop_condition: print("Loop Condition keeps: %s" %(loop_condition)) loop_condition = False
Den sløyfe tilstand er True
slik at det holder itera - før vi setter den til False
.
For Looping : du bruker variabelen " num " på blokken, og " for " -uttrykket vil gjenta den for deg. Denne koden skrives ut som under koden: fra 1 til 10 .
for i in range(1, 11): print(i)
Se? Det er så enkelt. Området starter med 1
og går til det 11
th elementet ( 10
er det 10
th elementet).
Liste: Samling | Array | Data struktur
Tenk deg at du vil lagre heltallet 1 i en variabel. Men kanskje du nå vil lagre 2. Og 3, 4, 5 ...
Har jeg en annen måte å lagre alle heltallene jeg vil ha, men ikke i millioner av variabler ? Du gjettet det - det er virkelig en annen måte å lagre dem på.
List
er en samling som kan brukes til å lagre en liste over verdier (som disse heltallene du vil ha). Så la oss bruke det:
my_integers = [1, 2, 3, 4, 5]
Det er veldig enkelt. Vi opprettet en matrise og lagret den på my_integer .
Men kanskje du spør: "Hvordan kan jeg få en verdi fra denne matrisen?"
Flott spørsmål. List
har et konsept som heter index . Det første elementet får indeksen 0 (null). Den andre får 1, og så videre. Du får ideen.
For å gjøre det tydeligere kan vi representere matrisen og hvert element med indeksen. Jeg kan tegne det:

Ved hjelp av Python-syntaksen er det også enkelt å forstå:
my_integers = [5, 7, 1, 3, 4] print(my_integers[0]) # 5 print(my_integers[1]) # 7 print(my_integers[4]) # 4
Tenk deg at du ikke vil lagre heltall. Du vil bare lagre strenger, som en liste over dine slektningers navn. Mine ville se ut slik:
relatives_names = [ "Toshiaki", "Juliana", "Yuji", "Bruno", "Kaio" ] print(relatives_names[4]) # Kaio
Det fungerer på samme måte som heltall. Hyggelig.
Vi har nettopp lært hvordan Lists
indekser fungerer. Men jeg må fremdeles vise deg hvordan vi kan legge til et element i List
datastrukturen (et element i en liste).
Den vanligste metoden for å legge til en ny verdi til a List
er append
. La oss se hvordan det fungerer:
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
er superenkelt. Du trenger bare å bruke elementet (f.eks. “ The Effective Engineer ”) som append
parameter.
Vel, nok om Lists
. La oss snakke om en annen datastruktur.
Ordbok: Nøkkelverdidatastruktur
Nå vet vi at de Lists
er indeksert med heltall. Men hva om vi ikke vil bruke heltall som indekser? Noen datastrukturer som vi kan bruke er numeriske, streng eller andre typer indekser.
La oss lære om Dictionary
datastrukturen. Dictionary
er en samling nøkkelverdipar. Slik ser det ut:
dictionary_example = { "key1": "value1", "key2": "value2", "key3": "value3" }
Den nøkkelen er indeksen peker tilverdi . Hvordan får vi tilgang til Dictionary
verdien ? Du gjettet det - ved å bruke nøkkelen . La oss prøve det:
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
Jeg skapte en Dictionary
om meg. Mitt navn, kallenavn og nasjonalitet. Disse egenskapene er Dictionary
nøklene .
Da vi lærte å få tilgang til List
brukerindeksen, bruker vi også indekser ( nøkler i Dictionary
sammenheng) for å få tilgang til verdien som er lagret i Dictionary
.
I eksemplet skrev jeg ut en setning om meg ved å bruke alle verdiene som er lagret i Dictionary
. Ganske enkelt, ikke sant?
Another cool thing about Dictionary
is that we can use anything as the value. In the Dictionary
I 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 Dictionary
key. Nothing complicated here, right?
Iteration: Looping Through Data Structures
As we learned in the Python Basics, the List
iteration is very simple. We Python
developers 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 Dictionary
key
, 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 init
method. 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 pythonic
getter
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')
Når vi kaller denne metoden, returnerer den bare en streng “ VRRRRUUUUM. ”
tesla_model_s = Vehicle(4, 'electric', 5, 250) tesla_model_s.make_noise() # VRUUUUUUUM
Innkapsling: Skjule informasjon
Innkapsling er en mekanisme som begrenser direkte tilgang til objektenes data og metoder. Men samtidig forenkler det operasjonen på disse dataene (objektenes metoder).
“Innkapsling kan brukes til å skjule data medlemmer og medlemmer funksjon. Under denne definisjonen betyr innkapsling at den interne representasjonen av et objekt generelt er skjult fra syn utenfor objektets definisjon. ” - WikipediaAll intern representasjon av et objekt er skjult fra utsiden. Bare objektet kan samhandle med interne data.
Først må vi forstå hvordan public
og non-public
forekomstvariabler og metoder fungerer.
Variabler i offentlig instans
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
Der går vi. Vi satte bare en annen verdi ( kaio
) til first_name
forekomstvariabelen, og den oppdaterte verdien. Så enkelt som det. Siden det er en public
variabel, kan vi gjøre det.
Ikke-offentlig instansvariabel
Vi bruker ikke begrepet "privat" her, siden ingen attributter egentlig er private i Python (uten generelt unødvendig mye arbeid). - PEP 8Som public instance variable
, kan vi definere non-public instance variable
begge innenfor konstruktormetoden eller i klassen. Syntaksforskjellen er: for non-public instance variables
, bruk en understreking ( _
) foran variable
navnet.
_spam
) Skal behandles som en ikke-offentlig del av API (enten det er en funksjon, en metode eller et datamedlem) ” - Python Software Foundation
Her er et eksempel:
class Person: def __init__(self, first_name, email): self.first_name = first_name self._email = email
Så du email
variabelen? Slik definerer vi en non-public variable
:
tk = Person('TK', '[email protected]') print(tk._email) # [email protected]
Vi kan få tilgang til og oppdatere den.
Non-public variables
er bare en konvensjon og bør behandles som en ikke-offentlig del av API.
Så vi bruker en metode som lar oss gjøre det innenfor klassedefinisjonen vår. La oss implementere to metoder ( email
og update_email
) for å forstå det:
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
Nå kan vi oppdatere og få tilgang til non-public variables
ved hjelp av disse metodene. La oss se:
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]
- We initiated a new object with
first_name
TK andemail
[email protected] - Printed the email by accessing the
non-public variable
with a method - Tried to set a new
email
out of our class - We need to treat
non-public variable
asnon-public
part of the API - Updated the
non-public variable
with our instance method - 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_age
non-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
Vi kan få tilgang til og oppdatere den.
Non-public methods
er bare en konvensjon og bør behandles som en ikke-offentlig del av API.
Her er et eksempel på hvordan vi kan bruke det:
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
Her har vi a _get_age
non-public method
og a show_age
public method
. Den show_age
kan brukes av objektet vårt (utenfor vår klasse) og det _get_age
eneste som brukes i vår klassedefinisjon (indre show_age
metode). Men igjen: som et spørsmål om konvensjon.
Innkapslingssammendrag
Med innkapsling kan vi sikre at den interne representasjonen av objektet er skjult fra utsiden.
Arv: atferd og egenskaper
Enkelte objekter har noen ting til felles: deres oppførsel og egenskaper.
For eksempel arvet jeg noen egenskaper og atferd fra faren min. Jeg arvet hans øyne og hår som egenskaper, og hans utålmodighet og innadvendthet som atferd.
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.
Hvis du vil ha et fullstendig Python-kurs, lære mer virkelige kodingsferdigheter og bygge prosjekter, kan du prøve One Month Python Bootcamp . Vi sees der ☺
For flere historier og innlegg om min læring og mestring av programmering, følg publikasjonen min The Renaissance Developer .
Ha det gøy, fortsett å lære, og fortsett å kode.
Min Twitter og Github. ☺