34

Python, , .

   Python

, Python? , Python - :

- , .

Python -: , , , - . Quora, Pinterest Spotify Python -. , .


Python?

  • Python -.
  • Python .
  • Python . .
  • Python .
  • Python , .

Python?

  • Python (Windows, Mac, Linux, Raspberry Pi ..).
  • Python , .
  • Python , .
  • Python , , , . , .
  • Python , - .
  • Python .

  • Python - Python 3. Python 2, , , - .
  • Python , Thonny, Pycharm, Netbeans Eclipse, Python.

Python

  • Python .
  • Python , , .
  • Python ; , , . .

Python

Mac Python.

, Python Windows, Python cmd.exe :

C:\Users\Your Name>python --version	

, python Linux Mac, Linux Mac :

python --version

, python, -: https://www.python.org/

Python - , , Python .py , Python .

Python :

C:\Users\Your Name>python helloworld.py	

helloworld.py - python.

Python helloworld.py, .

print("Hello, World!")

. , , , :

C:\Users\Your Name>python helloworld.py	

:

Hello, World!

, Python.

Python

Python, . , Python .

Windows, Mac Linux :

C:\Users\Your Name>python

, python , py:

C:\Users\Your Name>py	

Python, hello world :

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!") 

"Hello, World!" :

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World! 

Python, , Python:

exit()	

1.

, . .

Python . , 1 one (). :

one = 1

? 1 one.

two = 2
some_number = 10000	
Python - , , , .

, . , two 2, some_number 10 000.

, (True False), , .

# booleans ( )
true_boolean = True
false_boolean = False
 
# string ()
my_name = "Leandro Tk"

# float (   )
book_price = 15.80	
#, Python :

2. :

if , . True, , if. :

if True:
  print("Hello Python If")

if 2 > 1:
  print("2 is greater than 1")	
, if . , Python . Python . , .

2 1, print. else , if .

print () .
if 1 > 2:
  print("1 is greater than 2")
else:
  print("1 is not greater than 2")	
Python ==, - .

1 2, else .

elif, else if:

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. /

Python . : while for.

while: True, . , 1 10.

num = 1

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

while . True, . , num 11, False.

, :

loop_condition = True

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

for: num , for . , while: 1 10.

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

? . 1 11- (10 - 10- ).


List: , , c

, 1 . , , 2. 3, 4, 5

, ? - .

List - , (, , ). , :

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

. my_integer.

, , : ? . , . 0. 1 .

, .

Array: [5][7][1][3][4]	
Index: [0][1][2][3][4]	

Python, :

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

, . , , . :

relatives_names = [
  "Alex",
  "Juliana",
  "Max",
  "Bruno",
  "Kaio"
]

print(relatives_names[4]) # Kaio

, . .

, List. , List ( ).

List - append. , :

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 . (, The Effective Engineer) .

. .


Dictionary: "-"

, List . , ? , , , .

Dictionary . Dictionary - -. :

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

key - , value. ? - . :

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "birthplace": "Brazil"
}

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 from %s" %(dictionary_tk["birthplace"])) # And by the way I'm from Brazil

dictionary_tk, , . .

, , ( ) , .

Dictionary - , . age :

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "birthplace": "Brazil"
  "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 from %s" %(dictionary_tk["birthplace"])) # And by the way I'm from Brazil

: age, : 24, .

, , . , , - , Dictionary. , :

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "birthplace": "Brazil"
}

dictionary_tk['age'] = 24

print(dictionary_tk) # {'birthplace': 'Brazil', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'}	

. , ?

Pythhon - (tuple), (set), .

:

Python, ( List) . Python, For. :

bookshelf = [
  "The Effective Engineer",
  "The 4 hours work week",
  "Zero to One",
  "Lean Startup",
  "Hooked"
]

for book in bookshelf:
    print(book)	

- bookshelf. (, ) , print. .

- () for, :

dictionary = { "some_key": "some_value" }

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

, . .

- items, . , dictionary.items()

dictionary = { "some_key": "some_value" }

for key, value in dictionary.items():
    print("%s --> %s" %(key, value))

# some_key --> some_value	

key value, . . :

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "birthplace": "Brazil",
  "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 birthplace is Brazil
# My age is 24	

, , . !


- , . , , . .

Python def:

def my_function():
  print("Hello from a function") 	

, , :

def my_function():
  print("Hello from a function")

my_function()	

. . , . fname. , , :

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus") 

. , 2 , 2 , . 1 3 , .

def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Emil", "Refsnes") 	

, , * .

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus") 

. , :

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden") #I am from Sweden
my_function() #I am from Norway

(, , , ), .

, , :

def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

, return:

def my_function(x):
  return 5 * x

print(my_function(3)) #15
print(my_function(5)) #25

Python

Python . , .

Python 3.6 Python 2.7. Python 3.6 input().

username = input("Enter username:")
print("Username is: " + username)

Python 2.7 raw_input().

username = raw_input("Enter username:")
print("Username is: " + username)	

Python , input (), , .


Python

try .

except .

finally try except.

, , Python .

try:

try:
  print(x)
except:
  print("An exception occurred") 	

try , x .

try , except . try .

, , .

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong") 	

, try NameError, - .

else, , , :

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong") 	

finally, , , try .

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished") 	

Python .

( ) , raise.

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero") 	

, , , .

x = "hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed") 	

:

, , . : .

, , . : , , , , .

, - .

- , . . . ( , , ..).


- Python

Python - : .

- , .

, , - . , , , . , , - .

, Python :

class Vehicle:
    pass	
pass -, . .

class - . , ?

- . , .

car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>

car - ( ) Vehicle.

, : , , . . , , :

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	
__init__,
self .

init. . , , . , Tesla Model S . , , , 250 /. :

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

+ + + 250 /.

. ? . . . :

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	

: number_of_wheels set_number_of_wheels. (getter) (setter). , .

Python , @property () . :

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	

, :

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 #     2
print(tesla_model_s.number_of_wheels) # 2

. . , , , 2 number_of_wheels. Python.

, , make_noise. :

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')

, VRRRRUUUUM.

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

:

- , . ( ).

. .

-, , - pubulic non-public.

Python .

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

first_name (public instance variable).

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

:

class Person:
    first_name = 'TK'	

first_name , , TK.

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

, . - , . ? : .

Person, first_name:

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

kaio first_name, . . , .

(non-public) , . : _ .

, , , Python . , Python: (, _spam) API ( , ).

:

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

_email? :

tk = Person('TK', 'tk@mail.com')
print(tk._email) # tk@mail.com

. - , API.

API - . .

, , . (emali update_email), :

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	

. :

tk = Person('TK', 'tk@mail.com')
print(tk.email()) # => tk@mail.com
# tk._email = 'new_tk@mail.com' --     API  
print(tk.email()) # => tk@mail.com
tk.update_email('new_tk@mail.com')
print(tk.email()) # => new_tk@mail.com	
  1. TK tk@mail.com
  2. email,
  3. API.
  4. !

:

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

    def show_age(self):
        return self._age	

:

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

- .

. Person, show_age _.

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

    def _show_age(self):
        return self._age	

:

tk = Person('TK', 25)
print(tk._show_age()) # => 25	
. . - , API.

, :

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

_get_age show_age. show_age ( ), _get_age ( show_age). : .

, .


:

: .

- () () .

Python.

. , - . , ElectricCar Car.

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	

Car :

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

. .

Python (parent) (child) . ElectricCar Car.

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

. - , ( Car). :

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	

Python

? , - , . , , .

, .py:

mymodule.py

def greeting(name):
  print("Hello, " + name) 

, import:

import mymodule

mymodule.greeting("Jonathan") #Hello, Jonathan 

, as:

import mymodule as mx

Python , .

import platform

x = platform.system()
print(x) 	

( ) . dir():

import platform

x = dir(platform)
print(x)	

:

['DEV_NULL', '_UNIXCONFDIR', 'WIN32_CLIENT_RELEASES', 'WIN32_SERVER_RELEASES', '__builtins__', '__cached__', '__copyright__', '__doc__', '__file__', '__loader__', '__name__', '__package __', '__spec__', '__version__', '_default_architecture', '_dist_try_harder', '_follow_symlinks', '_ironpython26_sys_version_parser', '_ironpython_sys_version_parser', '_java_getprop', '_libc_search', '_linux_distribution', '_lsb_release_version', '_mac_ver_xml', '_node', '_norm_version', '_perse_release_file', '_platform', '_platform_cache', '_pypy_sys_version_parser', '_release_filename', '_release_version', '_supported_dists', '_sys_version', '_sys_version_cache', '_sys_version_parser', '_syscmd_file', '_syscmd_uname', '_syscmd_ver', '_uname_cache', '_ver_output', 'architecture', 'collections', 'dist', 'java_ver', 'libc_ver', 'linux_distribution', 'mac_ver', 'machine', 'node', 'os', 'platform', 'popen', 'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation', 'python_revision', 'python_version', 'python_version_tuple', 're', 'release', 'subprocess', 'sys', 'system', 'system_aliases', 'uname', 'uname_result', 'version', 'warnings', 'win32_ver']

Python

- . Python , , .

Python open().

open() - .

() :

  • r - - . , ,
  • a - - , , .
  • w - - , , .
  • x - - , , .

, , .

  • t - - .
  • b - - (, )

, :

f = open("demofile.txt")

, :

f = open("demofile.txt", "rt")

r t , .

, , , Python:

, open(). open() , read() :

f = open("demofile.txt", "r")
print(f.read()) 	

, , :

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read()) 	

, readline():

f = open("demofile.txt", "r")
print(f.readline()) 	

. - , , , .

f = open("demofile.txt", "r")
print(f.readline())
f.close() 	

open():

  • a - -
  • w - -

"demofile2.txt" :

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#       :
f = open("demofile2.txt", "r")
print(f.read()) 

"demofile3.txt" :

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

Python, open() :

  • x - - , ,
  • a - - ,
  • w - - ,

myfile.txt:

f = open ("myfile.txt", "x")

: !

, os os.remove():

import os
os.remove("demofile.txt")	

, , , :

import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")	

, os.rmdir():

import os
os.rmdir("myfolder")	
.

Python PIP

PIP? PIP - Python , .

. Python 3.4 , PIP .

? , . - Python, .

, PIP

Python :

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version

PIP

PIP, : https://pypi.org/project/pip/

. PIP . Python :

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase	

camelcase

. camelcase import.

import camelcase

c = camelcase.CamelCase()

txt = "hello world"

print(c.hump(txt)) 	

https://pypi.org/.

uninstall, :

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip uninstall camelcase

PIP , :

Uninstalling camelcase-02.1:
  Would remove:
    c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase-0.2-py3.6.egg-info
    c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase\*
Proceed (y/n)?

y, .

list, , :

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip list	
Package         Version
-----------------------
camelcase       0.2
mysql-connector 2.1.6
pip             18.1
pymongo         3.6.1
setuptools      39.0.1	

!

Python:

  • Python
  • Python
  • Python
  • Python (while for)
  • Python
  • Python
  • Python
  • Python
  • Python
  • PIP
  • :
  • Dictionary
  • Python
  • :
  • :

PHP


50% Merion Academy