8

Python, , .

, , , - , .

Python, . , , .


1. import *

, , from xyz import *.

. :

  1. : , , .
  2. : *, , .

? - , .

# Using import *

# Bad
from math import *

print(floor(2.4))
print(ceil(2.4))
print(pi)

# Good
import math
from math import pi

print(math.floor(2.4))
print(math.ceil(2.4))
print(pi)	

2. Try/except: except

. , Pycharm ( ), . PEP8.

# Try - except

# Bad
try:
    driver.find_element(...)
except:
    print("Which exception?")

# Good
try:
    driver.find_element(...)
except NoSuchElementException:
    print("It's giving NoSuchElementException")
except ElementClickInterceptedException:
    print("It's giving ElementClickInterceptedException")	

, SystemExit KeyboardInterrupt, Control-C.

, try/except, except.


3. Numpy

, Python , .

Numpy . Numpy , for.

, random_scores, , (score<70). for.

import numpy as np

random_scores = np.random.randint(1, 100, size=10000001)

# Bad (solving problem with a for loop)
count_failed = 0
sum_failed = 0
for score in random_scores:
    if score < 70:
        sum_failed += score
        count_failed += 1

print(sum_failed/count_failed)	

Numpy.

# Good (solving problem using vector operations)
mean_failed = (random_scores[random_scores < 70]).mean()
print(mean_failed)	

, , Numpy . ? Numpy .


4.

, , , , Python, .

open, write/read, close . , write/read , .

, , with. , .

# Bad
f = open('dataset.txt', 'w')
f.write('new_data')
f.close()

# Good
with open('dataset.txt', 'w') as f:
    f.write('new_data')	

5. PEP8

PEP8 , , Python. Python ( PEP8).

Python. , PEP8 IDE ( , ).

, Pycharm. , 8, .

PEP8

, .

.

# Good
my_list = [1, 2, 3, 4, 5]
my_dict = {'key1': 'value1', 'key2': 'value2'}

my_name = "Frank"	

x my_name. Pycharm , 8 , , .


6. .keys .values

, , .keys .values .

, .

dict_countries = {'USA': 329.5, 'UK': 67.2, 'Canada': 38}>>>dict_countries.keys()
dict_keys(['USA', 'UK', 'Canada'])>>>dict_countries.values()
dict_values([329.5, 67.2, 38])	

, .

, . .keys, , , ? .keys .

# Not using .keys() properly
# Bad
for key in dict_countries.keys():
    print(key)
    
# Good
for key in dict_countries:
    print(key)	

, , , .items().

# Not using .items()
# Bad
for key in dict_countries:
    print(dict_countries[key])
    
# Good
for key, value in dict_countries.items():
    print(key)
    print(value)	

7. ( )

(, ..) .

, countries .

for, .

# Bad
countries = ['USA', 'UK', 'Canada']

lower_case = []
for country in countries:
    lower_case.append(country.lower())

# Good (but don't overuse it!)
lower_case = [country.lower() for country in countries]	

, ! Python: , .


8. range(len())

, range len, , range(len()) .

: countries populations. , , , range(len()).

# Using range(len())
countries = ['USA', 'UK', 'Canada']
populations = [329.5, 67.2, 38]

# Bad
for i in range(len(countries)):
    country = countries[i]
    population = populations[i]
    print(f'{country} has a population of {population} million people')

, , enumerate (, , zip ).

# OK
for i, country in enumerate(countries):
    population = populations[i]
    print(f'{country} has a population of {population} million people')

# Much Better
for country, population in zip(countries, populations):
    print(f'{country} has a population of {population} million people')	

9. +

, , Python, - , +.

, Python. , , + .

f-.

# Formatting with + operator
# Bad
name = input("Introduce Name: ")
print("Good Morning, " + name + "!")

# Good
name = input("Introduce Name: ")
print(f'Good Morning, {name}')	

f- , , .


10.

(, ) , .

# Bad
def my_function(i, my_list=[]):
    my_list.append(i)
    return my_list>>> my_function(1)
[1]
>>> my_function(2)
[1, 2]
>>> my_function(3)
[1, 2, 3]	

, my_function, my_list ( , , ).

, my_list None if .

# Good
def my_function(i, my_list=None):
    if my_list is None: 
        my_list = []
    my_list.append(i)
    return my_list>>> my_function(1)
[1]
>>> my_function(2)
[2]
>>> my_function(3)
[3]	

50% Merion Academy