Python
 


   Python  ,    :        .

   Python 3.15  Windows,   macOS  Linux   .    : , , , , , ,   .  -  : , Git,   SQLite,      .       "",  ,  ,    , ,      , Telegram-       .           - -CRM  .     :  , ,  .    .





 

Python





Python:      

 



 





.    

   

     

  

  

 Python 3.15

 

 ,   

 ,   

 1.  

  

 Python

 Python 3.15

 

 

 

    



 2.    







 

  



  :   



 3. 

:  if

: else



 : elif

 : and, or, not

   

 

   

  : match

  : 



 4. 

 while

 for   range

  : break  continue

 

 " "



 5.   

  





 

  

 

 



  :   



 6.   

  

 

 



frozendict -  Python 3.15

  :  



 7.   

 

  

  

 



 : ,    

  :  



 8. 

  

  

  

 

 

  

   

 : lambda

  :   



 9.   

  

  

 : try  except

 else  finally

 





  :   



 10. 

  

  UTF-8  

  :  pathlib

CSV:   

JSON:   

 : TXT, CSV  JSON



 11.   

  import



 

   pip

 

uv:  



 12.   

  

,   

 



 : dataclasses

  

  :  



 13. 

  

  assert

pytest

  

  

   



 14.    Git

   

 

ruff:   

 

Git:    



GitHub   



 15.   SQLite

,   

SQL  

 sqlite3

  



 16.   API

  -

 requests

JSON  API

 -   

POST:  

     



 17.    

  -   

 

  

     

    



 18. :   

 

 

  

  

 

 

 - 

  



 19. : ,   

   

: ,   

   

,  

   

  



 20.  

  

 

 



   tkinter

 ""

   

 ""

  



 21.   

  

 

  

   

    .exe

  



 22.  :    

  

  

 

   

  

  



  



 23.  :   

 

   pandas

    

 matplotlib

  Excel



  



 24.   : -

  

  

   

  Telegram

 

 

  

  



 25. Telegram-   :  

  

    Telegram

  BotFather

:   

 

 

  Telegram

  

  



 26. Telegram-   :   

  

  

 

  

  

:   

 :   

 

 

  

  



 27.   :  

  

  

 

  : --



 

: 

 

  



 28.   : ,   

  

      

 

  

  

  



  

  



 29.    

  

     

:  

  

 

 

 

 

  

   

  



 30. -CRM:   

  





 







  



 31. -CRM: ,   

  

  

  0.3



    Word

  Excel

 

  0.3



  0.3

  



 32.     

  

   

  1.0

  

 .exe

  

README, requirements.txt  .gitignore

  1.0

 

   



 

  



 .    " "

 1.  

 2.    

 3. 

 4. 

 5.   

 6.   

 7.   

 8. 

 9.   

 10. 

 11.   

 12.   

 13. 

 14.    Git

 15.   SQLite

 16.   API

 17.    

 .   Python

   ( 1, 11)

, ,    ( 2, 3)

   ( 2)

  ( 2, 7)

   ( 3)

 ( 3)

 ( 4, 5)

 ( 7)

   ( 5)

   ( 6)

 ( 8)

   ( 9)

 ( 10)

    ( 11)

 ( 12)

 ( 13)

SQLite  SQL ( 15)

  API ( 16)

Git ( 14)

  Python 3.15

 .       

    

,    

   

  

   Windows

   




.    



     ,     .    "7777".       ,    .  ,  ,  :   ,    ,    .

   ,   :   ,     .     ,      , ,    ,  ,    .        Python ( "",     "",    ).




   



 ,    .   ,   ,         .  ,    :     ,     .

        14 . -    , -    , -       ,     .       :  ,  ,   .

    - Windows:      .    macOS  Linux,  . Python  ,   (,   ,   )    "   macOS  Linux".




     



 ,     :

 ""  , ,    ;

   -  ;

       ,      Windows ( .exe);

 :    ,   , ,    Excel;

-:              Telegram,      ;

Telegram-,     ,        ;

  : ,   ,        ;

-CRM  : , , ,     Word,   Excel   .

  .        :             .         .




  



    .

 1.  ( 1-12).  Python,  , , , , , , , , , ,   .  .        :    .

 2.   ( 13-17). ,  ,    Git,   SQLite,        .     ,     .

 3.  ( 18-28).     , ,  -CRM.      .      ,      .      ,      ,   .

 4.   ( 29-32). -CRM    :   "  ?"   ,    .

    :   ,   Python     .




  



      : , ,  , .    .      (  listing, ""),       . ,     .    ,   :         .

 0.1. barsik.py

name = input("  ? ")



print(f" , {name}!   .")



print(" .        .")

 0.1  ",  ".   5    5.1, 5.2   .    ,     :

  ? 



 , !   .



 .        .

  .   ,    ""   Enter.   ,   ,    ,   ,  ,       .          Python 3.15,   .

       :      Python. ,   ,      >>>,   Python    :

>>> 2 + 2



4



>>> "" * 3



''

        ,    .




 " "


  1-17     .   :

 .   barsik.py ,        .

      ,  "  4.3".        .    :   ,     ,      .   ,   .        ,     .

       .     ,  ,      ,   .     ,  .




-


  18-32    :    -   .          "  "  ,    .     ,    .







    "": -    .     ,      ,   .







       :

   macOS  Linux.  ,      .

  Python 3.15.      ,   .

 .   ,     .

.   ,    ,    .







      .      ,       , :  (variable),  (function),  (list).   ,            : Python   -.




 Python 3.15



Python 3.15  9  2026 .       ,        .

:     Python          UTF-8   .   Windows        "",       .      .

: Python 3.15    .         push  append,     .    -   1  5.

      ,      .    (,  frozendict   6)    3.15.     :    ,   .




 



      " .zip".  -   : 01, 02   .       .      :   ,   ,  .

 ,       .         .  ,        :  ,     ,     .     :   -  .

   13   .           requirements.txt,    ,    11.




 ,   



  .    ,   " ",    .             ,     .   ,    :

1.           ,   .   ,     1  9.

2.               : , , , .

3.         :       .

4.          .  , -     .

5.       ,   :      ,    17.

6.         .   :       ,      .




 ,   



 ,  : -    ,      .     .   ,    :  ,  ,    ,  .        ,       .

  .  -        ,  .     ,   ,     .        ,    ,  ,   .

       .    .




 1.  



     Python,        .      ,      :     .  .    ,  Python   ,   .




  



   . "     ,      ,  ,      ,    ".   ,    .    :     .

  .  ,   "  "  " ".    ,  ,  .   ,     .     ,     ,  :    .       " ",   "" ,          ,    .

  -   .   ,       .  ,      :  ,      ,   ,     .

     (programming language).        .    ,   ,     :      ,     ,    .

Python -    .   Python   (interpreter):  ,          ,   .   " Python",     .

  1.1.          ,      .     .     :      ? ,   ,    ?

  1.2.      ,       . :  ,  ,  ,   .




 Python



  .       Python?

-,       .  ,     ", !",   Java:

public class Main {



public static void main(String[] args) {



System.out.println(", !");



}



}

  Python:

print(", !")

   ,    ,     "   ".

-, Python   .      Telegram-,     ,  ,    ,  ,   .           ,          .

-, Python     Windows, macOS  Linux.       (library) -   . -       ,      Excel,       .

 ,  Python    .     C++   ,        .             .       ,  ,    Python   .




 Python 3.15



Python    Windows,   .        .




  Windows


   Python  Windows     Python install manager (  Python).    Python,           .   .

1.          python.org/downloads/windows.      "Latest Python install manager" (  ).       "Installer (MSIX)".  :   Microsoft Store  "Python install manager"   "".   .

2.           "Install" ().

3.       . ٸ      ""   "" ( Windows 10    "Windows PowerShell").  ,     .

4.          Enter:

py install 3.15

    Python 3.15.          (,        PATH      ), :  y   Enter.

5.       ,     ,   :

python --version

Python 3.15.1

    ,   3.15, Python .       :    ,      .      py list.

 .   Python  Microsoft Store   ,   "python"   (    cmd: "python      ").      :       .   ,  "",  "   "  ,     "Python (default)"  "Python install manager" .    ,     .

.     Python 3.15      "Windows installer (64-bit)".    ,        "Add python.exe to PATH".    python     .   3.16    ,       .

   macOS  Linux.  macOS    macOS   python.org/downloads/macos ( .pkg)    .  -   "": python3 --version.  Linux Python   ,    .    3.15   uv:      11,    -  : curl -LsSf https://astral.sh/uv/install.sh | sh  uv python install 3.15.  Python   python3.15. ,     python,  macOS  python3,   Linux - python3.15.




 



Python ,    .        Enter:

python

           >>>.    (interactive mode),      REPL (  read-eval-print loop: ", , , "). Python  ,      . :

>>> 2 + 2



4



>>> 7 * 8



56



>>> 100 / 3



33.333333333333336



>>> 2 ** 10



1024



>>> (1500 + 230) * 2



3460

  ,  .  *  , / - ,  ** -   : 2 ** 10 -     .     .

 .   Python   :

>>> ""



''



>>> print("")







>>> "" + "  "



'  '



>>> "" * 3



''

      ?    ,     :   ,    ,      .  print   ,  ,    .  +    ,         .  :    .

    ,  exit   Enter.    :  Windows Ctrl+Z,  Enter;  macOS  Linux Ctrl+D.

     : ,   ,  -,  .  ,     ,   .        .

  1.3.    ,          (   365 ).

  1.4.    "" + "!"  "" * 5? ,    Enter.    "" + 5  ,   Python. , -,   ?




 



  Python        .py.  ,      .     :     ,   ,       .




Visual Studio Code


      Visual Studio Code ( VS Code).   ,    ,  .

1.       VS Code   code.visualstudio.com  .   "  "   "  PATH"     "   Code":  .

2.       VS Code.      .       ( "",   Ctrl+Shift+X),    Python    Python  Microsoft.      .

3.          ,      "Russian Language Pack for Visual Studio Code",    .

    .   C:\pyprojects:  ,    C:,          " ? ".  VS Code    " ?  "   .   ,        ,  "":   .

.      : " ?  ?   " ( Windows 10:  "",  "  ").     hello.py.txt,    hello.py,  Python   .




IDLE


  VS Code   ,   .   Python    IDLE.     ""   IDLE.    ,    "File ? New File"    .    F5,     .    IDLE  ,         VS Code.

   macOS  Linux. VS Code     ,     .        : ~/pyprojects.




 



 ,   ,         ", !".  VS Code  " ?  ",   hello.py    .

 1.1. hello.py

print(", !")

  (Ctrl+S).     . :  VS Code         "Run Python File" (  Python). :   ( VS Code   " ?  ")    python   :

python hello.py

       ,      cd C:\pyprojects.       ,   :

, !

,  !  :   ,    .

,   . print -   (function),    ,  - .  print    ,     .     :    Python "".   -  (string),     .   ,   ,      .

      ,   : print(', !')    .      . ,       .




 


     . Python    ,  .

 1.2. about_cat.py

print(": .")



print(":", 4, "")



print(" : ,   .")



print()



print("     :", 2 * 7)

: .



: 4 



 : ,   .





     : 14

   .     print     : ,    .         .    print()      :     .     Python   2 * 7     .   2 * 7 ,    ,  .

: print("2 * 7")  2 * 7,  print(2 * 7)  14.   .




  


 print   ,   .   ,  .

 1.3. yolka.py

print("    *")



print("   ***")



print("  *****")



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



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



print("   | |")



print()



print(" !")

*



***



*****



*******



*********



| |





 !

      -  ,   .  :      print  .       Python   ,      .




  


   ,     ? ,  : "!".   print(" : "!""), Python ,      ,  .  :    ,    .

 1.4. quotes.py

print(' : "!"')



print(" : '  .'")

 : "!"



 : '  .'

    ,     .

  1.5.   about_me.py,       ,    .

  1.6.   ,   .  ,  .

  1.7.       24     168 ,   168   Python:  ,    .

  1.8.    : "    !"   .




    



  .    :  ,  ,   .   ,     .         ,     ,   ,      .

  .

 1.5. error_name.py

print("")



pirnt(", !")



print("")

   : pirnt  print. :





Traceback (most recent call last):



File "C:\pyprojects\error_name.py", line 2, in <module>



pirnt(", !")



^^^^^



NameError: name 'pirnt' is not defined. Did you mean: 'print'?

   ,    .     (traceback):    ,   ,   .

Traceback (most recent call last): - : " (   )".    .

File "C:\pyprojects\error_name.py", line 2, in <module> -  :    ,  .  in <module>  "   ",    - .

 Python         ^ ,    .

  -  :    . NameError -  . name 'pirnt' is not defined - " pirnt  ",   Python    .   : Did you mean: 'print'? - ",     print?".

   :  ""  . Python   ,     .      .

  :    .  ,  .     ,   .




 


   ,     . ,   .

 1.6. error_bracket.py

print("")



print(", !"



print("")

File "C:\pyprojects\error_bracket.py", line 2



print(", !"



^



SyntaxError: '(' was never closed

SyntaxError -  ,   . : '(' was never closed - " '('     ".  ^      .

    :     "".   Python      ,    .  ,    .    :      ,       .

   .

 1.7. error_quote.py

print(", !)

File "C:\pyprojects\error_quote.py", line 1



print(", !)



^



SyntaxError: unterminated string literal (detected at line 1)

unterminated string literal - " ": Python     ,       .   :    1.

   -     .

 1.8. error_indent.py

print("")



print(", !")

File "C:\pyprojects\error_indent.py", line 2



print(", !")



IndentationError: unexpected indent

IndentationError: unexpected indent - " :  ".  Python     -   ,    .         .   ,     3.




   


   :

 1.9. error_no_quotes.py

print()

Traceback (most recent call last):



File "C:\pyprojects\error_no_quotes.py", line 1, in <module>



print()



^^^^^^



NameError: name '' is not defined

  Python    ,   - (  ,    ),   ,     .

      ,    print  :

 1.10. error_old_print.py

print ""

File "C:\pyprojects\error_old_print.py", line 1



print ""



^^^^^^^^^^^^^^



SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

   Python 2,    . Python      : Did you mean print(...)? - ",     print(...)?".

  Python 3.15. Python    "Did you mean",    3.15    . ,           JavaScript  Java, Python    .       5  7.




  


      .  ,    :

Error - ; Syntax - ,  ;

not defined -  , ;

was never closed -    ;

unterminated - ;

unexpected - ;

invalid - , ;

expected - ;

Did you mean - ,    .

  ,           .  ,         .

  1.9.   hello.py  :   ,   ,  Print   .      .     ?

  1.10.     .  ,   ,         Python.

print(" :")



print(")



prnt("")



print("  ")








 -    . Python     ,  ;   .

Python 3.15  Windows   Python install manager;   -  python --version  .

  (>>>)    ,      .py   : VS Code  IDLE.

 print()      .    ,     .

      ,        .

   :   ,  ,   -  .  "Did you mean"    .




 2.    



       .   ,    .     :  ,  ,    -   .         , ,        .








     .     ,    : "", "", " 2025".     ,    .  (variable)  Python -   : ,    .

 2.1. variables.py

cat_name = ""



cat_age = 4



print(cat_name, "   ", cat_age, "")





cat_age = 5



print("    ", cat_age)

     4 



     5

 cat_name = ""  : "  cat_name   ".  =  Python   "",   (assignment):  ,  ,    .      : print(cat_name)  .

   .     cat_age    4   5.   ,   print   5.

 = -  ,   ,  Python   ,        :

>>> sausages = 3



>>> sausages = sausages + 1



>>> sausages



4

Python    :    sausages (3),  1   4.    sausages  .     ,    .

    :       ,  Python   .       ,   print.




  


   :

   ,     _;

     ;

   ;

    : cat, Cat  CAT -   ;

    (keywords) Python,   if, for, class, True.   35,      ,    .

  ,   :

>>> 2cats = 2



File "<python-input-0>", line 1



2cats = 2



^



SyntaxError: invalid decimal literal



>>> my cat = ""



File "<python-input-1>", line 1



my cat = ""



^^^



SyntaxError: invalid syntax



>>> class = "5"



File "<python-input-2>", line 1



class = "5"



^



SyntaxError: invalid syntax

    ,      Python.      ,    : cat_name, price_per_kg, total_sum.    snake_case, " ":        .

Python    :   = "" .    .      ,         .     ,   : ,   .

  :   ,   .  a = 45  tomato_price = 45.      ,   a,   tomato_price  .      .

  2.1.     Python ,   : price, 2price, price2, total price, total_price, for, _secret, ?     .

  2.2.   breakfast, lunch  dinner           print.








 Python    .   (integer,  int)   : 4, -15, 1000.   (floating point,  float, "   ")   ,    : 3.5, 0.25, -12.0.      type:

>>> type(4)



<class 'int'>



>>> type(4.5)



<class 'float'>



>>> type("")



<class 'str'>

int -  , float - , str ( string) - .  (type)  ,     :    ,     .







    :















+

7 + 2

9





-

7 - 2

5





*

7 * 2

14





/

7 / 2

3.5



   

//

7 // 2

3



  

%

7 % 2

1



  

**

7 ** 2

49



    :  ,    ,    .   .     .

 2.2. seeds.py

tomato_price = 45



cucumber_price = 38.5



tomato_packs = 3



cucumber_packs = 2





total = tomato_price * tomato_packs + cucumber_price * cucumber_packs



print(":", total, ".")



print("  1000 :", 1000 - total, ".")

: 212.0 .



  1000 : 788.0 .

   38.5 ,   .         ,    .   212.0,   212.

    :   /    ,    .

>>> 10 / 2



5.0



>>> 10 // 2



5



>>> 2 ** 100



1267650600228229401496703205376



>>> 1_000_000 * 3



3000000

2 ** 100 -     ,  Python   .    Python    ,    .     1_000_000     ,      . Python   .




   


 //  %  ,   .    .    17   5 ,    .

 2.3. sausages.py

sausages = 17



cats = 5





per_cat = sausages // cats



left = sausages % cats





print(" :", per_cat)



print(":", left)



print(",  ,  .")

 : 3



: 2



,  ,  .

17 // 5 -   5    17,   3. 17 % 5 -  ,   2.     ,    (n % 2  0  ),      ,    .      .




 


  total = total + 100   ,     : total += 100.    -=, *=  /=.

>>> money = 1000



>>> money -= 212



>>> money



788



>>> money *= 2



>>> money



1576




   


  ,    :

>>> 0.1 + 0.2



0.30000000000000004



>>> round(0.1 + 0.2, 2)



0.3



>>> round(7.456, 1)



7.5

   Python.       ,      ,  0.1,    ,  1/3   (0.3333...).       .      :    round,         .      Python    Decimal,   -   11.

  2.3.     37       .      9    .    ?  . :     -,      .

  2.4.   135 .      "2  15 ",  //  %.

  2.5.     0.1 + 0.1 + 0.1  0.1 * 3.     ?     .








    :  (string) -    .     +    *,   len   ,      :

>>> greeting = ", " + ""



>>> greeting



', '



>>> len(greeting)



14



>>> "-" * 20



'--------------------'

    ,     : ", " -  14 .




 


        print?      ,       \.  :

\n -   (n  new line, " ");

\t - ,  ;

\"  \' - ,    ;

\\ -    .

 2.4. special_chars.py

print(" :\n- \n- \n-   ")



print("\t")



print("\t450")



print(" : \"!\"")



print("    C:\\pyprojects")

 :



- 



- 



-   



   



     450



 : "!"



    C:\pyprojects

 .     Windows     ,   .   "C:\new\table.txt" Python  \n ( )  \t (),   .  :   ("C:\\new\\table.txt"),    ("C:/new/table.txt", Python  Windows  )      r: r"C:\new\table.txt".  r ( raw, "")  Python    .   10         .




 


       ,      .      :

 2.5. postcard.py

postcard = """ !



   !



 ,  



    .



     """





print(postcard)

 !



   !



 ,  



    .



     




f-


     :    .   ,          str,    .  : " " + str(cat_age) + " ".   f- (f-strings).      f,         :

 2.6. fstrings.py

cat_name = ""



cat_age = 4



weight = 5.678





print(f"  {cat_name},  {cat_age} .")



print(f"    {cat_age + 1}.")



print(f": {weight} ,  : {weight:.1f} .")



print(f"   : {30 * 65.5:.2f} .")

  ,  4 .



    5.



: 5.678 ,  : 5.7 .



   : 1965.00 .

        ,   : {cat_age + 1}.      .  :.1f  "       ", :.2f -  .    :.2f   : "1965.00 ."  ,  "1965.0 .".   ,      7.

      .         =, Python   ,  :

>>> cat_age = 4



>>> print(f"{cat_age=}")



cat_age=4

  2.6.     ,      .  f-   ": 1.5   180 . = 270.00 .".

  2.7.   print      " - "    ,  \n  \t.

  2.8.  f-    : "   5 ".  len    .




 



   :     , True ()  False ().    (boolean,  bool,     ).   ,   - :

>>> 5 > 3



True



>>> 2 + 2 == 5



False



>>> "" == ""



False



>>> is_hungry = True



>>> type(is_hungry)



<class 'bool'>

  == -  : "  ?".      =,  . ""     ""    Python  ,    False.

      ,     :   , ,   .

  2.9.   Python,  : 10 / 2 == 5, 7 // 2 == 3.5, "" * 2 == "", len("") == 3.     .




  



   .  input ()    ,       Enter.     ,      .

 2.7. greeting.py

name = input("  ? ")



city = input("   ? ")



print(f", {name}!     {city}?")

  ? 



   ? 



, !     ?

     "  ? ".       :   ?.




 -  


 ,      :

 2.8. next_year_bad.py

age = input("  ? ")



print(f"    {age + 1}")

  ? 25



Traceback (most recent call last):



File "C:\pyprojects\next_year_bad.py", line 2, in <module>



print(f"    {age + 1}")



~~~~^~~



TypeError: can only concatenate str (not "int") to str

 TypeError:  . "      (  int)".  input   ,     .  Python "25" -   ,   ,     .       .

    ,   int ( )  float ( ):

 2.9. next_year.py

age = int(input("  ? "))



print(f"    {age + 1}")

  ? 25



    26

     ,  . Python   : input      "25".  : int   "25"   25.      age.

    :  str    .      (type conversion).

>>> int("42") + 1



43



>>> float("3.5") * 2



7.0



>>> str(42) + "1"



'421'



>>> float("3,5")



Traceback (most recent call last):



File "<python-input-3>", line 1, in <module>



float("3,5")



~~~~~^^^^^^^



ValueError: could not convert string to float: '3,5'

  -   ,      .  Python    ,   "3,5"  float  .      ,     : "   ".

 ,       ?

  ?  



Traceback (most recent call last):



File "C:\pyprojects\next_year.py", line 1, in <module>



age = int(input("  ? "))



~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^



ValueError: invalid literal for int() with base 10: ' '

ValueError -  : "   int()   10".  " "    .          .   9     ,   .




 


  .  ,        15  ,    9,    -  4. ,   -  24-,     4    .

 2.10. cat_years.py

#      



# (   ,   )



name = input("  ? ")



cat_age = int(input("  ? "))





human_age = 24 + (cat_age - 2) * 4



print(f"- {name}  {human_age}-.")

  ? 



  ? 4



-   32-.

  -  32- .   :   ,   ,       .        .         ,     .

  2.10.  ,         ( )         .

  2.11.  -:        ,  ,    .    ,     .

  2.12.   next_year.py ,      ,    ",  10    35".








  2.10       #.   (comments): ,    #   , Python .    :       .

       :

 2.11. comments.py

price = 180  #    , .



weight = 1.5  #  , 





#  10%   



total = price * weight * 0.9



print(f" : {total:.2f} .")



# print("   :  ")

 : 243.00 .

   :    #,  Python   .     ,   .  VS Code     Ctrl+/ -     #    .

  ,  - ,    .  #   0.9 :    .  #  10%    ,    0.9.        ,    .

  2.13.      2.10     :        .




  :   



 ,       .          ,        ,   .

 2.12. dacha_trip.py

#      





distance = float(input("     , : "))



consumption = float(input(" ,   100 : "))



fuel_price = float(input("  , .: "))



people = int(input("  ? "))





#   ,   



liters = distance * 2 * consumption / 100



cost = liters * fuel_price



per_person = cost / people





print()



print(f"     : {liters:.1f} ")



print(f" : {cost:.2f} .")



print(f"   {people}: {per_person:.2f} .")



print(f"  : {people >= 1}")

     , : 68



 ,   100 : 8.5



  , .: 62.4



  ? 3





     : 11.6 



 : 721.34 .



   3: 240.45 .



  : True

  .   -  input,      : ,     ,  float,     ,  int.   ,       .    :     2.   f-  :      ,   .

  - ,   :  people >= 1   ,  f-    True.       ,   .   ,     ,       :          .         .

  2.14.  :               (  )    .








 - ,   .  =  ,   ;    .

       (snake_case)   ,   ,  .

 :   int,  float ( !),  str    bool   True  False.    type.

: + - * /,   //,  %,  **.  /    ;       ,    round.

f-    : f" {age} ",   :.2f     .

input   .      int  float,     str.

   #  ,   .




 3. 



         :   ,  .     .   ,  .     ,   .      , ,  .       .




:  if



    .

 3.1. umbrella.py

answer = input("  ? (/) ")



if answer == "":



print(" !")



print("  ,    .")



print(" !")

  ,   :

  ? (/) 



 !



  ,    .



 !

  ? (/) 



 !

  .  if  "".     (condition): answer == "",   "   ".     .    : "  ,   ,   ".

       .       (block).    (True), Python   .   (False),      .  print(" !")   ,        .

   Python :  ,   "" .           begin  end,   Python - .      ,      1, -  ,   .

.   Python -   . VS Code   ,    Enter    ,   Tab      .          :    ,  Python  .

   , Python   :

 3.2. error_no_indent.py

answer = ""



if answer == "":



print(" !")

File "C:\pyprojects\error_no_indent.py", line 3



print(" !")



^^^^^



IndentationError: expected an indented block after 'if' statement on line 2

"      if   2". Python    ,      .

  3.1.  ,      ,    ,   .          .




: else



   ,   ,  ,  .      else ("").

 3.3. even_odd.py

number = int(input("  : "))



if number % 2 == 0:



print(f"{number} -  .")



else:



print(f"{number} -  .")

  : 14



14 -  .

  : 7



7 -  .

       2:        2  . else      ,   if,    .      :  ,  .      -  .

  3.2.   ,   ,     3  .








 -   (expression),   True  False.    .    :













==



5 == 5

True



!=

 

5 != 5

False



<



3 < 5

True



>



3 > 5

False



<=

  

5 <= 5

True



>=

  

4 >= 5

False



    ,   .    , ,      : ,     ,  .

>>> "" < ""



True



>>> "" == ""



False



>>> "" < ""



True



>>> "10" > "9"



False



>>> 10 > 9



True

     .  10  9   ,  10 .   "10"  "9"  ,    :   "1"  "9",   Python   .   :        int,        .

  :        ,  "" ,  "".      ,  .     ,    7.

 Python    ,   :

>>> age = 35



>>> 18 <= age < 65



True



>>> 0 < age < 18



False

18 <= age < 65  "  18    65".       ,   Python   .

  3.3.   Python,  : "" == " ", "" < "", 3 < 5 < 4, "100" < "25".  .

  3.4.  ,    ,    123,  " , !",   " . ,  ?".




 : elif



   ,    elif (  else if, " ").         .

 3.4. discount.py

total = float(input(" , .: "))





if total >= 5000:



discount = 10



elif total >= 3000:



discount = 5



elif total >= 1000:



discount = 2



else:



discount = 0





to_pay = total * (100 - discount) / 100



print(f": {discount}%")



print(f" : {to_pay:.2f} .")

 , .: 3500



: 5%



 : 3325.00 .

 , .: 740



: 0%



 : 740.00 .

Python          ,   .     .   3500   (>= 5000) ,  (>= 3000) , ,  5%,   .      ,   else.  :       ,     .

   . ,  ,    :

 3.5. discount_bad.py

total = 7000



if total >= 1000:



discount = 2



elif total >= 3000:



discount = 5



elif total >= 5000:



discount = 10



else:



discount = 0



print(f": {discount}%")

: 2%

  7000    2%,   10%.  7000  1000,   ,      .   , Python   ,   .     (logic errors)  :     .    elif   "  "     .

          2:     .

 3.6. cat_years2.py

name = input("  ? ")



cat_age = int(input("   ? "))





if cat_age <= 0:



print("  .   ,  -.")



elif cat_age == 1:



print(f"{name} -  15- .")



elif cat_age == 2:



print(f"{name} -  24-.")



else:



human_age = 24 + (cat_age - 2) * 4



print(f"- {name}  {human_age}-.")

  ? 



   ? 1



 -  15- .

  ? 



   ? 4



-   32-.

  3.5.  ,      ( 0  100)  : 90   - "5",  75 - "4",  60 - "3",  60 - "2".

  3.6.   - ,    4,     100. : ,    400,   ( 2000   ,  1900 - ).      elif,          .




 : and, or, not



      . "  ,       ".       (logical operators):

and ("") - ,    ;

or ("") - ,     ;

not ("") -  : not True  False.

 3.7. garden.py

temperature = int(input("   ? "))



rain = input(" ? (/) ")



frost = input("   ? (/) ")





if temperature > 25 and rain != "":



print("  :   .")





if frost == "" or temperature < 5:



print(":   .")





if not (rain == "" or frost == ""):



print("   .     .")

   ? 28



 ? (/) 



   ? (/) 



  :   .



   .     .

   ? 4



 ? (/) 



   ? (/) 



:   .

   if,     elif:     ,     .  if/elif/else     ,    if     .

    : not (rain == "" or frost == "").   not      .  :    ,  .    ,     .




 Python  


      ,    . Python ,     ,   :    - ,   - .

>>> bool(0)



False



>>> bool(42)



True



>>> bool("")



False



>>> bool("0")



True



>>> bool("")



True

  0    "".   "0"   (   ),  .      "":  Python    ,   .

  ,  ,     -:

 3.8. empty_name.py

name = input("   ? ")



if not name:



print("   .   ?")



else:



print(f"{name} -  !")

   ?



   .   ?

not name ,   :    Enter.  if not name: ,  if name == "":,    Python   .

  3.7.       3.6    and, or  not.    2024, 2025, 1900  2000.

  3.8.    ,     3000         .  ,       ,  ,   .




   



        ,    .

:  =   ==.      ,   :

 3.9. error_assign_in_if.py

answer = input(" ? ")



if answer = "":



print(" !")

File "C:\pyprojects\error_assign_in_if.py", line 2



if answer = "":



^^^^^^^^^^^^^



SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Python    ,   : " ,     '=='  ':='  '='?".   ==.    :=    ,     .

  ,   Python   . ,       ,       ,    : "    ".

 3.10. or_bug.py

answer = input(" ? ")



if answer == "" or "":



print(" !")



else:



print("  ,  .")

 ? 



 !

  "",     .   ,  Python  .    (answer == "") or (""):  ,    "".   False,   ""  ,  ,      . False or "" - ,      .

     :

 3.11. or_fixed.py

answer = input(" ? ")



if answer == "" or answer == "":



print(" !")



else:



print("  ,  .")

 ? 



  ,  .

  7    :         .    "",  "",   "",    Caps Lock.

  3.9.    :   7  ,   .    .

number = int(input(" : "))



if number > 0 or number == 0 or "":



print(" .")



if number < 0 or "":



print(" .")




 



  if    if.     (nested).    :       .

 3.12. cinema.py

age = int(input("  ? "))





if age >= 16:



print(",  !")



else:



with_parent = input("  ? (/) ")



if with_parent == "":



print("   .")



else:



print(",  16+.   .")

  ? 14



  ? (/) 



   .

  ? 12



  ? (/) 



,  16+.   .

      ,   16:     .  ,     :          .

    :     ,  ,  else   if .     elif   ,  .   ,           ,    (bugs,    ).

  3.10.  ,      .   500 .   7  ,   18   50%,   65   30%.    18  64 ,  ,   ,     20%.




   



,       . ,   :     .      if  else,   :

 3.13. cat_diet.py

weight = float(input("  , ? "))



advice = "  " if weight > 6 else "  "



print(f"  {weight} : {advice}.")

  , ? 6.5



  6.5 :   .

  , ? 5.2



  5.2 :   .

 1 if  else 2    (conditional expression).    -: "  ,    ,    ".       ,           f-.

     "  ".         ,  if, elif  else  .

  3.11.   even_odd.py ( 3.3) ,   ""  ""   ,  print     .




  : match



       ,  elif  : if drink == "", elif drink == "", elif drink == ""...     Python   match ()   case ().

 3.14. coffee_machine.py

drink = input("  ? ")





match drink:



case "":



print("  , 60 .")



case "" | "":



print("  , 120 .")



case "":



print("  , 90 .")



case _:



print(" .  , ,   .")

  ? 



  , 120 .

  ? 



 .  , ,   .

match drink:  "  drink  ". Python       (pattern)   case     .   |  "": case "" | ""    .  _ ()    ,   else,    .

 match       elif.    :    .    ,      .  command.split()      (   -   7),  match ,      .

 3.15. shopping_commands.py

command = input(": ")





match command.split():



case [""]:



print("  .")



case ["", item]:



print(f"  : {item}")



case ["", count, item]:



print(f"  : {count} {item}")



case [""] | [""]:



print(" !")



case _:



print(" . : , , .")

:  



  : 

:  2 



  : 2 

:  



 . : , , .

 ["", item] ,            "".  ,     ,    item.  ["", count, item] -   .    " "      ,  _.

 match            ,      .      match  :  "" ( 19)  ,      ,     ( 22) -   .

  3.12.  ,      ( 1  7)    .  6  7    "!".  match,      _.

  3.13.   3.15   <>,   "  : <>",   ,    .




  : 



 ,        :   .    ,        .

 3.16. cat_quiz.py

print(":     ?")



score = 0





answer = input("1.      : 5, 10  15? ")



if answer == "15":



print("!   12-16   .")



score += 1



else:



print(",  15.  -   .")





answer = input("2.     ? (/) ")



if answer == "" or answer == "":



print("!     .")



score += 1



else:



print(",    .  -  .")





answer = input("3.      ? (/) ")



if answer == "" or answer == "":



print("!     ,   .")



score += 1



else:



print(",        .")





print()



print(f" : {score}  3.")



match score:



case 3:



print("   !")



case 2:



print("!   .")



case _:



print("   .   .")

:     ?



1.      : 5, 10  15? 15



!   12-16   .



2.     ? (/) 



,    .  -  .



3.      ? (/) 



!     ,   .





 : 2  3.



!   .

   : ,  ,   ,     .  score  ,    match     .   case     ,   .

  ,      .    :     ,  ,          .     ,    :  ( 4),  ( 5)   ( 8)          .

  3.14.        : "" -  4  , "" -  3,  - "   ".








if :    ,    .  -        .

else:    ,   ,  elif   .     ,    .

: == != < > <= >=;    , ,   .  10  9,   "10"   "9".

  and, or, not  ;    .

     ,   - : if not name: ,    .  answer == "" or ""  :      .

         : "" if n % 2 == 0 else "".

  ,           .

match    : case "":, case "" | "":, case _:,    ["", item]    .




 4. 



  .      ,          ",   ".        .        (loops).         Python,          .




 while



 while   "".  while   ,   .      .

 4.1. countdown.py

seconds = 5



while seconds > 0:



print(seconds)



seconds -= 1



print("  !")

5



4



3



2



1



  !

   if:  while, ,     .  if    ,  while      .  :

1.        seconds > 0.  seconds  5,  .

2.       :  5,  seconds  4.

3.         1.

     (iteration).  seconds   ,  ,  ,  Python     : .

 seconds -= 1   .  ,  seconds   ,    ,     ,    .     (infinite loop).     ,  :       Ctrl+C. Python     KeyboardInterrupt - "  ".

 .     ,        .   ""          ,   ,    while     .




  


 while ,   ,   . ,      .

 4.2. password_attempts.py

secret = "123"



attempts = 0



password = ""





while password != secret and attempts < 3:



password = input(": ")



attempts += 1





if password == secret:



print(" !")



else:



print("  .  .")

: 



: 123



: 123



 !

 ,        .    password   :     ,        .       ,      .




  


 ,     .      25 000 .     3000    ,    1%    ,     .     ?

 4.3. bike_savings.py

goal = 25000



monthly = 3000



savings = 0



months = 0





while savings < goal:



savings = savings * 1.01 + monthly



months += 1



print(f" {months}:   {savings:.2f} .")





print(f" {months} .   !")

 1:   3000.00 .



 2:   6030.00 .



 3:   9090.30 .



 4:   12181.20 .



 5:   15303.02 .



 6:   18456.05 .



 7:   21640.61 .



 8:   24857.01 .



 9:   28105.58 .



 9 .   !

  ,         .    ,  ,  ,         .       ,   .

  4.1.     10  1,     "  !"  .      .

  4.2.  ,         ,     0.    .

  4.3.    ,         .    1  ,    - 500  .       ?




 for   range



 , for,    .  ,   , -  :

 4.4. letters.py

for letter in "":



print(letter)























  -: "      -  ".  letter       ,    ,   .    : letter, char, x -    .

  for  .     range ().     :

range(5) -   0  4 ( ,   );

range(1, 6) -  1  5:  ,   ;

range(0, 20, 5) -  0  20   5: 0, 5, 10, 15;

range(10, 0, -1) -  10  1   .

,      ,    .   : range(1, 6)  6 - 1 = 5 .     1  10,  range(1, 11).

    .      ,   ,  print   end:  ,       .     ,    .

 4.5. ranges.py

for i in range(5):



print(i, end=" ")



print()





for i in range(1, 6):



print(i, end=" ")



print()





for i in range(0, 20, 5):



print(i, end=" ")



print()





for i in range(10, 0, -1):



print(i, end=" ")



print()

0 1 2 3 4



1 2 3 4 5



0 5 10 15



10 9 8 7 6 5 4 3 2 1

 print()     ,       .

 .    (off-by-one error) -      ,    .    1  10,  range(1, 10) -   1  9.   ,  while count <= 10  count = 0 -  .    ,     :         .




 


  -   .

 4.6. times_table.py

number = int(input("  ? "))



for i in range(1, 11):



print(f"{number} x {i} = {number * i}")

  ? 7



7 x 1 = 7



7 x 2 = 14



7 x 3 = 21



7 x 4 = 28



7 x 5 = 35



7 x 6 = 42



7 x 7 = 49



7 x 8 = 56



7 x 9 = 63



7 x 10 = 70

    .      ,   .




 


 :         -   . ,    ,   ,        1  100,        .    ,      :

 4.7. sum_to_100.py

total = 0



for number in range(1, 101):



total += number



print(f"   1  100: {total}")

   1  100: 5050

,    ,   (accumulator). Ÿ         :    0.     ,      .

   :   (counter),  ,   ,   .

 4.8. count_letters.py

text = "  ,     "



count = 0



for char in text:



if char == "":



count += 1



print(f"   {count} ")

   7 

   ,   ,    .     -     .

.    -  ,   print  : print(f"{char=} {count=}").  ,      .   ,  print .

  4.4.       1  100.    :         range.

  4.5.   n ( n!) -      1  n: 5! = 1 * 2 * 3 * 4 * 5 = 120.  ,   n    . ,        .

  4.6.      ,    .     ,      ?




  


       while,   for,       .  :

 ,       ( ,   ,   1  100),  for;

  ,  -   (  ,   ,     ""),  while.

,       :

 4.9. two_loops.py

print(" while:")



n = 3



while n > 0:



print(n)



n -= 1





print(" for:")



for n in range(3, 0, -1):



print(n)

 while:



3



2



1



 for:



3



2



1

 for   :   ,     ,  ,     .




  : break  continue



     .     break ().    ,  Python     .

  break    while True.  True  ,    ,     break.    : ",     ".

 4.10. shopping_list.py

print("   .  ,  .")



count = 0



shopping = ""





while True:



item = input(": ")



if item == "":



break



if item == "":



print("  .")



continue



count += 1



shopping += f"{count}. {item}\n"





print(f"\n  {count} :")



print(shopping)

   .  ,  .



: 



:



  .



: 



:   



: 





  3 :



1. 



2. 



3.   

    , continue ().     ,    : ,     , ,       .      ,    continue   count += 1.

  ,  : break - ", ", continue - " ,  ".

 ,   .  shopping - ,            \n  .   ,    ,   .     ,     - .




  else


   Python   :  else.  ,    ,     break.  ,   ,    ,  : . ,   .      1   : 2, 3, 5, 7, 11, 13   .

 4.11. prime.py

number = int(input("   1: "))





for divisor in range(2, number):



if number % divisor == 0:



print(f"{number} - :   {divisor}")



break



else:



print(f"{number} -  ")

   1: 91



91 - :   7

   1: 97



97 -  

   .    ,       ,   else  .          ,  else:  .    : else      for,    if.  else ,   .

  4.7.     4.2  while True  break:  ,      "".      continue.

  4.8.     1000,     17,   23.  while True  for   range  break.




 



     .        .   :      ,    .    .

 4.12. multiplication_table.py

for row in range(1, 10):



for col in range(1, 10):



print(f"{row * col:4}", end="")



print()

1   2   3   4   5   6   7   8   9



2   4   6   8  10  12  14  16  18



3   6   9  12  15  18  21  24  27



4   8  12  16  20  24  28  32  36



5  10  15  20  25  30  35  40  45



6  12  18  24  30  36  42  48  54



7  14  21  28  35  42  49  56  63



8  16  24  32  40  48  56  64  72



9  18  27  36  45  54  63  72  81

    ,  - .         ,    (end=""),   print()    .  {row * col:4}  f-  "  4 ".     ,    ,     ,  .

   .     1? Ÿ    .         : " " * 3 -   ,  "*" * 5 -  .

 4.13. yolka_loop.py

height = int(input(" : "))





for level in range(1, height + 1):



spaces = " " * (height - level)



stars = "*" * (2 * level - 1)



print(spaces + stars)





for _ in range(2):



print(" " * (height - 2) + "| |")

 : 6



*



***



*****



*******



*********



***********



| |



| |

  1  ,   2 ,   3 :     ,  2 * level - 1.         ,    .

     _.   ,     :     ,      .

  4.9.            #  .     ,       .

  4.10.  ""  ,  ,  ,   .       4:

1



12



123



1234




 " "



      .     1  100,   ,   :   .

   "",    .  Python     random.  (module) -    ,    import.    -   11,     : import random     random.randint(1, 100),       1  100 .

 4.14. guess.py

import random





secret = random.randint(1, 100)



attempts = 0



print("    1  100.  !")





while True:



guess = int(input(" : "))



attempts += 1



if guess < secret:



print("  .")



elif guess > secret:



print("  .")



else:



print(f"!  {secret}. : {attempts}.")



break

    1  100.  !



 : 50



  .



 : 25



  .



 : 37



  .



 : 43



  .



 : 40



  .



 : 42



!  42. : 6.

     :     .     .   - 50,  .  ""  ""    .   -   ,   .      (binary search).        7 :       ,  2    -  128,  ,          .




 


  ,     .    for  else:       break, ,  .

 4.15. guess_limited.py

import random





secret = random.randint(1, 100)



print("    1  100.   7 .")





for attempt in range(1, 8):



guess = int(input(f" {attempt}: "))



if guess == secret:



print(f"  {attempt}- !")



break



hint = "" if guess < secret else ""



print(f"  {hint}.")



else:



print(f" .   {secret}.")

  ,       :

    1  100.   7 .



 1: 10



  .



 2: 90



  .



 3: 50



  .



 4: 20



  .



 5: 70



  .



 6: 40



  .



 7: 60



  .



 .   31.

       3,         attempt: range(1, 8)    1  7.




 


    .   ,     :        .

 4.16. computer_guesses.py

print("   1  100,   .")



print(": ,   .")





low = 1



high = 100



attempts = 0





while low <= high:



guess = (low + high) // 2



attempts += 1



answer = input(f" {guess}? ")



if answer == "":



low = guess + 1



elif answer == "":



high = guess - 1



elif answer == "":



print(f"!   : {attempts}.")



break



else:



print(" . : ,   .")



attempts -= 1



else:



print(",  -   .")

  42:

   1  100,   .



: ,   .



 50? 



 25? 



 37? 



 43? 



 40? 



 41? 



 42? 



!   : 7.

 low  high -  ,     .      ,    .    ,   : attempts -= 1     .      low   high,   ,   else:     .

  4.11.      4.14  " ? (/)"  .           while.

  4.12.     4.11    (  )        .

  4.13.      4.16,   1,   100.   ?      ?








 while  ,   .    - ,    ;      Ctrl+C.

 for    :  ,   range. range(1, 11) -    1  10:   .

        :   ,   .

break   , continue -   . while True  break  -   ,     .

 else   ,    ,  break;    .

          .  {x:4}    ,  print(..., end="")    .

random.randint(1, 100)    ;      1  100     7 .




 5.   



          . ,  :      ,  ,   ,     .      Python   .     - .       ,  , ,         .        - .




  



 (list) -    .     ,   .

 5.1. shopping.py

shopping = ["", "", "  ", ""]



prices = [89, 45, 320, 150]



empty = []





print(shopping)



print(prices)



print(empty)



print(f"  : {len(shopping)}")



print(f"  : {sum(prices)} .")

['', '', '  ', '']



[89, 45, 320, 150]



[]



  : 4



  : 604 .

     (elements  items).    , ,      .  len,   , ,    ,   sum    .   []   :   ,       .

 :     Python     .   ,   ,   .   ,    ,    .








      -  (index).    :     0,  - 1,   .   ,        .

>>> shopping = ["", "", "  ", ""]



>>> shopping[0]



''



>>> shopping[2]



'  '



>>> shopping[-1]



''



>>> shopping[-2]



'  '

    : -1 -  , -2 - .   :    ,     .

   ?       :  ,       .      ,   .   ,       .

   ,  , Python   :

>>> shopping = ["", "", "  ", ""]



>>> shopping[4]



Traceback (most recent call last):



File "<python-input-1>", line 1, in <module>



shopping[4]



~~~~~~~~^^^



IndexError: list index out of range

"   ".    ,    0  3,   4 .     ,       4.

      ,   :

>>> shopping = ["", "", "  "]



>>> shopping[1] = ""



>>> shopping



['', '', '  ']

    : ""[0] -  "".       .   (immutable):     ,    .

>>> name = ""



>>> name[0]



''



>>> name[-1]



''



>>> name[0] = ""



Traceback (most recent call last):



File "<python-input-3>", line 1, in <module>



name[0] = ""



~~~~^^^



TypeError: 'str' object does not support item assignment

" str    ".    (mutable),     .

  5.1.       .  ,    ,     .

  5.2.   temperatures = [-3, -5, 0, 2, 4, 1, -1]    ,    .       .    :     3 .








    ,   .     (slices).   : [:].    range,    ,   - .

 5.2. week_weather.py

days = ["", "", "", "", "", "", ""]



temperatures = [-3, -5, 0, 2, 4, 1, -1]





print("  :", days[0:3], temperatures[0:3])



print(" :", days[:5])



print(":", days[5:], temperatures[-2:])



print(" :", days[::2])



print(" :", days[::-1])

  : ['', '', ''] [-3, -5, 0]



 : ['', '', '', '', '']



: ['', ''] [1, -1]



 : ['', '', '', '']



 : ['', '', '', '', '', '', '']

 :

    ([:5]),     ;

    ([5:]),     ;

  -  ([::2] -   ),   range;

 -1  .

    ,   .     ,      :

>>> ""[::-1]



''



>>> ""[::-1]



''



>>> " "[:5]



''

 ""     .    .

  5.3.  ,     ,   .    "", ""  "".

  5.4.   months = ["", "", "", "", "", "", "", "", "", "", "", ""]  :  ;  ;   ,   .




 



    .       (methods): ,       .  :

append(x) -    ;

insert(i, x) -       i;

remove(x) -   ,  x;

pop() -     ; pop(i) -    i;

clear() -  .

 5.3. shopping_edit.py

shopping = ["", ""]



print(":", shopping)





shopping.append("")



print(" :", shopping)





shopping.insert(0, "  ")



print(" -   :", shopping)





shopping.remove("")



print("  :", shopping)





last = shopping.pop()



print(f"  ({last}):", shopping)





if "" in shopping:



print("  !")



print("  ?", "" in shopping)

: ['', '']



 : ['', '', '']



 -   : ['  ', '', '', '']



  : ['  ', '', '']



  (): ['  ', '']



  !



  ? False

 in ,     ,   True  False.     not in.    : index(x)    ,  x,  count(x) ,   x   .

   ,  .     - :

>>> shopping = ["", ""]



>>> shopping.remove("")



Traceback (most recent call last):



File "<python-input-1>", line 1, in <module>



shopping.remove("")



~~~~~~~~~~~~~~~^^^^^^^^^^^



ValueError: list.remove(x): x not in list

  remove  : if "" in shopping:.

  Python 3.15.      JavaScript,    push  append. Python 3.15       :

>>> shopping = [""]



>>> shopping.push("")



Traceback (most recent call last):



File "<python-input-1>", line 1, in <module>



shopping.push("")



^^^^^^^^^^^^^



AttributeError: 'list' object has no attribute 'push'. Did you mean '.append'?




  -  


 ,    .    ,        .

 5.4. two_names.py

papa_list = ["", ""]



mama_list = papa_list



mama_list.append("")





print(" :", mama_list)



print(" :", papa_list)

 : ['', '', '']



 : ['', '', '']

     !     2:  -    .  mama_list = papa_list    ,        .  ,    ,       .

   ,   copy():

 5.5. two_lists.py

papa_list = ["", ""]



mama_list = papa_list.copy()



mama_list.append("")





print(" :", mama_list)



print(" :", papa_list)

 : ['', '', '']



 : ['', '']

      :  ,  ""      ,    .     ,   ,    .

  5.5.     .       append,       insert,     remove,     pop    ": ...".     .

  5.6.   guests = ["", "", "", "", ""]   .   count,    ,     ,    .




  



    .  sort()   ,  .  sorted()       , .      ,    reverse=True -  .

 5.6. harvest.py

#    , 



harvest = [2.5, 3.1, 1.8, 4.2, 3.6, 2.9, 0.7]





print(" :", harvest)



print(" :", sorted(harvest))



print(" :", sorted(harvest, reverse=True))



print("   :", harvest)





total = sum(harvest)



print(f": {total:.1f} ")



print(f" : {max(harvest)} , : {min(harvest)} ")



print(f" : {total / len(harvest):.2f}   ")





harvest.sort()



print(" sort():", harvest)

 : [2.5, 3.1, 1.8, 4.2, 3.6, 2.9, 0.7]



 : [0.7, 1.8, 2.5, 2.9, 3.1, 3.6, 4.2]



 : [4.2, 3.6, 3.1, 2.9, 2.5, 1.8, 0.7]



   : [2.5, 3.1, 1.8, 4.2, 3.6, 2.9, 0.7]



: 18.8 



 : 4.2 , : 0.7 



 : 2.69   



 sort(): [0.7, 1.8, 2.5, 2.9, 3.1, 3.6, 4.2]

 max  min     ,    -  ,   .   -     ,      .

 .  sort()   :     .  harvest = harvest.sort() - :  harvest    None (),    .     -  sorted(harvest),     -  harvest.sort().

   , ,   ,      3.  key     . , key=len    :

>>> pets = ["", "", "", ""]



>>> sorted(pets)



['', '', '', '']



>>> sorted(pets, key=len)



['', '', '', '']

  5.7.     : [5, 4, 4, 3, 5, 5, 4, 2, 5].        ,         .

  5.8.    ["", "", "", "", ""]  ,     , ,   .




 



 ,    , -     for,   ,   .

 5.7. numbered.py

shopping = ["", "", "  "]





for item in shopping:



print("-", item)





print()



for number, item in enumerate(shopping, start=1):



print(f"{number}. {item}")

- 



- 



-   





1. 



2. 



3.   

    .    ,     enumerate ().      :   ,        .  start=1     ,    ,    ,    .

     ,      zip (-).    ,   :

 5.8. receipt.py

products = ["", "", "", "  "]



prices = [89, 45, 450, 320]





total = 0



for product, price in zip(products, prices):



print(f"{product:<20}{price:>6} .")



total += price



print("-" * 30)



print(f"{'':<20}{total:>6} .")

                  89 .



                    45 .



                    450 .



         320 .



------------------------------



                  904 .

    : {product:<20}  20     ,  {price:>6}  6     .     -   7.




,    


      4    -:   -   .

 5.9. shopping_input.py

print("   .  ,  .")



shopping = []





while True:



item = input(": ")



if item == "":



break



if item in shopping:



print("    .")



continue



shopping.append(item)





shopping.sort()



print(f"\n   {len(shopping)},  :")



for number, item in enumerate(shopping, start=1):



print(f"{number}. {item}")

   .  ,  .



: 



: 



: 



    .



: 



: 





   3,  :



1. 



2. 



3. 

    : append    .  item in shopping        .        .       4   ,    .

 .        for,     .    ,     :   ""   ,    .    ,  :     ,    .

  5.9.   names = ["", "", ""]  ages = [45, 43, 15].    zip   " - 45 ".     .

  5.10.  ,    (),      "",      ,   , ,   .




 



      :   -     .    :

prices = [89, 45, 450, 320]



sale_prices = []



for price in prices:



sale_prices.append(round(price * 0.9, 2))

        (list comprehension):

 5.10. comprehensions.py

prices = [89, 45, 450, 320, 1200]





sale_prices = [round(price * 0.9, 2) for price in prices]



print("  10%:", sale_prices)





expensive = [price for price in prices if price > 300]



print(" 300 :", expensive)





words = ["", "", "", ""]



lengths = [len(word) for word in words]



print(" :", lengths)





squares = [n ** 2 for n in range(1, 11)]



print(":", squares)

  10%: [80.1, 40.5, 405.0, 288.0, 1080.0]



 300 : [450, 320, 1200]



 : [3, 6, 5, 7]



: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

     : ",   0.9    ,      ".  round       80.10000000000001:        2?     ,    ,   for,    -  if,   .  -  ,   .

    ,     .           ,   for  .




  


     ,     . ,     ,      :

 5.11. flatten.py

weeks = [



[1200, 450, 89],



[3200, 150],



[560, 780, 45, 320],



]





all_expenses = [*week for week in weeks]



print("  :", all_expenses)



print(":", sum(all_expenses))



print("  :", max(all_expenses))

  : [1200, 450, 89, 3200, 150, 560, 780, 45, 320]



: 6794



  : 3200

  week  "    ".   ,           .    .

  Python 3.15.     -   3.15.          : [cost for week in weeks for cost in week].        Python,   .

  5.11.    [-3, -5, 0, 2, 4, 1, -1]   :     ( )       (: F = C * 9 / 5 + 32).

  5.12.          1  100,    7,      .








 (tuple)   ,  :     .     .

 5.12. dacha.py

dacha = (56.35, 37.52)  #   



birthday = (12, "", 2022)  #   





print(" :", dacha)



print(":", dacha[0])





latitude, longitude = dacha



print(f" {latitude},  {longitude}")





day, month, year = birthday



print(f"  {day} {month} {year} .")

 : (56.35, 37.52)



: 56.35



 56.35,  37.52



  12  2022 .

       ,   .    latitude, longitude = dacha   (unpacking):      .       .

  ,   ?    ,        : , ,    .     :     -    .   , Python 3.15 , , ,   :

>>> dacha = (56.35, 37.52)



>>> dacha.append(100)



Traceback (most recent call last):



File "<python-input-1>", line 1, in <module>



dacha.append(100)



^^^^^^^^^^^^



AttributeError: 'tuple' object has no attribute 'append'. Did you mean to use a 'list' object?

    -      :

>>> a = ""



>>> b = ""



>>> a, b = b, a



>>> print(a, b)



 

   (b, a),        a  b.      ,  .  :       , (5,),   (5) -    5  .




 


    . , -:   -     .

 5.13. price_list.py

price_list = [



("", 89),



("", 45),



("", 450),



("  ", 320),



]





for name, price in price_list:



print(f"{name}: {price} .")





cheap = [name for name, price in price_list if price < 100]



print(" 100 :", cheap)

: 89 .



: 45 .



: 450 .



  : 320 .



 100 : ['', '']

     : for name, price in price_list          .     .      ,     8,    .

  5.13.       (, , )       "  5  2010 ".

  5.14.    " -   "   .  ,     ,      .




  :   



  3     ,          .     ,   ,     :  - ,  - .

 5.14. quiz_list.py

questions = [



("     : 5, 10  15?", "15"),



("    ? (/)", ""),



("     ? (/)", ""),



("   ?", ""),



]





print(":     ?")



score = 0



for number, (question, right_answer) in enumerate(questions, start=1):



answer = input(f"{number}. {question} ")



if answer == right_answer:



print("!")



score += 1



else:



print(f",  : {right_answer}.")





print(f"\n : {score}  {len(questions)}.")

:     ?



1.      : 5, 10  15? 15



!



2.     ? (/) 



,  : .



3.      ? (/) 



!



4.    ? 



!





 : 3  4.

       .     ,         :   (question, right_answer) ,   enumerate   "  ".     ,      :   -      .      :  ,  .

  5.15.         ,            .








 -       . len  , sum, min, max - ,    .

   ,    ;      IndexError.  [::]   ,   .

 append, insert, remove, pop, clear  ,  in   . ,    , .

 b = a   ,     ;   a.copy().

sort()       , sorted()   ;  reverse=True  key=len  .

enumerate    , zip    .

  [ for x in  if ]     ;  Python 3.15       .

 -     ;  a, b = b, a    .




 6.   



 ,   :  , , .     .  ,  ,   -      ,     "  ?"  "   ?".     Python  .        ,   ,       ,   frozendict -  Python 3.15.




  



   :      .   :      .  (dictionary,  dict)  Python   :    " - " (key - value).      .

 6.1. prices.py

prices = {



"": 89,



"": 45,



"": 450,



}





print(prices)



print(" ", prices[""], ".")





prices["  "] = 320  #  



prices[""] = 49  #  



print(prices)





del prices[""]



print("   :", prices)



print("  :", len(prices))



print("    ?", "" in prices)

{'': 89, '': 45, '': 450}



  89 .



{'': 89, '': 49, '': 450, '  ': 320}



   : {'': 89, '': 49, '  ': 320}



  : 3



    ? True

    .   -  ,   ,    .     ,    ,   .      ,      .

      : prices[""].     .    ,    ,   -  .    del.  len ,    ,   in ,   .

 :   ,    .   "  "   .




  


    ,    ,  :

>>> prices = {"": 89, "": 45}



>>> prices[""]



Traceback (most recent call last):



File "<python-input-1>", line 1, in <module>



prices[""]



~~~~~~^^^^^^^^^^^



KeyError: ''

KeyError -  ,      ,   .    ,   get.   ,     -   None ("")     ,      ( -      ,    -   8):

>>> prices = {"": 89, "": 45}



>>> prices.get("")



45



>>> print(prices.get(""))



None



>>> prices.get("", 0)



0

None -  ,    .     ,     print.    None   8,    .

  -     .

 6.2. translator.py

words = {



"": "cat",



"": "milk",



"": "thank you",



" ": "how much",



}





word = input(" -: ")



translation = words.get(word, "   ")



print(f"{word} - {translation}")

 -: 



 - cat

 -: 



 -    




   


     : , , ,  .      : , , .     ,     ,    .    :     ,   .

  6.1.       :   45,   43,  15,  4.   ,      (    1)    .

  6.2.      6.2   .  ,      ,      .

  6.3. ,   ,   :

d = {"a": 1, "b": 2, "a": 3}



print(d, len(d))




 



   for,  .    :  ,    .

 6.3. expenses.py

expenses = {



"": 18500,



"": 6800,



"": 3200,



"": 2100,



"": 4000,



}





for category in expenses:



print(category, end="; ")



print()





total = sum(expenses.values())



print(f"  : {total} .")





for category, amount in expenses.items():



share = amount / total * 100



print(f"{category:<12}{amount:>7} .{share:>6.1f}%")





biggest = max(expenses, key=expenses.get)



print(f"    : {biggest}")

; ; ; ; ;



  : 34600 .



      18500 .  53.5%



     6800 .  19.7%



      3200 .   9.2%



            2100 .   6.1%



    4000 .  11.6%



    : 

 for category in expenses  :      .  values()   ,      sum.   items()   " - ",      ,     5.    keys()  ,    :      .

  max - ,   .  max   ,       ,   ,   expenses.get   .       .      : sorted(expenses, key=expenses.get).




   


    :  - ,  ,  -   . ,        .

 6.4. word_count.py

review = "            "





counts = {}



for word in review.split():



counts[word] = counts.get(word, 0) + 1





print(counts)



for word in sorted(counts, key=counts.get, reverse=True)[:3]:



print(f"{word}: {counts[word]}")

{'': 2, '': 1, '': 3, '': 1, '': 1, '': 1, '': 1, '': 1, '': 1, '': 1}



: 3



: 2



: 1

  - counts[word] = counts.get(word, 0) + 1.    , get  0,     1.    , get   ,     1.               .      ,     Python      Counter;       11.

  6.4.   expenses   6.3   ,       ,  .

  6.5. ,        "".     .

  6.6.    grades = {"": 5, "": 3, "": 4, "": 5, "": 4}.   ,          .




 



  ,      .        ,    - .         .




 


 ,      : , ,  .   - ,    -   .

 6.5. contacts.py

contacts = [



{"name": "", "phone": "+7 900 111-22-33", "birthday": "12.03"},



{"name": "Ҹ ", "phone": "+7 900 444-55-66", "birthday": "30.07"},



{"name": "", "phone": "+7 495 777-88-99", "birthday": None},



]





for person in contacts:



line = f"{person['name']}: {person['phone']}"



if person["birthday"]:



line += f",   {person['birthday']}"



print(line)





wanted = "Ҹ "



for person in contacts:



if person["name"] == wanted:



print(f"!    {person['phone']}")



break



else:



print(f"{wanted}    ")

: +7 900 111-22-33,   12.03



Ҹ : +7 900 444-55-66,   30.07



: +7 495 777-88-99



!    +7 900 444-55-66

 f-      : person['name'].  f-   ,      ,   .   3.12 Python     ,       ,      .       ,     None:  if person["birthday"]  None ,   .       break  else   4.




 


   ,      .  -  ,  -  ,    .

 6.6. garden_beds.py

beds = {



" ": ["", ""],



" ": ["", "", ""],



" ": [""],



}





beds[" "].append("")



beds[""] = [""]





for bed, plants in beds.items():



print(f" {bed}: {', '.join(plants)}")





plant = ""



for bed, plants in beds.items():



if plant in plants:



print(f"{plant.capitalize()}    {bed}.")

  : , 



  : , , 



  : , 



 : 



     .

beds[" "] -  ,        append:    ,     ,     .  ', '.join(plants)          ,  capitalize()     .        7.




 


,   :     .

>>> pets = {



...     "": {"": "", "": 4, "": 5.6},



...     "": {"": "", "": 2, "": 0.1},



... }



>>> pets[""][""]



5.6



>>> pets[""][""] += 1



>>> pets[""]



{'': '', '': 3, '': 0.1}

   : pets[""]   ,  [""]    .            JSON,         .  JSON      10.

  6.7.      6.5   .   ,      ( 06, 07  08). :   "30.07"[3:]   .

  6.8.   beds   6.6 ,      ,   ,     .








 (set) -       .    ,  ,   .

>>> numbers = {3, 1, 2, 3, 1}



>>> numbers



{1, 2, 3}



>>> len(numbers)



3



>>> 2 in numbers



True



>>> numbers.add(10)



>>> numbers.discard(1)



>>> numbers



{10, 2, 3}

  :         .  add  , discard  (  ,   ),  in ,   ,       ,    .

    set().    {} -   ,   :   Python      .

 .    .    ,            .    :   ,       sorted.




 


    -   .

 6.7. unique.py

bought = ["", "", "", "", "", ""]



unique = set(bought)



print(f"  {len(bought)},   {len(unique)}")



print(" :", sorted(unique))

  6,   3



 : ['', '', '']

 set    ,   .  sorted   ,         .




  


  ,  , ,    : ,   .      :     ,   .

 6.8. guests.py

mama = {"", "", "", " "}



papa = {"", "", "", " "}





print(" :", sorted(mama | papa))



print(" :", sorted(mama & papa))



print(" :", sorted(mama - papa))



print(" :", sorted(papa - mama))



print("  - :", sorted(mama ^ papa))

 : ['', '', '', '', ' ', ' ']



 : ['', '']



 : ['', ' ']



 : ['', ' ']



  - : ['', '', ' ', ' ']

| -  (union):     ;

& -  (intersection):  ,    ;

- -  (difference): ,    ,    ;

^ -   (symmetric difference): ,       .

        ,   -     .

  6.9.    ,  .  : , , , , .  : , , , , . ,    ,  ,             .

  6.10.      ,      ( ). :      ,   : set("").




frozendict -  Python 3.15



     - .        .  Python 3.15  : frozendict, " ".   ,  ,  :     .

 6.9. settings.py

DEFAULT_SETTINGS = frozendict(theme="", font_size=12, sound=True)





print(DEFAULT_SETTINGS)



print("   :", DEFAULT_SETTINGS["font_size"])





my_settings = DEFAULT_SETTINGS | {"theme": ""}



print(" :", my_settings)



print("    :", DEFAULT_SETTINGS)





DEFAULT_SETTINGS["sound"] = False

frozendict({'theme': '', 'font_size': 12, 'sound': True})



   : 12



 : frozendict({'theme': '', 'font_size': 12, 'sound': True})



    : frozendict({'theme': '', 'font_size': 12, 'sound': True})



Traceback (most recent call last):



File "C:\pyprojects\settings.py", line 10, in <module>



DEFAULT_SETTINGS["sound"] = False



~~~~~~~~~~~~~~~~^^^^^^^^^



TypeError: 'frozendict' object does not support item assignment

frozendict   frozendict.      ,  ,   : frozendict({"theme": ""}).       :  , get, items(),  for.         TypeError: " frozendict    ".

   -   frozendict   .  |  :  ,     .  -  frozendict,    .

 DEFAULT_SETTINGS   .    Python    (constants) - ,           .       : -          .  frozendict  .




frozendict  


    . frozendict       ,    - :

>>> orders = set()



>>> orders.add({"": "", "": True})



Traceback (most recent call last):



File "<python-input-1>", line 1, in <module>



orders.add({"": "", "": True})



~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^



TypeError: cannot use 'dict' as a set element (unhashable type: 'dict')



>>> orders.add(frozendict({"": "", "": True}))



>>> frozendict(=True, ="") in orders



True

Python ,       :   (unhashable type - " ";  -    ,        ).  frozendict   .     : frozendict    ,     ,      .

      . ,      ,     :

 6.10. orders.py

orders = [



{"": 3, "": "", "": True},



{"": 5, "": "", "": False},



{"": True, "": "", "": 3},



]





seen = set()



for order in orders:



key = frozendict(order)



if key in seen:



print(", :", dict(key))



continue



seen.add(key)



print(" :", dict(key))

 : {'': 3, '': '', '': True}



 : {'': 5, '': '', '': False}



, : {'': True, '': '', '': 3}

  -   ,   ,       .  seen    ,  frozendict        .  dict  frozendict    :    ,    .

  Python 3.15. frozendict -  ,    .  json,       10,   frozendict  ,   .     Python   ,      NameError.

  6.11.  frozendict WORK_HOURS        (, "": "9-21").      frozendict,       10  18,   .




  :  



 - ,   :  , , ,  .     " - ",   match   3.

 6.11. phonebook.py

phonebook = {"": "+7 900 111-22-33"}



print(" . : , , , , .")





while True:



command = input("> ")



match command:



case "":



name = input(": ")



phone = input(": ")



phonebook[name] = phone



print(f": {name}")



case "":



name = input(" ? ")



print(phonebook.get(name, "  "))



case "":



name = input(" ? ")



if name in phonebook:



del phonebook[name]



print(f": {name}")



else:



print("  ")



case "":



for name in sorted(phonebook):



print(f"{name}: {phonebook[name]}")



case "":



print(" !")



break



case _:



print("  ")

 . : , , , , .



> 



: 



: +7 495 777-88-99



: 



> 



 ? 



+7 900 111-22-33



> 



: +7 900 111-22-33



: +7 495 777-88-99



> 



 ? 



  



> 



 !

 ,   .  ,    :     .           ,     10.

  6.12.      "",    ,   ,   "" ,     ,  ,   .








   " - "   : {"": 89}.      : prices[""]; del  , in   .

   KeyError;  get(, _)      None.

 -   (, , ),  - .     .

: for key in d - , d.values() - , d.items() - . max(d, key=d.get)     .

  ( ,  ,  )    ;  -  .

     : set()  ,  | & - ^  ,   .   - set(),   {}.

frozendict ( Python 3.15) -  :   ,       ; |   frozendict  .




 7.   



  ,    , -  . , , , ,  ,  ,    -.         :  ,   ,      . ,      .       ,      : ,    .




 



  5     : append, sort  .     .    ,  .

 7.1. string_methods.py

name = "     "





print(f"[{name}]")



print(f"[{name.strip()}]")



print(name.strip().upper())



print(name.strip().capitalize())



print(name.strip().title())



print(" ר".lower())



print("".startswith(""), "".endswith(""))



print("2026".isdigit(), "20 26".isdigit(), "".isalpha())

[     ]



[ ]



 



 



 



 



True True



True False True

  :

strip()   (  )   .        ,  ,      .   lstrip()  rstrip():        .

upper()  lower()        ,       .

capitalize()     ,  title() -    .

startswith()  endswith() ,          .

isdigit() ,      ,  isalpha() -   .   "20 26"  ,     .

   : name.strip().upper()   ,      upper.  ,       ,   .    ,    : name = name.strip().

  Python 3.15.     JavaScript  Java     toUpperCase, Python ,     :

>>> "".toUpperCase()



Traceback (most recent call last):



File "<python-input-0>", line 1, in <module>



"".toUpperCase()



^^^^^^^^^^^^^^^^^^^^



AttributeError: 'str' object has no attribute 'toUpperCase'. Did you mean '.upper'?




 ""   


  3     ""  ""    .    :   ,         .

 7.2. answer_yes.py

answer = input(" ? ").strip().lower()





if answer in ["", "", "yes", ""]:



print(" !")



else:



print("  ,  .")

 ?   



 !

  Caps Lock    ,     .  answer in [...]      .  ""  (   ) - ,       .

  7.1.        ,     ,   ,     ""  "   ".

  7.2.    ,      ,   isdigit,    .  ,  "   ".

  7.3.    [".docx", ".jpg", ".xlsx", ".JPG", ".pdf"].    (   jpg   ).




  



 ,     - ,   in,   .   ,    ,   find.       -1,    .

>>> text = "    "



>>> "" in text



True



>>> text.find("")



12



>>> text.find("")



-1



>>> text.count("")



6



>>> text.replace("", "")



'    '



>>> text



'    '

 count ,      ,  replace      .     :    . replace   ,      .  -  .

   index,   find,     ,    ValueError,    -1.   -  ,  find  in.




    


   -:  ,  ,  .       ,     .     ,       .

 7.3. phones.py

phones = ["+7 (900) 111-22-33", "8 900 111 22 33", "89001112233", "111-22-33"]





for phone in phones:



digits = ""



for char in phone:



if char.isdigit():



digits += char



if len(digits) == 11 and digits.startswith("8"):



digits = "7" + digits[1:]



if len(digits) == 11:



print(f"{phone:<20} -> +{digits}")



else:



print(f"{phone:<20} ->  ")

+7 (900) 111-22-33   -> +79001112233



8 900 111 22 33      -> +79001112233



89001112233          -> +79001112233



111-22-33            ->  

     .  :   11   - ,      digits[1:],    .         ,      ,      .

  7.4.  ,      ""  ""  ,   .    "    ,     ".

  7.5.           :      @,    ,     .




  



 split       .       (     ),    -   .

>>> "       ".split()



['', '', '', '']



>>> ",,".split(",")



['', '', '']



>>> "12.03.2022".split(".")



['12', '03', '2022']



>>> ", ".join(["", "", ""])



', , '



>>> "-".join("")



'-----'

  -  join ("").       ,     ,   .   :   , ", ".join().      ,    .

   ,  -   :

 7.4. parse_purchases.py

message = " 89;  45 ; 450;     320"





purchases = {}



for part in message.split(";"):



part = part.strip()



name, price = part.rsplit(" ", 1)



purchases[name] = int(price)





print(purchases)



print(f": {sum(purchases.values())} .")

{'': 89, '': 45, '': 450, '  ': 320}



: 904 .

           "  45 ".       .     .  split()   : "   320"    .  rsplit(" ", 1)          ,     :    .

  -    :

 7.5. initials.py

full_name = input("  : ")



last, first, middle = full_name.split()



print(f"{last.capitalize()} {first[0].upper()}. {middle[0].upper()}.")

  :   



 . .

split()     ,       .     ,    ValueError.   9     .

     splitlines():        .      ,        27.

  7.6.      "5, 4, 3, 5, 5, 4".         .

  7.7.           : "  "    "  ".




 



    :.2f     .   f-  .   :

>>> price = 1234567.891



>>> f"{price:.2f}"



'1234567.89'



>>> f"{price:,.2f}"



'1,234,567.89'



>>> f"{price:_.2f}"



'1_234_567.89'



>>> f"{0.256:.1%}"



'25.6%'



>>> f"{7:03}"



'007'



>>> f"{42:+}"



'+42'

:,  :_     ;

:.1%    100    ;

:03       :     "007";

:+    ,   .

     ,    - : 1 234 567,89.    f- ,     :   -,     ,   -  .

 7.6. rubles.py

amount = 1234567.891



english = f"{amount:,.2f}"



russian = english.replace(",", " ").replace(".", ",")



print(f"-: {english}")



print(f"-: {russian} .")

-: 1,234,567.89



-: 1 234 567,89 .




  


     :    .  <   , > - , ^ -  .     -.

 7.7. budget_table.py

expenses = [



("", 18500, 0.535),



("", 6800, 0.197),



("", 4000, 0.116),



("", 3200, 0.092),



("", 2100, 0.061),



]





print(f"{'    ':=^40}")



print(f"{'':<15}{'':>12}{'':>13}")



print("-" * 40)



for name, amount, share in expenses:



print(f"{name:<15}{amount:>12,}{share:>13.1%}")



print("=" * 40)

==========    ===========



                      



----------------------------------------



             18,500        53.5%



            6,800        19.7%



           4,000        11.6%



             3,200         9.2%



                   2,100         6.1%



========================================

 {'    ':=^40}  40 ,    ,      =.        15,    - .    ,    .  ,    : :>12, -    12   ,   .

  7.8.     5 ,      : 5 x  1 =   5    5 x 10 =  50.

  7.9.           ,      1, 2, 3, 4  5  (       ).   -:        .








   Python   datetime.   ,     4   random.   datetime    date - .

 7.8. new_year.py

from datetime import date





today = date.today()



new_year = date(today.year + 1, 1, 1)



days_left = (new_year - today).days





print(":", today)



print("-:", today.strftime("%d.%m.%Y"))



print(f"    : {days_left}")

: 2026-11-19



-: 19.11.2026



    : 43

 from datetime import date  "  datetime  date".   date.today()   ,  date(2027, 1, 1)    ,   .     year, month  day: , today.year -  .   :  -    ( timedelta),    days -  .

      ,   .  :     .

 strftime (string format time, "  ")      .   %d - , %m - , %Y -    .     strptime (string parse time):         .       .




 -


 strftime        ,     -:

>>> from datetime import date



>>> date(2026, 12, 31).strftime("%d %B %Y, %A")



'31 December 2026, Thursday'

      locale,    -    .     .       ,    : "31 ",   "31 ".

 7.9. russian_date.py

from datetime import date, datetime





MONTHS = ["", "", "", "", "", "", "",



"", "", "", "", ""]



WEEKDAYS = ["", "", "", "",



"", "", ""]





text = input("  (..): ")



birthday = datetime.strptime(text, "%d.%m.%Y").date()





month = MONTHS[birthday.month - 1]



weekday = WEEKDAYS[birthday.weekday()]



print(f"  {birthday.day} {month} {birthday.year} , "



f" : {weekday}.")





age_days = (date.today() - birthday).days



print(f"    {age_days} .")

  (..): 12.03.2022



  12  2022 ,  : .



    1713 .

    1  12,    -  0  11,  MONTHS[birthday.month - 1].  weekday()    : 0 - , 6 - ,      .  datetime.strptime       ,  .date()   .

 f-  print   :      Python   .       .

  7.10.  ,      ..  ,     . ,         .

  7.11.     110   .          -. :      timedelta(days=110),       : from datetime import datetime, timedelta.




 : ,    



 upper, lower, capitalize     .       . :

>>> words = ["", "", "", "", "", "", ""]



>>> sorted(words)



['', '', '', '', '', '', '']

 . Python         (Unicode) -  ,        .         ,  ""   "".        :   -    ,    -  .  ""   ,  "" -   .

  :      .    sorted  key=str.lower,   "   ,      ":

>>> words = ["", "", "", "", "", "", ""]



>>> sorted(words, key=str.lower)



['', '', '', '', '', '', '']

 ,        ,  .        ,     ,  .     ,         .      ,     : def    russian_key,  return ,   .

 7.10. russian_sort.py

ALPHABET = ""







def russian_key(word):



return [ALPHABET.find(char) for char in word.lower()]







words = ["", "", "", "", "", "", "", ""]



print(sorted(words, key=russian_key))

['', '', '', '', '', '', '', '']

     : ""  ""  ,   ""  ""  ,     .  russian_key          ALPHABET,      . ,     (, ,  ),   -1       .




,    


      . -  "", - "",       .  -   :         .

 7.11. search_yo.py

recipes = [" ", "  ", " -",



"  ", "  "]





query = input(" ? ")



query_norm = query.lower().replace("", "")





found = [r for r in recipes if query_norm in r.lower().replace("", "")]



if found:



print(":", ", ".join(found))



else:



print("  ")

 ? 



:  

 ? 



:   

        ,    .         ,     .            28.

.        Python   casefold().       ,  lower(),      : ,  ?    ss.         ,  casefold().

  7.12.      : ["", "", "", "", "", ""].  ,       .

  7.13.  ,  ,    ,     ,       .    "     ".




  :  



      . ,            .    "", "", "" :         .

 7.12. reviews.py

text = """ !    ,  .



 ,  . .



    .  .  !



   ,   ."""





sentences = text.count(".") + text.count("!") + text.count("?")



words = text.lower().replace("", "").split()



clean = [word.strip(".,!?") for word in words]





counts = {}



for word in clean:



if len(word) > 3:



counts[word] = counts.get(word, 0) + 1





print(f": {len(text)}, : {len(clean)}, : {sentences}")



print("  :")



for word in sorted(counts, key=counts.get, reverse=True)[:4]:



print(f"  {word:<15}{counts[word]}")

: 183, : 29, : 8



  :



           4



           2



       1



  1

       :     , count     , lower  replace  , split    , strip  ,       ,      6.    : "".   ,       .

  7.14.  :   ,   ()     ""    ("", "", "")       "". :  splitlines()    .








    ,   : strip()  , lower()  upper()  , capitalize()  title()   , isdigit()  isalpha()  .

     : input().strip().lower().

find    (  -1), count , replace ; in ,     .

split    , rsplit(" ", 1) -   , join      .

 f-: :, , :.1% , :03  , :<15, :>12, :^40 ;     .

 datetime: date.today(), date(, , ),    , strftime  strptime   %d.%m.%Y.     -     .

Python      :    ,   . key=str.lower   ,      -  ;      .




 8. 



    : print, input, len, sorted, round.    -     ,  - .        .   :        ,            .




  



,      .     " "    ,   .    -  " "     .    .          ,   " "      : "  (. . 12)".

 (function) -        :    ,       ,   .      ,       ,    .

    DRY (Don't Repeat Yourself, " ").       ,      .




  



  (define)  def,    ,    .     .

 8.1. greet.py

def greet():



print("!")



print("   .")







greet()



print("... ...")



greet()

!



   .



... ...



!



   .

 def greet():       ,    :    Python,  ,   .     (call):    , greet().      .

    ,  : Python       ,  ,   .     ,   :    .    -     : greet, print_menu, count_words,    - .

.            . Python   ,     .   PEP 8 -      Python,        14.




  



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

 8.2. greet_name.py

def greet(name, greeting=""):



print(f"{greeting}, {name}!")







greet("")



greet(" ", "")



greet(greeting=" ", name="")

, !



,  !



 , !

,    ,   (arguments).   greet("")  name   "".   greeting     (default value) "":    ,  .

    .  (positional)   :   -  ,  - .  (keyword)    , greeting=" ",     .     : greet(name="")      .

   , Python    :

>>> def greet(name, greeting=""):



...     print(f"{greeting}, {name}!")



...



>>> greet()



Traceback (most recent call last):



File "<python-input-1>", line 1, in <module>



greet()



~~~~~^^



TypeError: greet() missing 1 required positional argument: 'name'

" greet()      : name".

       . ,   :

 8.3. receipt_lines.py

def print_line(name, price, quantity=1):



total = price * quantity



print(f"{name:<18}{quantity:>3} x {price:>6.2f} = {total:>8.2f}")







def print_separator(char="-", width=40):



print(char * width)







print_separator("=")



print_line("", 89.90, 2)



print_line("", 45)



print_line("  ", 320, 3)



print_separator()

========================================



              2 x  89.90 =   179.80



                1 x  45.00 =    45.00



      3 x 320.00 =   960.00



----------------------------------------

     ,   print_line.      -,    .

 .       ,   : def add_item(item, basket=[]).     ,  Python   ,     .       basket         .   basket=None,   : if basket is None: basket = [].  is None  "  None":     .

  8.1.   print_box(text),       .       .

  8.2.   print_box  char     "*",       .        .




 



     -  .          ,       .     return ("").

 8.4. discount.py

def price_with_discount(price, percent):



return round(price * (100 - percent) / 100, 2)







milk = price_with_discount(89.90, 10)



cheese = price_with_discount(450, 15)



print(f"  : {milk:.2f} .")



print(f"  : {cheese:.2f} .")



print(f": {milk + cheese:.2f} .")



print(f"  : {price_with_discount(320, 5) * 5:.2f} .")

  : 80.91 .



  : 382.50 .



: 463.41 .



  : 1520.00 .

return      ,   .  price_with_discount(89.90, 10)      , 80.91,      ,        f-.     : len("")  6.




print  return


        . :

 8.5. print_vs_return.py

def area_print(width, height):



print(width * height)







def area_return(width, height):



return width * height







result1 = area_print(3, 4)



result2 = area_return(3, 4)



print("result1 =", result1)



print("result2 =", result2)

12



result1 = None



result2 = 12

   12  ,    .   return    None (""),       6.   result1  None,      .  :     ,    ,      -  ,   .




    


     :      ,   .

 8.6. harvest_stats.py

def stats(numbers):



if not numbers:



return 0, 0, 0



average = sum(numbers) / len(numbers)



return min(numbers), max(numbers), round(average, 2)







harvest = [2.5, 3.1, 1.8, 4.2, 3.6, 2.9, 0.7]



low, high, avg = stats(harvest)



print(f"  :  {low}  {high} ,   {avg} ")



print(" :", stats([]))

  :  0.7  4.2 ,   2.69 



 : (0, 0, 0)

     .   ,    (   ),     .  return  ,     .      (early return):     ,      .

,   ""  "",  True  False.     is_  has_: " ", " ".      3:

 8.7. leap.py

def is_leap(year):



return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0







def days_in_year(year):



return 366 if is_leap(year) else 365







for year in [1900, 2000, 2024, 2026]:



print(f"{year}:  - {is_leap(year)},  {days_in_year(year)}")

1900:  - False,  365



2000:  - True,  366



2024:  - True,  366



2026:  - False,  365

 is_leap    : True  False.  if ...: return True else: return False  ,     .   days_in_year  is_leap:     ,        .

  8.3.   grade(points),     0  100   (   3.5),      95, 80, 61  30.

  8.4.   cat_human_age(cat_age),            3.     .

  8.5.   split_bill(total, people, tip_percent=10),    :        ( ).    .




 



,   ,    .    (local).    :

 8.8. scope.py

discount = 10  #  







def apply_discount(price):



result = price * (100 - discount) / 100  # result - 



return result







print(apply_discount(500))



print(result)

450.0



Traceback (most recent call last):



File "C:\pyprojects\scope.py", line 10, in <module>



print(result)



^^^^^^



NameError: name 'result' is not defined

    discount,  .  ,    ,   (global).    result ,    ,     .  NameError   .

,   ,    (scope).   :          ,             .

  ,       ?

 8.9. scope_error.py

visits = 0







def count_visit():



visits += 1



print(f"   : {visits}")







count_visit()

Traceback (most recent call last):



File "C:\pyprojects\scope_error.py", line 9, in <module>



count_visit()



~~~~~~~~~~~^^



File "C:\pyprojects\scope_error.py", line 5, in count_visit



visits += 1



^^^^^^



UnboundLocalError: cannot access local variable 'visits' where it is not associated with a value

   ( visits += 1 -  )   . Python ,      visits,      ,    . "     visits,    ".

Python    ,       global visits.       :      ,      .          return:

 8.10. scope_fixed.py

def count_visit(visits):



visits += 1



print(f"   : {visits}")



return visits







visits = 0



visits = count_visit(visits)



visits = count_visit(visits)

   : 1



   : 2

 ,   ,    ,  ,  , -  return.    ,    .

  8.6.   , ,   .  .

x = 1







def f():



x = 2



print(":", x)







f()



print(":", x)




  



 print     .      .      ,        .      args (arguments).         ,     kwargs (keyword arguments).       ,    .

 8.11. pizza.py

def total(*prices):



return sum(prices)







def order_pizza(size, *toppings, **details):



print(f" {size} ")



if toppings:



print(":", ", ".join(toppings))



for key, value in details.items():



print(f"  {key}: {value}")







print(":", total(89, 45, 450))



print(":", total())



order_pizza(30, "", "", "",



=". , 5", ="")



order_pizza(25)

: 584



: 0



 30 



: , , 



: . , 5



: 



 25 

  total      prices,  sum  .     :   .  order_pizza     size,   -  toppings,   -   details.

     ,  .      ,  ""    :

>>> def total(*prices):



...     return sum(prices)



...



>>> basket = [89, 45, 450]



>>> total(*basket)



584



>>> print(*basket, sep=" + ")



89 + 45 + 450

 sep  print    :    .

  8.7.   average(*numbers),      ,     - None.




   



    .           (docstring)   :   ,     .         (type hints):    .

 8.12. documented.py

def price_with_discount(price: float, percent: float = 0) -> float:



"""   ,   .





price -   , percent -    ( 0  100).



"""



return round(price * (100 - percent) / 100, 2)







help(price_with_discount)



print(price_with_discount(450, 15))

Help on function price_with_discount in module __main__:





price_with_discount(price: float, percent: float = 0) -> float



   ,   .





price -   , percent -    ( 0  100).





382.5

 help      .  VS Code       ,            .

  : price: float - " price,  ", -> float - "   ".     ,   : list[str] -  , dict[str, int] -       .    ,  str | None - "  None".

 :  Python   .    price_with_discount ,     ,       .  -      : VS Code   ,     ,   :     (Ctrl+,)  Type Checking Mode   basic.         ,    .

  8.8.         grade  cat_human_age   8.3  8.4.      help.




 : lambda



        ,       def .     - (lambda functions): lambda x: x * 2 -  ,   x   x * 2.  return  ,     .

      key  sorted, min  max.   5    -  .  :

 8.13. sort_lambda.py

price_list = [



("", 89),



("", 450),



("", 45),



("  ", 320),



]





by_price = sorted(price_list, key=lambda item: item[1])



print("   :", by_price)





priciest = max(price_list, key=lambda item: item[1])



print(" :", priciest[0])





pets = {"": 5.6, "": 3.9, "": 4.4}



for name, weight in sorted(pets.items(), key=lambda pair: pair[1]):



print(f"{name}: {weight} ")

   : [('', 45), ('', 89), ('  ', 320), ('', 450)]



 : 



: 3.9 



: 4.4 



: 5.6 

    sorted       ,   . lambda item: item[1]     , .  "   ".

     :  , if     .         ,     def     .

  8.9.    ["", "", "", "", ""]      .       .

  8.10.     : [("", 4.8), ("", 3.9), ("", 4.5)].   max  min       .




  :   



  3      ,   5     .     ,       .

 8.14. quiz_functions.py

QUESTIONS = [



("     : 5, 10  15?", "15"),



("    ? (/)", ""),



("     ? (/)", ""),



("   ?", ""),



]







def normalize(text: str) -> str:



"""    :    , ."""



return text.strip().lower().replace("", "")







def ask(number: int, question: str, right_answer: str) -> bool:



"""    True,   ."""



answer = input(f"{number}. {question} ")



if normalize(answer) == normalize(right_answer):



print("!")



return True



print(f",  : {right_answer}.")



return False







def verdict(score: int, total: int) -> str:



"""     ."""



share = score / total



if share == 1:



return "   !"



if share >= 0.5:



return "!   ."



return "   .   ."







def run_quiz(questions: list[tuple[str, str]]) -> int:



"""      ."""



score = 0



for number, (question, right_answer) in enumerate(questions, start=1):



if ask(number, question, right_answer):



score += 1



return score







def main():



print(":     ?")



score = run_quiz(QUESTIONS)



print(f"\n : {score}  {len(QUESTIONS)}.")



print(verdict(score, len(QUESTIONS)))







if __name__ == "__main__":



main()

:     ?



1.      : 5, 10  15? 15



!



2.     ? (/) 



!



3.      ? (/) 



,  : .



4.    ? 



!





 : 3  4.



!   .

  ,       . normalize     ,  ""  "", ""  ""  . ask   . verdict  . run_quiz   ,  main ()   .

   -   Python .  __name__  "__main__",     .           (  -   11), main()   ,     , ,  normalize,   .    ,    main,       .

  8.11.     ask_name(),       ,         .

  8.12.   print_progress(score, total),      ,  [####------] 4/10,      .








 -   . Ÿ   def            .

     ;     ()    ().     ([]) - ,    None.

return     ;   return  None.       -  .

     ;    return    .

       .        global,        .

*args      , **kwargs -   ;       .

     (price: float, -> float)     ; Python   .

lambda -      ,    key  sorted, min  max.  if __name__ == "__main__": main()  ,     .




 9.   



    ,       .     .        ,  ,        ,   ,          .




  



     .

  (syntax errors) -   :  ,  .  Python   ,      .       1.

   (runtime errors)    :   ,     ,     " ".  Python    (exceptions),       .        .

  (logic errors) -  .      ,   .   2%  10%   3? Python    :    ,  ,    .    ( 13)  .




  



     ,   .  ,       .

 9.1. family_share.py

def share(total, people):



return total / people







def print_shares(expenses, family):



for category, amount in expenses.items():



print(f"{category}:  {share(amount, len(family)):.2f} .")







def main():



expenses = {"": 18500, "": 6800}



family = []



print_shares(expenses, family)







main()

Traceback (most recent call last):



File "C:\pyprojects\family_share.py", line 16, in <module>



main()



~~~~^^



File "C:\pyprojects\family_share.py", line 13, in main



print_shares(expenses, family)



~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^



File "C:\pyprojects\family_share.py", line 7, in print_shares



print(f"{category}:  {share(amount, len(family)):.2f} .")



~~~~~^^^^^^^^^^^^^^^^^^^^^



File "C:\pyprojects\family_share.py", line 2, in share



return total / people



~~~~~~^~~~~~~~



ZeroDivisionError: division by zero

     "  ". ,     1,  .

1.       :  . ZeroDivisionError: division by zero -   .

2.        -  : ,  2,  share,  return total / people.    ,    .

3.       -   share:  7,  print_shares.

4.        -   print_shares:  13,  main.

5.          -  main()   16,    .

   share,    .   ,     .        :  main  family .   : ,   ,  ,   , -  .          .

.        ,    .       :      ,    ,    .




 


 ,    .      .





 





ValueError

  ,  

int("")



TypeError

   

"5" + 1



NameError

 

 pirnt



IndexError

   

[1, 2][5]



KeyError

    

prices[""]



AttributeError

    

[1].push(2)



ZeroDivisionError

  

1 / 0



FileNotFoundError

  

  



  -   .    ,   .

  9.1.   ,        .        .

  9.2.     9.1 ,    ,     ,   "    ". ,    :  share,  print_shares   main.




 : try  except



    ,     .     (catch)  try - except: "  ,    - ,   ".

 9.2. ask_age.py

while True:



text = input("  ? ")



try:



age = int(text)



break



except ValueError:



print(f"'{text}' -   .   .")





print(f"    {age + 1}")

  ?  



' ' -   .   .



  ? 25 



'25 ' -   .   .



  ? 25



    26

  try  ,   .    ,  except .    try   ValueError, Python  ,    try ( break   )    except.  ,      .

 ,   except   .   ValueError,     -  .  :     ,     ,  .




  


   try   ,      except:

 9.3. divide.py

try:



total = float(input(" : "))



people = int(input(" ? "))



print(f" : {total / people:.2f} .")



except ValueError:



print("  .")



except ZeroDivisionError:



print("     .")

 : 3500



 ? 0



     .

 : 



  .

Python   except      .     ,    : except (ValueError, ZeroDivisionError):.   Python 3.14    : except ValueError, ZeroDivisionError:.      :       .

     ,    :

>>> try:



...     int("")



... except ValueError as error:



...     print(":", error)



...



: invalid literal for int() with base 10: ''

 .   except:           except Exception:   .        ,    ,      .   ,  .

  9.3.   ask_int(prompt),    ,      ,    .

  9.4.  ,           prices.   ,  KeyError   "  ".     try,   get.    ?




 else  finally



  try     .  else ,    .  finally  :   ,   .

 9.4. try_else_finally.py

def check_weight(text):



try:



weight = float(text)



except ValueError:



print(":    .")



else:



if weight > 6:



print(f"{weight}  -    .")



else:



print(f"{weight}  -   .")



finally:



print(" .")







check_weight("6.4")



check_weight("")

6.4  -    .



 .



:    .



 .

 else,        try?   try   ,      .  except ValueError       .

 finally     :  ,    ,  .  ,    try  ,    ,     .

  9.5.       9.3 ,         else,    finally  ",   !".




 



    ,   .  raise ("")  .  ,    ,     ,      ,   .

 9.5. piggy_bank.py

class NotEnoughMoneyError(Exception):



"""    ."""







def withdraw(balance, amount):



if amount <= 0:



raise ValueError("    ")



if amount > balance:



raise NotEnoughMoneyError(f"  {balance} .,  {amount}")



return balance - amount







balance = 2500



for amount in [700, -50, 3000, 1800]:



try:



balance = withdraw(balance, amount)



print(f" {amount} .,  {balance} .")



except ValueError as error:



print(":", error)



except NotEnoughMoneyError as error:



print("  :", error)

 700 .,  1800 .



:     



  :   1800 .,  3000



 1800 .,  0 .

      NotEnoughMoneyError.  class   ,        12.    :   -  ,      Exception,       .       Error.

 withdraw      ,    . Ÿ  - : " ,   ".    :           .          ,   Telegram-,   .        .

  9.6.   set_age(age),   ValueError,      150,   ,    .     25, -3  200,  .

  9.7.   FridgeEmptyError   take_from_fridge(fridge, product),      fridge   FridgeEmptyError,    .








 (debugging) -    .  bug -  "":  ,  1947       ,   ,        "  ".        - " ".




 


   -  print     ,      4.     ,    .

 9.6. average_bug.py

def average(numbers):



total = 0



for i in range(1, len(numbers)):



total += numbers[i]



return total / len(numbers)







grades = [5, 4, 3]



print(f" : {average(grades):.2f}")

 : 2.33

   5, 4  3   4,    2.33.   ,   .      print(f"{i=} {numbers[i]=} {total=}"),   ,     i=1      .    .







 (debugger) - ,          :   ,     ,   .

 VS Code        Python.    :

1.      ٸ    ,   .    -   (breakpoint).

2.       F5 ( " ?  ")   "Python Debugger: Current File".

3.          .    ""      .

4.              : F10 -    (  ), F11 -     (  ), Shift+F11 -   , F5 -     .

     total += numbers[i]   9.6   .  ,      i = 1. ,   ,   range(1, len(numbers)).




 pdb


 VS Code   ,  Python    pdb (Python debugger).   ,     breakpoint() -     ,      .

 9.7. average_pdb.py

def average(numbers):



total = 0



for i in range(1, len(numbers)):



total += numbers[i]



return total / len(numbers)







grades = [5, 4, 3]



breakpoint()



print(f" : {average(grades):.2f}")

> C:\pyprojects\average_pdb.py(9)<module>()



-> breakpoint()



(Pdb) p grades



[5, 4, 3]



(Pdb) n



> C:\pyprojects\average_pdb.py(10)<module>()



-> print(f" : {average(grades):.2f}")



(Pdb) s



--Call--



> C:\pyprojects\average_pdb.py(1)average()



-> def average(numbers):



(Pdb) n



> C:\pyprojects\average_pdb.py(2)average()



-> total = 0



(Pdb) n



> C:\pyprojects\average_pdb.py(3)average()



-> for i in range(1, len(numbers)):



(Pdb) n



> C:\pyprojects\average_pdb.py(4)average()



-> total += numbers[i]



(Pdb) p i, numbers[i], total



(1, 4, 0)



(Pdb) c



 : 2.33

  (Pdb)  ,   .   :

p  -   (print): p grades, p i, total;

n -        (next);

s -   ,      (step);

l -      (list);

c -         (continue);

q -     (quit).

   -> - ,    .  s     average,       : i  1,  ,   .  :  range(len(numbers)) ,  , for number in numbers: total += number.    - sum(numbers).   , breakpoint()   .

  9.8.     average      VS Code:       return    total  .








 ,    .       :     , -    ? -    ,     ,  .      -  (log).       logging.

 9.8. logging_demo.py

import logging





logging.basicConfig(



level=logging.INFO,



format="%(asctime)s %(levelname)s %(message)s",



datefmt="%d.%m.%Y %H:%M:%S",



)





logging.debug("  :    ")



logging.info(" ")



logging.warning("   :  2 ")





try:



portions = 10 / 0



except ZeroDivisionError:



logging.exception("   ")





logging.info(" ")

17.11.2026 12:03:19 INFO  



17.11.2026 12:03:19 WARNING    :  2 



17.11.2026 12:03:19 ERROR    



Traceback (most recent call last):



File "C:\pyprojects\logging_demo.py", line 14, in <module>



portions = 10 / 0



~~~^~~



ZeroDivisionError: division by zero



17.11.2026 12:03:19 INFO  

     .  : DEBUG (  ), INFO ( ), WARNING (), ERROR (), CRITICAL ( ).  level=logging.INFO  basicConfig : "   INFO  ".    DEBUG  .    ,     logging.DEBUG,   ,       .

 format   : , , .   ,     .  logging.exception    ERROR       .     except:   ,     ,     .

     ,   .    basicConfig   : filename="app.log"  encoding="utf-8".       app.log   ,     ,   .      :   Telegram- ( 25-26)  -CRM ( 32),  -      ( 24).

.  logging  print?        ,     ;     ;     .        print,   ,     ,  logging.

  9.9.       9.2:   INFO      WARNING    .  ,      age.log.




  :   



  2       ,       .   :     ,   ,     ,  ,   .

 9.9. dacha_trip_safe.py

def ask_number(prompt, cast=float):



"""  ,     ."""



while True:



text = input(prompt).strip().replace(",", ".")



try:



value = cast(text)



except ValueError:



print("    .   .")



continue



if value <= 0:



print("      .")



continue



return value







def main():



distance = ask_number("     , : ")



consumption = ask_number(" ,   100 : ")



fuel_price = ask_number("  , .: ")



people = ask_number("  ? ", cast=int)





cost = distance * 2 * consumption / 100 * fuel_price



print(f"\n   {cost:.2f} ., "



f"   {cost / people:.2f} .")







if __name__ == "__main__":



main()

     , : 68 



  .   .



     , : 68



 ,   100 : 8,5



  , .: 62.4



  ? 0



    .



  ? 



  .   .



  ? 3





   721.34 .,    240.45 .

 ask_number    ,     .      ,  "8,5"   .  cast -  ,     :   float,      int. ,         ,    len  str.lower   key.

    ,      .       ,   ,   .

  9.10.    ask_number  max_value     None.   ,      .  ,        30   100 .








   ( ),       ( ,  ).

   :   -  ,   -  .        .

try - except    ; as error    .    .

else ,    , finally - .

raise  ;   -  ,      Exception.    ,  ,    ,  .

 VS Code ( , F10, F11)   pdb (breakpoint(),  p, n, s, c)       .

 logging     DEBUG, INFO, WARNING, ERROR, CRITICAL; logging.exception  ;     .




 10. 



       .     6   ,   .      .     ,    .          ,    ( ,  Python 3.15   ),        ,         - CSV  JSON.




  



       : ,   , .    open.

 10.1. diary_write.py

with open("diary.txt", "w", encoding="utf-8") as file:



file.write("12 .  , 24 .\n")



file.write("13 .    .  .\n")



file.write("15 .  :  .\n")





print("   diary.txt")

   diary.txt

 open   :  ,  (mode)  .  "w" (write)  "  ":   ,   ,    - .     ,   :   encoding="utf-8".

 with ... as file:        file,      ,   .   :    ,          .  with     :  ,      .

 write  .    print,      ,       \n.

 diary.txt   ,   .        VS Code.    :

 10.2. diary_read.py

with open("diary.txt", encoding="utf-8") as file:



text = file.read()



print(text)





print(":")



with open("diary.txt", encoding="utf-8") as file:



for number, line in enumerate(file, start=1):



print(number, line.rstrip("\n"))

12 .  , 24 .



13 .    .  .



15 .  :  .





:



1 12 .  , 24 .



2 13 .    .  .



3 15 .  :  .

       ( "r", read).  read()      .      for,     .     :        .          ,      rstrip("\n").  print     ,       .




  


 "w"   .       ,   "a" (append, "").

 10.3. diary_add.py

from datetime import date





entry = input("    ? ")



with open("diary.txt", "a", encoding="utf-8") as file:



file.write(f"{date.today().strftime('%d.%m.%Y')}. {entry}\n")





with open("diary.txt", encoding="utf-8") as file:



lines = file.readlines()



print(f"  : {len(lines)}. :")



print(lines[-1].rstrip("\n"))

    ?   !



  : 4. :



19.11.2026.   !

 readlines()     ,    .        ,     .

 ,   ?   :

>>> open("nofile.txt", encoding="utf-8")



Traceback (most recent call last):



File "<python-input-0>", line 1, in <module>



open("nofile.txt", encoding="utf-8")



~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^



FileNotFoundError: [Errno 2] No such file or directory: 'nofile.txt'

FileNotFoundError - "    ".     try - except,    9,   ,   .  ,     .

  10.1.  ,              todo.txt,    ,  .

  10.2.  ,   diary.txt    ,   .

  10.3.     10.2 ,       ,   "  ".




  UTF-8  



     ,   -  (bytes).  (encoding) -  ,     .      ,    ,  . Ÿ     -  (- mojibake). ,   :

>>> data = "".encode("utf-8")



>>> data



b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'



>>> data.decode("utf-8")



''



>>> data.decode("cp1251")



'uривет'

 encode       ,  decode - .   UTF-8      ,  ""    .     Windows-1251 (cp1251) -      Windows, -  "uривет".         :    .

      UTF-8:      ,     .   Windows     cp1251,    Python     ,    . ,   ,         .

  Python 3.15.     Python   UTF-8  ,    ,   .          Windows.     Python    : encoding="utf-8".        Python 3.15,     ,      .       .

    ,      .   ,            cp1251.      UTF-8, Python   :

 10.4. encodings.py

with open("bank.txt", "w", encoding="cp1251") as file:



file.write(": , 1250 .\n")





try:



with open("bank.txt", encoding="utf-8") as file:



print(file.read())



except UnicodeDecodeError as error:



print(":", error)





with open("bank.txt", encoding="cp1251") as file:



print("  :", file.read().rstrip())

: 'utf-8' codec can't decode byte 0xd1 in position 0: invalid continuation byte



  : : , 1250 .

UnicodeDecodeError -  : " utf-8    ".       -  encoding="cp1251".   22     ,    .

  10.4.   " -  "   UTF-8  encode,      cp1251   decode   .      ?




  :  pathlib



       ,      .       ,  ,  ,   pathlib.     Path -  (path)    .

 10.5. paths.py

from pathlib import Path





folder = Path.cwd()



print(" :", folder)





report = folder / "" / ".txt"



print("  :", report)



print(" :", report.name)



print(" :", report.stem)



print(":", report.suffix)



print(" :", report.parent.name)





report.parent.mkdir(exist_ok=True)



report.write_text(" 34 600 .\n", encoding="utf-8")



print(" ?", report.exists())



print(":", report.read_text(encoding="utf-8").rstrip())

 : C:\pyprojects



  : C:\pyprojects\\.txt



 : .txt



 : 



: .txt



 : 



 ? True



:  34 600 .

Path.cwd() (current working directory)    - ,    .    /: folder / "" / ".txt".   ,  "": "  folder,   ,  .txt".  /    Windows:   Python     ,     .     \n  ,       2,   .

   : name -   , stem -   , suffix - , parent - ,    .  :

exists() -  ; is_file()  is_dir() -    ;

mkdir() -  ;  exist_ok=True  ,    ,   parents=True     ;

read_text()  write_text() -       ,  with  open;

iterdir() -   , glob("*.txt") -    ;

rename() -   , unlink() -  .

 .     data.txt,      VS Code,   ,    .   ,    "data.txt"    ,     ,   .   -    ,    : Path(__file__).parent / "data.txt".  __file__     .




   


 ""     ,    .  ,         .      ,       -.

 10.6. sort_downloads.py

from pathlib import Path





FOLDERS = {



".jpg": "",



".png": "",



".docx": "",



".pdf": "",



".xlsx": "",



".csv": "",



}





downloads = Path("_")



downloads.mkdir(exist_ok=True)



for name in [".jpg", ".pdf", ".xlsx", ".PNG",



".docx", ".mp3", ".csv"]:



(downloads / name).touch()





for file in sorted(downloads.iterdir()):



if not file.is_file():



continue



folder_name = FOLDERS.get(file.suffix.lower(), "")



target_folder = downloads / folder_name



target_folder.mkdir(exist_ok=True)



file.rename(target_folder / file.name)



print(f"{file.name:<15} -> {folder_name}")





for folder in sorted(downloads.iterdir()):



names = sorted(f.name for f in folder.iterdir())



print(f"{folder.name}: {', '.join(names)}")

.csv     -> 



.pdf     -> 



.jpg         -> 



.mp3       -> 



.docx     -> 



.PNG    -> 



.xlsx      -> 



: .pdf, .docx



: .jpg, .PNG



: .mp3



: .csv, .xlsx

 touch()    (   ,    ).      ,  ".PNG"    .    get   "".  rename     .

    sorted(...)     : f.name for f in folder.iterdir().  - (generator expression),    ,      ,     .    -   ,     .

     ,   Path("_")  Path.home() / "Downloads"    .       :   -  ,        .

  10.5.  ,       .py        . :    file.stat().st_size.

  10.6.   10.6 ,     ,          ,    -    .




CSV:   



CSV (comma-separated values, ",  ") -   .    -  ,      . CSV     Excel, LibreOffice, Google ,     -.

 ,    .    Excel  :     .   Excel      .        :

;;;



01.11.2026;;2350;



02.11.2026;;600;



03.11.2026;;890;



05.11.2026;;4120;



07.11.2026;;1500;



08.11.2026;;1890;



10.11.2026;;6800;



12.11.2026;;450;

   CSV  Python   csv.      DictReader:              .

 10.7. expenses_report.py

import csv





totals = {}



with open("expenses.csv", encoding="utf-8", newline="") as file:



for row in csv.DictReader(file, delimiter=";"):



category = row[""]



totals[category] = totals.get(category, 0) + int(row[""])





for category, amount in sorted(totals.items(), key=lambda p: -p[1]):



print(f"{category:<12}{amount:>6} .")





with open("summary.csv", "w", encoding="utf-8-sig", newline="") as file:



writer = csv.writer(file, delimiter=";")



writer.writerow(["", ""])



for category, amount in totals.items():



writer.writerow([category, amount])



print("   summary.csv")

      8360 .



    6800 .



   1500 .



           1340 .



      600 .



   summary.csv

    .

: delimiter=";" -  .     Excel -   ,  "" CSV -  (   ).

: newline=""   .  csv     ,      Python .    Windows         .

:     utf-8-sig.    UTF-8,       . Excel  Windows    ,    UTF-8.       .   : CSV  Excel   utf-8-sig.

  CSV   ,  .        int.    -p[1],      , -     .

  10.7.    expenses.csv,     .

  10.8.   CSV-    1  9 (  -   1  9)     Excel  LibreOffice.




JSON:   



CSV    .     ,      ,     ?        JSON (JavaScript Object Notation).        Python:

>>> import json



>>> pets = {"": {"": 4, "": ["", ""]}}



>>> text = json.dumps(pets, ensure_ascii=False, indent=2)



>>> print(text)



{



"": {



"": 4,



"": [



"",



""



]



}



}



>>> json.loads(text)[""][""]



4

 json.dumps (dump string)   Python   JSON,  json.loads (load string) - .  ensure_ascii=False     :    ""      \u0411\u0430....  indent=2  ,      .

 JSON   , , , , True, False  None.    ,   JSON  .  frozendict  Python 3.15    .

      json.dump  json.load (  s  ).         6  .

 10.8. phonebook_json.py

import json



from pathlib import Path





BOOK_FILE = Path("phonebook.json")







def load_book():



if not BOOK_FILE.exists():



return {}



with open(BOOK_FILE, encoding="utf-8") as file:



return json.load(file)







def save_book(book):



with open(BOOK_FILE, "w", encoding="utf-8") as file:



json.dump(book, file, ensure_ascii=False, indent=2)







def main():



book = load_book()



print(f" : {len(book)}")



while True:



command = input(" (, , ): ")



if command == "":



name = input(": ")



book[name] = input(": ")



save_book(book)



print(".")



elif command == "":



for name in sorted(book):



print(f"  {name}: {book[name]}")



elif command == "":



break







if __name__ == "__main__":



main()

 :  ,  .

 : 0



 (, , ): 



: 



: +7 900 111-22-33



.



 (, , ): 

 ,   :

 : 1



 (, , ): 



: 



: +7 495 777-88-99



.



 (, , ): 



: +7 900 111-22-33



: +7 495 777-88-99



 (, , ): 

    .       phonebook.json -       :

{



"": "+7 900 111-22-33",



"": "+7 495 777-88-99"



}

      .   -   JSON    (   -   15),    .

.     ,       .      ,    .

  10.9.      10.8  "".      .

  10.10.   JSON-   (    "", "", ""),          ,    .




 : TXT, CSV  JSON



   -  ,   : , ,   .

CSV -  ,       Excel       -.

JSON -     :    ,  .  JSON     ,       16.

           ,    .     ,    15   .








    with open(, , encoding="utf-8") as file: -    . : "r" -  ( ), "w" -   , "a" -   .

read()   ,  for - , readlines() -   ; write()      .

 -    .  Python 3.15   UTF-8   ,      ;         cp1251.

pathlib.Path -   :   /,  name, stem, suffix, parent,  exists, mkdir, iterdir, glob, read_text, write_text, rename.      : Path(__file__).parent / "".

CSV     csv  newline="";  Excel   ;,        utf-8-sig.

JSON     : json.dump  json.load  ensure_ascii=False  indent=2.




 11.   



 .    8   ,        .      :    ,       .     .          ,      , ,             .




  import



 (module) -       Python.   .py       import      .       random, datetime, json  csv,    Python.   .

 11.1. dacha_utils.py

"""   ."""





GRAMS_PER_SQ_M = 30  #      







def bed_area(length: float, width: float) -> float:



"""    ."""



return round(length * width, 2)







def fertilizer_grams(area: float) -> int:



"""     ."""



return round(area * GRAMS_PER_SQ_M)







if __name__ == "__main__":



print(" :", bed_area(4, 1.2), fertilizer_grams(4.8))

,    ,  ,    :

 11.2. plan_beds.py

import dacha_utils



from dacha_utils import bed_area as area





beds = {"": (4, 1.2), "": (3, 1), "": (5.5, 0.8)}





total = 0



for plant, (length, width) in beds.items():



size = area(length, width)



total += size



print(f"{plant:<10} {size:>5} . ")





grams = dacha_utils.fertilizer_grams(total)



print(f" {total} . ,   {grams} ")



print(f"( {dacha_utils.GRAMS_PER_SQ_M}   . )")

     4.8 . 



         3 . 



     4.4 . 



 12.2 . ,   366 



( 30   . )

    .

import dacha_utils   .      : dacha_utils.fertilizer_grams(total).  ,   .

from dacha_utils import bed_area as area           area.  as ("")   ,  .      from dacha_utils import bed_area.      : from datetime import date, timedelta.

Python        ,        .  dacha_utils.py     plan_beds.py.




 if __name__ == "__main__"


       8 .     ,  __name__  "__main__",    :

 : 4.8 144

     import, __name__   , "dacha_utils",    .    plan_beds.py  " "    .          ,   .

 .      ,    : random.py, math.py, json.py, csv.py. Python         .

  ,         random.py:

 11.3. oops/random.py

print("   random.py,    !")

 11.4. oops/game.py

import random





print(random.randint(1, 100))

   random.py,    !



Traceback (most recent call last):



File "C:\pyprojects\oops\game.py", line 3, in <module>



print(random.randint(1, 100))



^^^^^^^^^^^^^^



AttributeError: module 'random' has no attribute 'randint' (consider renaming 'C:\pyprojects\oops\random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)

Python    random,   randint    . ,   Python     : "    random.py,       ,     ".

  11.1.   cat_tools.py   cat_human_age   8   CAT_NAME = "".       :    from ... import.

  11.2.   cat_tools.py   if __name__ == "__main__":,     -. ,       .








   ,    .      (package).  Python ,   - ,     __init__.py.    ,    ,     .

 11.5. garden/__init__.py

"""   ."""

 11.6. garden/sowing.py

from datetime import date, timedelta





DAYS_TO_HARVEST = {"": 25, "": 50, "": 110}







def harvest_date(plant: str, sown: date) -> date:



return sown + timedelta(days=DAYS_TO_HARVEST[plant])

 11.7. garden/watering.py

def liters_per_day(area: float, hot: bool) -> float:



"""5    ,    ."""



return area * (10 if hot else 5)

 11.8. use_garden.py

from datetime import date





from garden import watering



from garden.sowing import harvest_date





sown = date(2026, 5, 10)



for plant in ["", "", ""]:



ready = harvest_date(plant, sown)



print(f"{plant}:   {ready.strftime('%d.%m.%Y')}")





print(f" 4.8 .   : {watering.liters_per_day(4.8, hot=True)} ")

:   04.06.2026



:   29.06.2026



:   28.08.2026



 4.8 .   : 48.0 

   :

pyprojects/



use_garden.py



garden/



__init__.py



sowing.py



watering.py

     : from garden.sowing import harvest_date - "  sowing  garden   harvest_date".  from garden import watering - "  garden   watering".

    import   .       ,   ,   ,      . Python  ,     ,   .




  .


   .

   ,     (https://www.litres.ru/book/vitalii-shefer-34217972/python-74903262/)  .

      Visa, MasterCard, Maestro,    ,   ,     ,  PayPal, WebMoney, ., QIWI ,       .


