You are on page 1of 40

Basic of Python Programming

This is a practical introduction to Python Programming Language. Python is an interpreted,


high-level, and general purpose programming language that was designed for efficiency,
readability, and simplicity.
Python design philosophy emphasizes simplicity and code readability. There are about 19
Python design guiding principles, the top 8 being:
• Beautiful is better than ugly.
• Explicit is better than implicit
• Simple is better than complex
• Complex is better than complicated
• Readability counts
• Now is better than ever
• If the implementation is hard to explain, it's a bad idea.
• If the implementation is easy to explain, it may be a good idea.
More design rules can be found in the Zen of Python. You can also display them by
importing this(import this) in any Python interpreter.

Bazele programării Python


Aceasta este o introducere practică în limbajul de programare Python. Python este un
limbaj de programare interpretat, de nivel înalt și de uz general, care a fost conceput
pentru eficiență , lizibilitate și simplitate.
Filosofia de design Python pune accent pe simplitate și pe lizibilitatea codului. Există
aproximativ 19 principii directoare de proiectare Python, primele 8 fiind:
Frumos este mai bun decât urât. Explicitul este mai bine decâ t implicit Simplu este mai bine
decât complex Complex este mai bine decâ t complicat Lizibilitatea contează Acum este mai
bine ca niciodată Dacă implementarea este greu de explicat, este o idee proastă. Dacă
implementarea este ușor de explicat, poate fi o idee bună .
Mai multe reguli de design pot fi gă site în Zen of Python. De asemenea, le puteți afișa
importâ nd acest(import this) în orice interpret Python.
import this
Python is a popular and go-to programming language in different tech communities, most
notable in machine learning and data science. It is sometimes referred to as “batteries
included” due to its rich standard library. Below are more elaborated advantages of Python:
• It is simple to read and write: Python syntaxes are very easy to write and easy to
recall as well.
• It has a beautiful design and built-in data types.
• It has thousands of great libraries in many disciplines.
• Supportive communities: Good documentation, courses, tutorials, social groups.
• Easy to learn and use due to its simple syntaxes which feel like a natural language.
This introduction will cover the following:
• 1. Variables, Numbers and Strings
– 1.1 Variables
– 1.2 Numbers
– 1.3 Strings
• 2. Data Structures
– 2.1 Lists
– 2.2 Dictionaries
– 2.3 Tuples
– 2.4 Sets
• 3. Comparison and Logic Operators
• 4. Control Flow
– 4.1 If Condition
– 4.2 For Loop
– 4.3 While Loop
• 5. Functions
• 6. Lambda Functions
• 7. Built in functions
– 7.1 Map Function
– 7.2 Filter Function
• 8. More Useful Python Stuff
– 8.1 List Comprehension
– 8.2 Enumerate Function
– 8.3 Zip Function
Python este un limbaj de programare popular și popular în diferite comunită ți tehnologice,
cel mai notabil în învă țarea automată și știința datelor. Este uneori denumit „bateriile
incluse” datorită bibliotecii sale standard bogate. Mai jos sunt mai detaliate avantajele
Python:
Este simplu de citit și de scris: sintaxele Python sunt foarte ușor de scris și ușor de rememorat.
Are un design frumos și tipuri de date încorporate. Are mii de biblioteci grozave în multe
discipline. Comunită ți de sprijin: documentare bună , cursuri, tutoriale, grupuri sociale.
*Ușor de învă țat și utilizat datorită sintaxelor sale simple, care se simt ca un limbaj natural.
Această introducere va acoperi urmă toarele:* 1. Variabile, numere și șiruri 1.1 Variabile 1.2
Numere 1.3 șiruri 2. Structuri de date 2.1 Liste 2.2 Dicționare 2,3 tupli 2.4 seturi 3. Operatori
de comparație și logici 4. Flux de control 4.1 Dacă condiția 4.2 For Loop 4.3 Bucla While 5.
Funcții 6. Funcții Lambda 7. Funcții încorporate 7.1 Funcția Hartă 7.2 Funcția de filtrare
8. Lucruri Python mai utile 8.1 Înțelegerea listei 8.2 Funcția de enumerare 8.3 Zip Function

1. Variables, Numbers, and Strings

1. Variabile, numere și șiruri

1.1 Variables

1.1 Variabile
Below are quick notes about Python variables and other most important things to know
before writing actual Python code:
• A Variable is a location in memory where we store the data.
• A variable in Python can either be of 3 data types: integer, float, or a string.
Data type specifies the category of the variables.
• We can use type(variable_name) to find the type of given variable_name.
• In Python, we use # to add comments. Comments do not change anything and are not
compiled.
• If your comment is longer than one line, you can use triple quotes. The lines inside
triple quotes are ignore during runtime.
"""
In Python, there is no official way to write long comments, but you can use
triple quotes.
The sentence between triple quote are ignored at runtime. You can also use
single quote('''....'''). Python treats single quote as double quotes in many
scanerios such as strings representation.

Guido also agreed it works:


https://twitter.com/gvanrossum/status/112670605505077248
"""
• We also use = to assign a value to the name of variable. Example: var_name = 1.
Note that it's different to comparison operator of equal to ( ==).
• We can use print() to display the value of variable or the results of any expression.
• Each line of the code start on the new line.
• Be aware of indentations. Python is serious about them.
Mai jos sunt note rapide despre variabilele Python și alte lucruri cele mai importante de
știut înainte de a scrie codul Python real:
„O variabilă” este o locație din memorie în care stocăm datele. O variabilă în Python poate
fi fie de 3 tipuri de date: integer, float sau un șir. Tipul de date specifică categoria
variabilelor. Putem folosi type(variable_name) pentru a găsi tipul variable_name dat. În
Python, folosim # pentru a adă uga comentarii. Comentariile nu schimbă nimic și nu sunt
compilate. *Dacă comentariul dvs. este mai lung de un râ nd, puteți utiliza ghilimele triple.
Liniile din ghilimele triple sunt ignorate în timpul rulă rii.
``` """ În Python, nu există o modalitate oficială de a scrie comentarii lungi, dar puteți folosi
ghilimele triple. Propozițiile dintre ghilimele triple sunt ignorate în timpul execuției. De
asemenea, puteți utiliza ghilimele simple ('''....'''). Python tratează ghilimele simple ca
ghilimele duble în multe scanerios, cum ar fi reprezentarea șirurilor.
Guido a fost de asemenea de acord că funcționează :
https://twitter.com/gvanrossum/status/112670605505077248 """ ``* De asemenea,
folosim=pentru a atribui o valoare numelui variabilei. Exemplu: var_name = 1.
Rețineți că este diferit de operatorul de comparație egal cu (==). *Putem
folosiprint()` pentru a afișa valoarea variabilei sau rezultatele orică rei expresii.* Fiecare
linie a codului începe pe noua linie.
• Fiți conștienți de indentă ri. Python este serios în privința lor.
# EXAMPLE OF CREATING A VARIABLE

# We use # to add comment, it won’t run or affect the code


# You use = to assign a value to the name of the variable.
# Each code starts on the new line. No semicolon or {}
# Python is awesome. You do not need to provide the data type of variable
when creating it.

int_var = 1
str_var = 'Hundred'

1.2 Numbers
Numbers in Python can either be integers int or floats float. Integer are real, finite,
natural or whole numbers. Take an example: 1,2,3,4 are integers. Floats are numbers that
have decimal points such as4.6, 6.0, 7.7. Note that 4.0 is considered as a float data type
too. Recently, Karpathy, AI Director at Tesla posted that floats are not real.
We can perform operations on numbers. The operations that we can perform include
addition, multiplication, division, modular, etc...

1.2 Numere
Numerele în Python pot fi fie numere întregi int, fie floats float. Numerele întregi sunt
numere reale, finite, naturale sau întregi. Luați un exemplu: 1,2,3,4 sunt numere întregi.
Flotantele sunt numere care au zecimale, cum ar fi „4,6”, „6,0”, „7,7”. Rețineți că „4.0” este
considerat și un tip de date flotant. Recent, Karpathy, director AI la Tesla, a postat că
floaturile nu sunt reale.
Putem efectua operații pe numere. Operațiile pe care le putem efectua includ adunare,
înmulțire, împă rțire, modulare etc...
int_var = 10
float_var = 12.8

type(int_var)

int

type(float_var)

float

# Numeric Operations

# Addition

1 + 100

101

# Multiplication

1 * 100

100

# Division

1 / 100

0.01

# Floor division

7 // 2

3
# Modular (%)
# This is the remainder or a value remaining after dividing two numbers
# 100 / 1 = 100, remainder is 0

100 % 1

1 % 100

10 % 2

# Powers
# 1 power any number is 1 always

1 ** 100

2 ** 2

# We use print() to display the results of the operations or a variable

print(1 + 100)

101

1.3 Strings
Python supports strings. String is a sequence of characters.
Strings are one of the commonly used and important data types. Most problems involve
working with strings. Thus, knowing how to work with strings is an incredible thing.
Strings are expressed in either "..." or '...'.
"text inside here will be a string"
'text inside here will also be a string'

We can manipulate strings in many ways. A simple example is to concat the strings.

1.3 șiruri
Python acceptă șiruri. Ș irul este o secvență de caractere.
Ș irurile de caractere sunt unul dintre tipurile de date frecvent utilizate și importante. Cele
mai multe probleme implică lucrul cu șiruri. Astfel, a ști să lucrezi cu corzi este un lucru
incredibil.
Ș irurile de caractere sunt exprimate fie în „”...”” fie în „...””.
„textul aici va fi un șir”
„textul dinăuntru aici va fi și un șir”

Putem manipula șirurile în multe feluri. Un exemplu simplu este concatarea șirurilor.
str_var = 'One'
str_var2 = 'Hundred'

str_var + str_var2

'OneHundred'

str_var + ' ' + 'and' + ' '+ str_var2 + '.'

'One and Hundred.'

# We can use print() to display a string

print(" This is a string")

This is a string

# We can also compare strings to check whether they are similar.


# If they are similar, case by case, comparison operator returns true. Else
false

"A string" == "a string"

False

"A string" == "A string"

True

Strings Methods
Python provides many built-in methods for manipulating strings. As a programmer,
knowing typical string methods and how to use them will give you a real leverage when
working with strings.
There are many string methods. You can find them here. Let's see some common methods.

Metode șiruri
Python oferă multe metode încorporate pentru manipularea șirurilor de caractere. În
calitate de programator, cunoașterea metodelor tipice de șiruri și modul de utilizare a
acestora vă va oferi o pâ rghie reală atunci câ nd lucrați cu șiruri.
Există multe metode cu șiruri. Le puteți gă si aici. Să vedem câ teva metode comune.
sentence = 'This IS A String'

# Case capitalization
# It return the string with first letter capitalized and the rest being lower
cases.

sentence.capitalize()

'This is a string'

# Given a string, convert it into title (each word is capitalized)

sentence_2 = 'this is a string to be titled'


sentence_2.title()

'This Is A String To Be Titled'

# Converting the string to upper case

sentence.upper()

'THIS IS A STRING'

# Converting the string to upper case

sentence.lower()

'this is a string'

# Splitting the string

sentence.split()

['This', 'IS', 'A', 'String']

Lastly, we can use replace() method to replace some characters in string with another
characters. Replace method takes two inputs: characters to be replaced, and new
characters to be inserted in string, replace('characters to be replaced', 'new
characters').

Example, given the string "This movie was awesome", replace the world movie with
project.

În cele din urmă , putem folosi metoda replace() pentru a înlocui unele caractere din șir cu
alte caractere. Metoda de înlocuire necesită două intră ri: caractere care urmează să fie
înlocuite și caractere noi care trebuie introduse în șir, replace('caracterele de
înlocuit', 'caractere noi').

De exemplu, avâ nd în vedere șirul „Acest film a fost grozav”, înlocuiți lumea „film” cu
„proiect”.
stri = "This movie was awesome"
stri.replace('movie', 'project')

'This project was awesome'

# In the following string, replace all spaces with `%20'

stri_2 = "The future is great"


stri_2.replace(' ', '%20')

'The%20future%20is%20great'

As you can see, strings methods are powerful and can save you time. Remember one of the
Python philosophies that we saw in the beginning: Simple is better than complex.
După cum puteți vedea, metodele cu șiruri sunt puternice și vă pot economisi timp.
Amintiți-vă una dintre filozofiile Python pe care le-am vă zut la început: „Simplu este mai
bine decâ t complex”.

2. Data Structures

2. Structuri de date
Data structures are used to organize and store the data. Algorithms supports operations on
data.
Python has 4 main data structures: Lists, Dictionaries, Tuples and Sets.
Structurile de date sunt folosite pentru a organiza și stoca datele. Algoritmii acceptă
operațiuni pe date.
Python are 4 structuri principale de date: Liste, Dicționare, Tuple și Seturi.

2.1 List

2.1 Lista
A list is a set of ordered values. Each value in a list is called an element or item and can be
identified by an index. A list supports different data types, we can have a list of integers,
strings, and floats.
What we will see with Python lists:
• Creating a list
• Accessing elements in a list
• Slicing a list
• Changing elements in a list
• Traversing a list
• Operations on list
• Nested lists
• List methods
• List and strings
O listă este un set de valori ordonate. Fiecare valoare dintr-o listă este numită „element”
sau „articol” și poate fi identificată printr-un index. O listă acceptă diferite tipuri de date,
putem avea o listă de numere întregi, șiruri și elemente flotante.
Ce vom vedea cu listele Python:
• Crearea unei liste
• Accesarea elementelor dintr-o listă
• Tă ierea unei liste
• Schimbarea elementelor dintr-o listă
• Parcurgerea unei liste
• Operațiuni pe listă
• Liste imbricate
• Enumeră metode
• Listă și șiruri

Creating a List
A python list can be created by enclosing elements of similar or different data type in
square brackets [...], or with range() function.

Crearea unei liste


O listă Python poate fi creată prin includerea elementelor de tip de date similare sau
diferite între paranteze drepte „[...]” sau cu funcția „range()”.
# Creating a list

week_days = ['Mon', 'Tue', 'Wed', 'Thur','Fri']


even_numbers = [2, 4, 6, 8, 10]
mixed_list = ['Mon', 1, 'Tue', 2, 'Wed', 3]

# Displaying elements of a list


print(week_days)

['Mon', 'Tue', 'Wed', 'Thur', 'Fri']

# Creating a list with range()


nums = range(5)

for i in nums:
print(i)

0
1
2
3
4

Accessing the elements of the list

Accesarea elementelor listei


We can access the a given element of the list by providing the index of the element in a
bracket. The index starts at 0 in Python.
Putem accesa un anumit element al listei furnizâ nd indexul elementului într-o paranteză .
Indexul începe de la 0 în Python.
# Accessing the first elements of the list

week_days[0]

'Mon'

even_numbers[2]

# Getting the last element of the list

print(even_numbers[-1])

10

Slicing a list

Tăierea unei liste


Given a list, we can slice it to get any parts or combination of its elements forming another
list.
Avâ nd o listă , o putem tă ia pentru a obține orice pă rți sau combinații ale elementelor sale
formâ nd o altă listă .
# Get the elements from index 0 to 2. Index 2 is not included.

week_days = ['Mon', 'Tue', 'Wed', 'Thur','Fri']


week_days[0:2]
['Mon', 'Tue']

# Get elements from the last fourth elements to the first


# -1 starts at the last element 'Fri', -2 second last element `Thur'..... -4
to 'Tue'

week_days[-4:]

['Tue', 'Wed', 'Thur', 'Fri']

# Get all elements up to the fourth index

week_days[:4]

['Mon', 'Tue', 'Wed', 'Thur']

# Get all elements from the second to the last index

week_days[2:]

['Wed', 'Thur', 'Fri']

You can use [:] to copy the entire list.


week_days[:]

['Mon', 'Tue', 'Wed', 'Thur', 'Fri']

Changing elements in a list


Python lists are mutable. We can delete or change the elements of the list.

Schimbarea elementelor dintr-o listă


Listele Python sunt modificabile. Putem șterge sau modifica elementele listei.
names = ['James', 'Jean', 'Sebastian', 'Prit']
names

['James', 'Jean', 'Sebastian', 'Prit']

# Change 'Jean' to 'Nyandwi' and 'Sebastian' to 'Ras'

names[1:3] = ['Nyandwi', 'Ras']


names

['James', 'Nyandwi', 'Ras', 'Prit']

# Change 'Prit' to Sun

names[-1] = 'Sun'
names
['James', 'Nyandwi', 'Ras', 'Sun']

# Change `James` to ``Francois`

names[0] = 'Francois'
names

['Francois', 'Nyandwi', 'Ras', 'Sun']

In order to delete a given element in a list, we can empty slice it but the better way to delete
element is to use del keyword.
Pentru a șterge un anumit element dintr-o listă , îl putem goli, dar cel mai bun mod de a
șterge elementul este să folosiți cuvâ ntul cheie del.
# Delete Nyandwi in names list

del names[1]
names

['Francois', 'Ras', 'Sun']

If you know the index of the element you want to remove, you can use pop(). If you don't
provide the index in pop(), the last element will be deleted.
Dacă cunoașteți indexul elementului pe care doriți să îl eliminați, puteți utiliza pop(). Dacă
nu furnizați indexul în pop(), ultimul element va fi șters.
names = ['James', 'Jean', 'Sebastian', 'Prit']
names.pop(2)
names

['James', 'Jean', 'Prit']

Also, we can use remove() to delete the element provided inside the remove() method.
names = ['James', 'Jean', 'Sebastian', 'Prit']
names.remove('James')
names

['Jean', 'Sebastian', 'Prit']

We can also use append() to add element to the list.


De asemenea, putem folosi append() pentru a adă uga un element în listă .
# Adding the new elements in list

names = ['James', 'Jean', 'Sebastian', 'Prit']


names.append('Jac')
names.append('Jess')
names
['James', 'Jean', 'Sebastian', 'Prit', 'Jac', 'Jess']

Traversing a list

Parcurgerea unei liste


There are times that we may need to go over the list to read the elements of the list or
perform iterative operations. We can use for loop to traverse through the list.
Există momente în care ar putea fi nevoie să trecem peste lista pentru a citi elementele
listei sau pentru a efectua operații iterative. Putem folosi for loop pentru a parcurge lista.
# Given a list names, use for loop to display its elements

names = ['James', 'Jean', 'Sebastian', 'Prit']

for name in names:


print(name)

James
Jean
Sebastian
Prit

# Given a list nums, add 1 to the first element, 2 to the second, 3 to 3rd
element, 4 to 4th element
# Example: nums = [1,2,3,6] will be nums_new = [2,4,6,10]

nums = [1, 2, 3, 6]
nums_new = []

for i in range(len(nums)): #len(nums) gives the length of the list


num = nums[i] + i + 1
nums_new.append(num)

nums_new

[2, 4, 6, 10]

Operations on list

Operațiuni pe listă
# Concatenating two lists

a = [1,2,3]
b = [4,5,6]

c = a + b

c
[1, 2, 3, 4, 5, 6]

# We can also use * operator to repeat a list a number of times

[None] * 5

[None, None, None, None, None]

[True] * 4

[True, True, True, True]

[1,2,4,5] * 2

[1, 2, 4, 5, 1, 2, 4, 5]

Nested lists

Liste imbricate
# Creating a list in other list

nested_list = [1,2,3, ['a', 'b', 'c']]

# Get the ['a', 'b', 'c'] from the nested_list

nested_list[3]

['a', 'b', 'c']

# Indexing and slicing a nested list is quite similar to normal list

nested_list[1]

List Methods
Python also offers methods which make it easy to work with lists. We already have been
using some list methods such as pop() and append() but let's review more other methods.

Listează metode
Python oferă , de asemenea, metode care facilitează lucrul cu liste. Am folosit deja unele
metode de listă , cum ar fi pop() și append(), dar haideți să revizuim mai multe alte metode.
# Sorting a list with sort()

even_numbers = [2,14,16,12,20,8,10]

even_numbers.sort()
even_numbers

[2, 8, 10, 12, 14, 16, 20]

# Reversing a string with reverse()

even_numbers.reverse()
even_numbers

[20, 16, 14, 12, 10, 8, 2]

# Adding other elements to a list with append()

even_numbers = [2,14,16,12,20,8,10]

even_numbers.append(40)
even_numbers

[2, 14, 16, 12, 20, 8, 10, 40]

# Removing the first element of a list

even_numbers.remove(2)
even_numbers

[14, 16, 12, 20, 8, 10, 40]

## Return the element of the list at index x

even_numbers = [2,14,16,12,20,8,10]

## Return the item at the 1st index

even_numbers.pop(1)

14

# pop() without index specified will return the last element of the list

even_numbers = [2,14,16,12,20,8,10]
even_numbers.pop()

10

# Count a number of times an element appear in a list

even_numbers = [2,2,4,6,8]
even_numbers.count(2)

2
List and strings

Listă și șiruri
We previously have learned about strings. Strings are sequence of characters. List is a
sequence of values.
Am învă țat anterior despre șiruri. Ș irurile sunt o secvență de caractere. Lista este o
succesiune de valori.
# We can convert a string into list

stri = 'Apple'

list(stri)

['A', 'p', 'p', 'l', 'e']

# Splitting a string produces a list of individual words

stri_2 = "List and Strings"


stri_2.split()

['List', 'and', 'Strings']

The split() string method allows to specify the character to use a a boundary while splitting
the string. It's called delimiter.
Metoda șirului split() permite specificarea caracterului pentru a utiliza o limită în timp ce
împă rțirea șirului. Se numește delimitator.
stri_3 = "state-of-the-art"

stri_3.split('-')

['state', 'of', 'the', 'art']

2.2 Dictionaries

2.2 Dicționare
Dictionaries are powerful Python builtin data structure that are used to store data of key
and values. A dictionary is like a list but rather than using integers as indices, indices in
dictionary can be any data type. Also, unlike lists, dictionary are unordered. Dictionaries
dont guarrantee keeping the order of the data.
Generally, a dictionary is a collection of key and values. A dictionary stores a mapping of
keys and values. A key is what we can refer to index.
What we will see:
• Creating a dictionary
• Accessing values and keys in dictionary
• Solving counting problems with dictionary
• Traversing a dictionary
• The setdefault() method
Dicționarele sunt puternice structuri de date încorporate în Python, care sunt folosite
pentru a stoca date ale cheilor și ale valorilor. Un dicționar este ca o listă , dar în loc să
folosească numere întregi ca indici, indicii din dicționar pot fi orice tip de date. De
asemenea, spre deosebire de liste, dicționarul este neordonat. Dicționarele nu garantează
pă strarea ordinii datelor.
În general, un dicționar este o colecție de chei și valori. Un dicționar stochează o mapare a
cheilor și a valorilor. O cheie este ceea ce ne putem referi la index.
Ce vom vedea:
• Crearea unui dicționar
• Accesarea valorilor și cheilor în dicționar
• Rezolvarea problemelor de numă rare cu dicționar
• Parcurgâ nd un dicționar
• Metoda setdefault().

Creating a dictionary

Crearea unui dicționar


We can create with a dict() function and add items later, or insert keys and values right
away in the curly brackets { }. Let's start with dict() function to create an empty dictionary.
Putem crea cu o funcție dict() și putem adă uga elemente mai tâ rziu, sau inseră m chei și
valori imediat în paranteze { }. Să începem cu funcția dict() pentru a crea un dicționar gol.
# Creating a dictionary

countries_code = dict()
print(countries_code)

{}

You can verify it's a dictionary by passing it through type().


Puteți verifica că este un dicționar trecâ ndu-l prin type().
type(countries_code)

dict
Let's add items to the empty dictionary that we just created.
Să adă ugă m elemente la dicționarul gol pe care tocmai l-am creat.
# Adding items to the empty dictionary.

countries_code["United States"] = 1

countries_code

{'United States': 1}

Let's create a dictionary with {}. It's the common way to create a dictionary.
Să creă m un dicționar cu {}. Este modalitatea obișnuită de a crea un dicționar.
countries_code = {
"United States": 1,
"China": 86,
"Rwanda":250,
"Germany": 49,
"India": 91,
}

countries_code

{'United States': 1, 'China': 86, 'Rwanda': 250, 'Germany': 49, 'India': 91}

To add key and values to a dictionary, we just add the new key to [ ] and set its new value.
See below for example...
Pentru a adă uga cheie și valori la un dicționar, adă ugă m noua cheie la [ ] și setă m noua ei
valoare. Vezi mai jos de exemplu...
countries_code['Australia'] = 61
countries_code

{'United States': 1,
'China': 86,
'Rwanda': 250,
'Germany': 49,
'India': 91,
'Australia': 61}

Accessing the values and keys in a dictionary

Accesarea valorilor și cheilor dintr-un dicționar


Just like how we get values in a list by using their indices, in dictionary, we can use a key to
get its corresponding value.
La fel ca și cum obținem valori într-o listă folosind indicii lor, în dicționar, putem folosi o
cheie pentru a obține valoarea corespunză toare.
# Getting the code of Rwanda

countries_code["Rwanda"]

250

We can also check if a key exists in a dictionary by using a classic in operator.


De asemenea, putem verifica dacă o cheie există într-un dicționar folosind un operator
clasic in.
"India" in countries_code

True

# Should be False

"Singapore" in countries_code

False

To get all the keys, value, and items of the dictionary, we can respectively use keys(),
values(), and items() methods.

Pentru a obține toate cheile, valoarea și elementele dicționarului, putem folosi metodele
keys(), values() și, respectiv, items().
# Getting the keys and the values and items of the dictionary

dict_keys = countries_code.keys()
dict_values = countries_code.values()
dict_items = countries_code.items()

print(f"Keys: {dict_keys}\n Values:{dict_values}\n Items:{dict_items}")

Keys: dict_keys(['United States', 'China', 'Rwanda', 'Germany', 'India',


'Australia'])
Values:dict_values([1, 86, 250, 49, 91, 61])
Items:dict_items([('United States', 1), ('China', 86), ('Rwanda', 250),
('Germany', 49), ('India', 91), ('Australia', 61)])

Lastly, we can use get() method to return the value of a specified key. Get method allows
to also provide a value that will be returned in case the key doesn't exists. This is a cool
feature!!
În cele din urmă , putem folosi metoda get() pentru a returna valoarea unei chei
specificate. Metoda Get permite, de asemenea, să furnizeze o valoare care va fi returnată în
cazul în care cheia nu există . Aceasta este o caracteristică cool!!
# Get the value of the Australia

countries_code.get('Australia')

61

# In case a provided key is absent....

countries_code.get('UK', 41)

41

Solving counting problems with dictionary


When solving real world problems, or perhaps doing interviews, most problems involve
counting certain elements. Let's take a simple example: Given a string, write an algorithm
that can count the occurence of each character.
Solution:
The first approach would be to create a list of 128 elements given that the standard size of
characters in ASCII is 128, convert each character to a number with ord() method(char()
convert from number to string), use the number as the index of the string, and then
increment it as you see a recurring character. The code would like like this....
Using dictionary, we would not have to worry about the size of the string or the nmber of
characters to keep beforehand. We would just create a dictionary whose keys are
characters and values are counts of corresponding characters. See character for the first
time, add it to the dictionary with value of 1 since it's the first count, and then increment it
if the character exists in dictionary.

Traversing a dictionary
We previously used for loop in dictionary to iterate through the values. Let's review it
again.

Parcurgând un dicționar
Am folosit anterior pentru buclă în dicționar pentru a itera prin valori. Să o revizuim din
nou.
countries_code

{'United States': 1,
'China': 86,
'Rwanda': 250,
'Germany': 49,
'India': 91,
'Australia': 61}

for country in countries_code:


print(country)
United States
China
Rwanda
Germany
India
Australia

We can also iterate through the items(key, values) of the dictionary.


De asemenea, putem itera elementele (cheie, valori) din dicționar.
for country, code in countries_code.items():
print(country, code)

United States 1
China 86
Rwanda 250
Germany 49
India 91
Australia 61

The setdefault() Method


The setdefault() method allows you to set a value of a given key that does not already have
a key. This can be helpful when you want to update the dictionary with a new value in case
the key you are looking for does not exist.

Metoda setdefault().
Metoda setdefault() vă permite să setați o valoare pentru o anumită cheie care nu are deja
o cheie. Acest lucru poate fi util atunci câ nd doriți să actualizați dicționarul cu o nouă
valoare în cazul în care cheia pe care o că utați nu există .
countries_code.setdefault("UK", 41)

41

countries_code

{'United States': 1,
'China': 86,
'Rwanda': 250,
'Germany': 49,
'India': 91,
'Australia': 61,
'UK': 41}

Cool! The UK value is added to the dictionary because it was not in the dictionary before.
The setdefault() method and get() method are different.
We can also use the setdefault() in the count program we wrote above.
Misto! Valoarea din Marea Britanie este adă ugată la dicționar deoarece nu era în dicționar
înainte. Metoda setdefault() și metoda get() sunt diferite.
De asemenea, putem folosi setdefault() în programul de numă rare pe care l-am scris mai
sus.
stri = input(str) #input must be a string

char_count = {}

for c in stri:
char_count.setdefault(c,0) #If character doesn't exist in char_count, add
it and set it to 0
char_count[c] += 1

print(char_count)

<class 'str'>AAAHHSHSHS
{'A': 3, 'H': 4, 'S': 3}

Summarizing dictionary
• Dictionaries are not ordered and they can not be sorted - list are ordered (and
unordered) and can be sorted.

• Dictionary can store data of different types: floats, integers and strings and can also
store lists.

<>Dicționar de rezumat<>**Dicționarele nu sunt ordonate și nu pot fi sortate - lista sunt


ordonate (și neordonate) și pot fi sortate.* Dicționarul poate stoca date de diferite tipuri:
flotanți, întregi și șiruri de caractere și poate stoca și liste.

2.3 Tuples
Tuple is similar to list but the difference is that you can't change the values once it is
defined (termed as immutability). Due to this property it can be used to keep things that
you do not want to change in your program. Example can be a country codes, zipcodes, etc...

2.3 Tupluri
Tuplu este similar cu lista, dar diferența este că nu puteți modifica valorile odată ce este
definit (numit „imuabilitate”). Datorită acestei proprietă ți, poate fi folosit pentru a pă stra
lucruri pe care nu doriți să le modificați în program. Un exemplu poate fi un cod de țară ,
coduri poștale etc...
tup = (1,4,5,6,7,8)
# Indexing

tup[4]

## Tuples are not changeable. Running below code will cause an error

# tup[2] = 10

# You can not also add other values to the tuple. This will be error
#tup.append(12)

2.4 Sets

2.4 Seturi
Sets are used to store the unique elements. They are not ordered like list.
Seturile sunt folosite pentru a stoca elementele unice. Nu sunt ordonate ca lista.
set_1 = {1,2,3,4,5,6,7,8}

set_1

{1, 2, 3, 4, 5, 6, 7, 8}

set_2 = {1,1,2,3,5,3,2,2,4,5,7,8,8,5}
set_2

{1, 2, 3, 4, 5, 7, 8}

As you can see, set only keep unique values. There can't be a repetition of values.
După cum puteți vedea, setați doar pă strați valori unice. Nu poate exista o repetare a
valorilor.
# List Vs Set

odd_numbers = [1,1,3,7,9,3,5,7,9,9]

print("List:{}".format(odd_numbers))

print("********")

set_odd_numbers = {1,1,3,7,9,3,5,7,9,9}

print("Set:{}".format(set_odd_numbers))
List:[1, 1, 3, 7, 9, 3, 5, 7, 9, 9]
********
Set:{1, 3, 5, 7, 9}

3. Comparison and Logic operators


Comparison operators are used to compare values. It will either return true or false.

3. Comparație și operatori logici


Operatorii „comparație” sunt utilizați pentru a compara valori. Va returna fie adevă rat, fie
fals.
## Greater than
100 > 1

True

## Equal to

100 == 1

False

## Less than

100 < 1

False

## Greater or equal to

100 >= 1

True

## Less or equal to

100 <= 1

False

'Intro to Python' == 'intro to python'

False

'Intro to Python' == 'Intro to Python'

True
Logic operators are used to compare two expressions made by comparison operators.

• Logic and returns true only when both expressions are true, otherwise false.

• Logic or returns true when either any of both expressions is true. Only false if both
expressions are false.

• Logic not as you can guess, it will return false when given expression is true, vice
versa.

Operatorii logici sunt folosiți pentru a compara două expresii realizate de operatorii de
comparare.
și logic returnează adevărat numai când ambele expresii sunt adevărate, în caz contrar false.
sau logic returnează adevă rat atunci câ nd oricare dintre ambele expresii este adevă rată .
Fals numai dacă ambele expresii sunt false.
• Logica „nu” așa cum puteți ghici, va returna fals atunci câ nd expresia dată este
adevă rată , invers.
100 == 100 and 100 == 100

True

100 <= 10 and 100 == 100

False

100 == 10 or 100 == 100

True

100 == 10 or 100 == 10

False

not 1 == 2

True

not 1 == 1

False

4. Control Flow
As an engineer, you will need to make decisions depending on the particular situation. You
will also need to control the flow of the program and this is where Control Flow comes in.
We will cover:
• If statement
• For loop
• While loop

4. Controlul fluxului
Ca inginer, va trebui să iei decizii în funcție de situația particulară . De asemenea, va trebui
să controlați fluxul programului și aici intervine Control Flow.
Vom acoperi:
Declarația If Pentru buclă
• bucla While

4.1 If, Elif, Else

4.1 If, Elif, Else


Structure of If condition:
if condition:
do something

else:
do this

if 100 < 2:

print("As expected, no thing will be displayed")

if 100 > 2:

print("As expected, no thing will be displayed")

As expected, no thing will be displayed

if 100 < 2:

print("As expected, no thing will be displayed")

else:
print('Printed')

Printed
# Let's assign a number to a variable name 'jean_age' and 'yannick_age'

john_age = 30
luck_age = 20

if john_age > luck_age:


print("John is older than Luck")

else:
print(" John is younger than Luck")

John is older than Luck

# Let's use multiple conditions

john_age = 30
luck_age = 20
yan_age = 30

if john_age < luck_age:


print("John is older than Luck")

elif yan_age == luck_age:


print(" Yan's Age is same as Luck")

elif luck_age > john_age:


print("Luck is older than John")

else:
print("John's age is same as Yan")

John's age is same as Yan

We can also put if condition into one line of code. This can be useful when you want to
make a quick decision between few choices.
Here is the structure:
'value_to_return_if_true' if condition else 'value_to_return_if_false'

Let's take some examples...


De asemenea, putem pune condiția if într-o singură linie de cod. Acest lucru poate fi util
atunci câ nd doriți să luați o decizie rapidă între câ teva alegeri.
Iată structura:
'valoare_la_return_if_true' if condiție altfel 'valoare_la_return_if_false'

Să luă m câ teva exemple...


# Example 1: Return 'Even' if below num is 'Even' and `Odd` if not.

num = 45

'Even' if num % 2 == 0 else 'Odd'

'Odd'

# Example 2: Return True if a given element is in a list and False if not

nums = [1,2,3,4,5,6]

True if 3 in nums else False

True

4.2 For Loop


For loop is used to iterate over list, string, tuples, or dictionary.
Structure of for loop:
for item in items:
do something

For loop is used to iterate over list, string, tuples, or dictionary.


Structure of for loop:
for item in items:
do something

even_nums = [2,4,6,8,10]

for num in even_nums:


print(num)

2
4
6
8
10

week_days = ['Mon', 'Tue', 'Wed', 'Thur','Fri']

for day in week_days:


print(day)

Mon
Tue
Wed
Thur
Fri

# For loop in dictionary

countries_code = { "United States": 1,


"India": 91,
"Germany": 49,
"China": 86,
"Rwanda":250
}

for country in countries_code:


print(country)

United States
India
Germany
China
Rwanda

for code in countries_code.values():


print(code)

1
91
49
86
250

For can also be used to iterate over an sequence of numbers. Range is used to generate the
sequence of numbers.
for number in range:
do something

for number in range(10):


print(number)

0
1
2
3
4
5
6
7
8
9
for number in range(10, 20):
print(number)

10
11
12
13
14
15
16
17
18
19

One last thing about for loop is that we can use it to make a list. This is called list
comprehension.
Un ultim lucru despre for loop este că îl putem folosi pentru a face o listă . Aceasta se
numește înțelegerea listei.
letters = []

for letter in 'MachineLearning':


letters.append(letter)

letters

['M', 'a', 'c', 'h', 'i', 'n', 'e', 'L', 'e', 'a', 'r', 'n', 'i', 'n', 'g']

The above code can be simplified to the following code:


Codul de mai sus poate fi simplificat la urmă torul cod:
letters = [letter for letter in 'MachineLearning']

letters

['M', 'a', 'c', 'h', 'i', 'n', 'e', 'L', 'e', 'a', 'r', 'n', 'i', 'n', 'g']

4.3 While loop


While loop will executes the statement(s) as long as the condition is true.
Structure of while loop
while condition:
statement(s)

a = 10
while a < 20:
print('a is: {}'.format(a))
a = a + 1

a is: 10
a is: 11
a is: 12
a is: 13
a is: 14
a is: 15
a is: 16
a is: 17
a is: 18
a is: 19

5. Functions
Functions are used to write codes or statements that can be used multiple times with
different parameters.
One fundamental rule in programming is "DRY" or Do not Repeat Yourself. Functions will
help to not repeat yourself.
This is how you define a function in Python:
def function_name(parameters):

"""
This is Doc String
You can use it to notes about the functions
"""
statements

return results

• function_name is the name of the function. It must not be similar to any built in
functions. We will see built in functions later.

• parameters are the values that are passed to the function.

• Doc String is used to add notes about the function. It is not a must to use it but it is
a good practice.

• return specify something or value that you want to return everytime you call or run
your function.
5. Funcții
Funcțiile sunt folosite pentru a scrie coduri sau instrucțiuni care pot fi folosite de mai multe
ori cu parametri diferiți.
O regulă fundamentală în programare este „USCAT” sau nu te repeta. Funcțiile vă vor ajuta
să nu vă repetați.
Iată cum definiți o funcție în Python:
def function_name(parametri):

"""
Acesta este Doc String
Îl puteți folosi pentru a nota despre funcții
"""
declarații

returnează rezultatele

• funcție_nume este numele funcției. Nu trebuie să fie similar cu nicio funcție


încorporată . Vom vedea funcțiile integrate mai tâ rziu. parametrii sunt valorile care
sunt transmise funcției. Doc String este folosit pentru a adă uga note despre funcție.
Nu este obligatoriu să îl folosiți, dar este o „bună practică ”.

• return specificați ceva sau valoarea pe care doriți să o returnați de fiecare dată câ nd
apelați sau rulați funcția.
# Function to add two numbers and return a sum

def add_nums(a,b):

"""
Function to add two numbers given as inputs
It will return a sum of these two numbers
"""

sum = a+b

return sum

add_nums(2,4)

add_nums(4,5)

9
# Displaying the doc string noted early

print(add_nums.__doc__)

Function to add two numbers given as inputs


It will return a sum of these two numbers

def activity(name_1, name_2):

print("{} and {} are playing basketball!".format(name_1, name_2))

activity("Chris", "Francois")

Chris and Francois are playing basketball!

activity("Kennedy", "Kleber")

Kennedy and Kleber are playing basketball!

As you can see, functions do not need to always have return. When you only want to
display the customized message (not involving expression), print() will be enough.
După cum puteți vedea, funcțiile nu trebuie să aibă întotdeauna „return”. Câ nd doriți să
afișați doar mesajul personalizat (nu implică expresia), print() va fi suficient.

6. Lamdba Functions
There are times that you want to create anonymous functions. These types of functions will
only need to have one expressions.
## Sum of two numbers

def add_nums(a,b):

sum = a+b

return sum

add_nums(1,3)

We can use lambda to make the same function in just one line of code! Let's do it!!
Putem folosi lambda pentru a face aceeași funcție într-o singură linie de cod! Hai să o
facem!!
sum_of_two_nums = lambda c,d: c + d

sum_of_two_nums(4,5)

7. Built in Functions
Python being a high level programming language, it has bunch of built in functions which
make it easy to get quick computations done.
An example of built in functions we used is len() which gives the length of the string or the
list givhttps://github.com/Nyandwi/python_basics/blob/main/n as the input to it.
Here is a full preview on all Python Built in functions.

# using len() to count the length of the string

message = 'Do not give up!'


len(message)

15

odd_numbers = [1,3,5,7]
len(odd_numbers)

4
# Using max() to find the maximum number in a list

odd_numbers = [1,3,5,7]
max(odd_numbers)

# Using min() to find the minimum number in a list

min(odd_numbers)

# Sorting the list with sorted()

odd_numbers = [9,7,3,5,11,13,15,1]

sorted(odd_numbers)

[1, 3, 5, 7, 9, 11, 13, 15]

Let's learn two more useful built functions: they are map and filter. You can try to explore
or use more built in functions on your own.
Să învă ță m încă două funcții utile construite: ele sunt map și filter. Puteți încerca să
explorați sau să utilizați mai multe funcții încorporate pe cont propriu.

7.1 Map function


Map gives you the ability to apply a function to an iterable structures such as list. When
used with a list for example, you can apply the function to every element of the list.
Let's see how it works.

7.1 Funcția map


Harta vă oferă posibilitatea de a aplica o funcție unei structuri iterabile, cum ar fi o listă .
Câ nd este utilizat cu o listă , de exemplu, puteți aplica funcția fiecă rui element al listei.
Să vedem cum funcționează .
def cubic(number):
return number ** 3

num_list = [0,1,2,3,4]

# Applying `map` to the num_list to just return the list where each element
is cubed...(xxx3)
list(map(cubic, num_list))

[0, 1, 8, 27, 64]

7.2 Filter function


Let's say that you have a list of numbers and you want to filter the list and remain with odd
numbers. Odd number is any number which can not be divided by 2.
You can develop a function to calculate it but you would have to always pass single value or
values but not entire list.
Using filter, you can return true for every element of list evaluated by the function.

7.2 Funcția de filtrare


Să presupunem că aveți o listă de numere și doriți să filtrați lista și să ră mâ neți cu numere
impare. Numă rul impar este orice numă r care nu poate fi împă rțit la 2.
Puteți dezvolta o funcție pentru a o calcula, dar ar trebui să treceți întotdeauna o singură
valoare sau valori, dar nu o listă întreagă .
Folosind filter, puteți returna true pentru fiecare element al listei evaluat de funcție.
def odd_check(number):

return number % 2 != 0

# != is not equal to operation

num_list = [1,2,4,5,6,7,8,9,10,11]

list(filter(odd_check, num_list))

[1, 5, 7, 9, 11]

8. More Useful Python Stuff

8. Lucruri Python mai utile


Python is an awesome programming language that has a lot of useful functions.
Let's see more useful things you may need beyond what's we just saw already.
Python este un limbaj de programare minunat care are o mulțime de funcții utile.
Să vedem mai multe lucruri utile de care ai putea avea nevoie în afară de ceea ce tocmai am
vă zut deja.

8.1 List Comprehension

8.1 Înțelegerea listei


List comprehension makes it easy to make a new list from an existing list based on a given
conditions. It's very concise and readable.
Take an example for the following cases.
Înțelegerea listei facilitează crearea unei noi liste dintr-o listă existentă pe baza unor
condiții date. Este foarte concis și ușor de citit.
Luați un exemplu pentru urmă toarele cazuri.
# Given a list of numbers, can you make a new list of even numbers from the
list nums?
# Even numbers are numbers divisible by 2, and they give the remainder of 0

nums = range(1,20)
even_nums = []

# A traditional way to do it is:

for num in nums:


if num % 2 == 0:
even_nums.append(num)

print(even_nums)

[2, 4, 6, 8, 10, 12, 14, 16, 18]

A more concise and easy way to do that is to use list comprehension.


even_nums = [num for num in nums if num % 2 == 0]
print(even_nums)

[2, 4, 6, 8, 10, 12, 14, 16, 18]

You can see it's pretty simple. And more readable than the former. Let's take another
example.
Puteți vedea că este destul de simplu. Ș i mai lizibil decâ t primul. Să luă m un alt exemplu.
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
day_T = []
# Make a list of days that start with `T`

for day in days:


if day[0] == 'T':
day_T.append(day)

print(day_T)

['Tuesday', 'Thursday']

A more concise way to do it would be:


O modalitate mai concisă de a face acest lucru ar fi:
day_T = [day for day in days if day[0] == 'T']
print(day_T)

['Tuesday', 'Thursday']

8.2 Enumerate Function

8.2 Funcția de enumerare


Enumerate function convert iterable objects into enumerate object. It basically returns a
tuple that also contain a counter.
That's sounds hard, but with examples, you can see how powerful this function is...
Funcția de enumerare convertește obiectele iterabile în obiect enumerate. Practic
returnează un tuplu care conține și un contor.
Sună greu, dar cu exemple, poți vedea câ t de puternică este această funcție...
seasons = ['Spring', 'Summer', 'Fall', 'Winter']

list(enumerate(seasons))

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

As you can see, each element came with index counter automatically. The counter initially
start at 0, but we can change it.
După cum puteți vedea, fiecare element a venit automat cu contor index. Contorul începe
inițial de la 0, dar îl putem schimba.
list(enumerate(seasons, start=1))

[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Here is another example:


Iată un alt exemplu:
class_names = ['Rock', 'Paper', 'Scissor']

for index, class_name in enumerate(class_names, start=0):


print(index,'-',class_name)

0 - Rock
1 - Paper
2 - Scissor

8.3 Zip Function

8.3 Funcția Zip


Zip is an incredible function that takes two iterators and returns a pair of corresponsing
elements as a tuple.
Zip este o funcție incredibilă care ia doi iteratoare și returnează o pereche de elemente
corespunză toare ca un tuplu.
name = ['Jessy', 'Joe', 'Jeannette']
role = ['ML Engineer', 'Web Developer', 'Data Engineer']

zipped_name_role = zip(name, role)


zipped_name_role

<zip at 0x107ebc9c0>

The zip object return nothing. In order to show the zipped elements, we can use a list. It's
also same thing for enumerate you saw above.
Obiectul zip nu returnează nimic. Pentru a afișa elementele cu fermoar, putem folosi o listă .
Este același lucru și pentru enumerarea pe care ați vă zut-o mai sus.
list(zipped_name_role)

[('Jessy', 'ML Engineer'),


('Joe', 'Web Developer'),
('Jeannette', 'Data Engineer')]

You might also like