From 1ba9ad6a3d1a8f69f60bc0f0ece1e3ee3cd3085e Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Wed, 17 Nov 2021 22:48:40 +0200 Subject: [PATCH 01/63] testimonial --- 03_Day_Operators/day-3.py | 8 ++++---- 04_Day_Strings/04_strings.md | 2 ++ 11_Day_Functions/11_functions.md | 3 +++ 30_Day_Conclusions/30_conclusions.md | 4 ++++ 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/03_Day_Operators/day-3.py b/03_Day_Operators/day-3.py index bacdf837c..b14028857 100644 --- a/03_Day_Operators/day-3.py +++ b/03_Day_Operators/day-3.py @@ -9,7 +9,7 @@ print('Division: ', 7 / 2) print('Division without the remainder: ', 7 // 2) # gives without the floating number or without the remaining print('Modulus: ', 3 % 2) # Gives the remainder -print ('Division without the remainder: ',7 // 3) +print ('Division without the remainder: ', 7 // 3) print('Exponential: ', 3 ** 2) # it means 3 * 3 # Floating numbers @@ -17,8 +17,8 @@ print('Floating Number, gravity', 9.81) # Complex numbers -print('Complex number: ', 1+1j) -print('Multiplying complex number: ',(1+1j) * (1-1j)) +print('Complex number: ', 1 + 1j) +print('Multiplying complex number: ',(1 + 1j) * (1-1j)) # Declaring the variable at the top first @@ -109,7 +109,7 @@ print('B in Asabeneh', 'B' in 'Asabeneh') # False -there is no uppercase B print('coding' in 'coding for all') # True - because coding for all has the word coding print('a in an:', 'a' in 'an') # True -print('4 is 2 ** 2:', 4 is 2 **2) # True +print('4 is 2 ** 2:', 4 is 2 ** 2) # True print(3 > 2 and 4 > 3) # True - because both statements are true print(3 > 2 and 4 < 3) # False - because the second statement is false diff --git a/04_Day_Strings/04_strings.md b/04_Day_Strings/04_strings.md index 4377d5eba..699e7ca6c 100644 --- a/04_Day_Strings/04_strings.md +++ b/04_Day_Strings/04_strings.md @@ -600,3 +600,5 @@ The area of a circle with radius 10 is 314 meters square. 🎉 CONGRATULATIONS ! 🎉 [<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_lists.md) + + diff --git a/11_Day_Functions/11_functions.md b/11_Day_Functions/11_functions.md index f7bd8f9ae..021c92a8c 100644 --- a/11_Day_Functions/11_functions.md +++ b/11_Day_Functions/11_functions.md @@ -373,6 +373,9 @@ print(do_something(square_number, 3)) # 27 🌕 You achieved quite a lot so far. Keep going! You have just completed day 11 challenges and you are 11 steps a head in to your way to greatness. Now do some exercises for your brain and muscles. +## Testimony +Now it is time to express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) + ## 💻 Exercises: Day 11 ### Exercises: Level 1 diff --git a/30_Day_Conclusions/30_conclusions.md b/30_Day_Conclusions/30_conclusions.md index 5f8f2cf21..555869b63 100644 --- a/30_Day_Conclusions/30_conclusions.md +++ b/30_Day_Conclusions/30_conclusions.md @@ -24,10 +24,14 @@ # Day 30 + ## Conclusions In the process of preparing this material I have learned quite a lot and you have inspired me to do more. Congratulations for making it to this level. If you have done all the exercise and the projects, now you are capable to go to a data analysis, data science, machine learning or web development paths. [Support the author for more educational materials](https://www.paypal.com/paypalme/asabeneh). +## Testimony +Now it is time to express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) + GIVE FEEDBACK: http://thirtydayofpython-api.herokuapp.com/feedback From ff24ab221faaec455b664ad5bbdc6e0de76c3caf Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Wed, 17 Nov 2021 22:50:22 +0200 Subject: [PATCH 02/63] testimonial --- 11_Day_Functions/11_functions.md | 2 +- 30_Day_Conclusions/30_conclusions.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/11_Day_Functions/11_functions.md b/11_Day_Functions/11_functions.md index 021c92a8c..a80e5bfb4 100644 --- a/11_Day_Functions/11_functions.md +++ b/11_Day_Functions/11_functions.md @@ -374,7 +374,7 @@ print(do_something(square_number, 3)) # 27 🌕 You achieved quite a lot so far. Keep going! You have just completed day 11 challenges and you are 11 steps a head in to your way to greatness. Now do some exercises for your brain and muscles. ## Testimony -Now it is time to express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) +Now it is time to express your thoughts about the Author and 30DaysOfPython. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) ## 💻 Exercises: Day 11 diff --git a/30_Day_Conclusions/30_conclusions.md b/30_Day_Conclusions/30_conclusions.md index 555869b63..d514eec2f 100644 --- a/30_Day_Conclusions/30_conclusions.md +++ b/30_Day_Conclusions/30_conclusions.md @@ -30,7 +30,7 @@ In the process of preparing this material I have learned quite a lot and you have inspired me to do more. Congratulations for making it to this level. If you have done all the exercise and the projects, now you are capable to go to a data analysis, data science, machine learning or web development paths. [Support the author for more educational materials](https://www.paypal.com/paypalme/asabeneh). ## Testimony -Now it is time to express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) +Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) GIVE FEEDBACK: http://thirtydayofpython-api.herokuapp.com/feedback From 870fe340a946b28abf7bc5b399e1bc7f5dc102f0 Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Wed, 7 Dec 2022 14:34:53 +0900 Subject: [PATCH 03/63] kor ver --- lang-ko/readme_ko.md | 454 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 454 insertions(+) create mode 100644 lang-ko/readme_ko.md diff --git a/lang-ko/readme_ko.md b/lang-ko/readme_ko.md new file mode 100644 index 000000000..770ee5923 --- /dev/null +++ b/lang-ko/readme_ko.md @@ -0,0 +1,454 @@ +# 🐍 30 Days Of Python + +|# Day | Topics | +|------|:---------------------------------------------------------:| +| 01 | [Introduction](./readme.md)| +| 02 | [Variables, Built-in Functions](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| +| 03 | [Operators](./03_Day_Operators/03_operators.md)| +| 04 | [Strings](./04_Day_Strings/04_strings.md)| +| 05 | [Lists](./05_Day_Lists/05_lists.md)| +| 06 | [Tuples](./06_Day_Tuples/06_tuples.md)| +| 07 | [Sets](./07_Day_Sets/07_sets.md)| +| 08 | [Dictionaries](./08_Day_Dictionaries/08_dictionaries.md)| +| 09 | [Conditionals](./09_Day_Conditionals/09_conditionals.md)| +| 10 | [Loops](./10_Day_Loops/10_loops.md)| +| 11 | [Functions](./11_Day_Functions/11_functions.md)| +| 12 | [Modules](./12_Day_Modules/12_modules.md)| +| 13 | [List Comprehension](./13_Day_List_comprehension/13_list_comprehension.md)| +| 14 | [Higher Order Functions](./14_Day_Higher_order_functions/14_higher_order_functions.md)| +| 15 | [Python Type Errors](./15_Day_Python_type_errors/15_python_type_errors.md)| +| 16 | [Python Date time](./16_Day_Python_date_time/16_python_datetime.md) | +| 17 | [Exception Handling](./17_Day_Exception_handling/17_exception_handling.md)| +| 18 | [Regular Expressions](./18_Day_Regular_expressions/18_regular_expressions.md)| +| 19 | [File Handling](./19_Day_File_handling/19_file_handling.md)| +| 20 | [Python Package Manager](./20_Day_Python_package_manager/20_python_package_manager.md)| +| 21 | [Classes and Objects](./21_Day_Classes_and_objects/21_classes_and_objects.md)| +| 22 | [Web Scraping](./22_Day_Web_scraping/22_web_scraping.md)| +| 23 | [Virtual Environment](./23_Day_Virtual_environment/23_virtual_environment.md)| +| 24 | [Statistics](./24_Day_Statistics/24_statistics.md)| +| 25 | [Pandas](./25_Day_Pandas/25_pandas.md)| +| 26 | [Python web](./26_Day_Python_web/26_python_web.md)| +| 27 | [Python with MongoDB](./27_Day_Python_with_mongodb/27_python_with_mongodb.md)| +| 28 | [API](./28_Day_API/28_API.md)| +| 29 | [Building API](./29_Day_Building_API/29_building_API.md)| +| 30 | [Conclusions](./30_Day_Conclusions/30_conclusions.md)| + +🧡🧡🧡 HAPPY CODING 🧡🧡🧡 + +
+Support the author to create more educational materials
+Paypal Logo +
+ +
+

30 Days Of Python: Day 1 - Introduction

+ + + + + Twitter Follow + + + Author: + Asabeneh Yetayeh
+ Second Edition: July, 2021 +
+
+ + +[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) + +![30DaysOfPython](./images/30DaysOfPython_banner3@2x.png) + +- [🐍 30 Days Of Python](#-30-days-of-python) +- [📘 Day 1](#-day-1) + - [환영합니다](#welcome) + - [소개](#introduction) + - [왜 Python이느냐?](#why-python-) + - [환경 설정](#environment-setup) + - [Python 설치](#installing-python) + - [Python 셸](#python-shell) + - [Visual Studio Code 설치](#installing-visual-studio-code) + - [visual studio code를 사용하기](#how-to-use-visual-studio-code) + - [Python 기본](#basic-python) + - [Python 구문](#python-syntax) + - [Python 들여쓰기](#python-indentation) + - [주석](#comments) + - [데이터 타입](#data-types) + - [Number](#number) + - [String](#string) + - [Booleans](#booleans) + - [List](#list) + - [Dictionary](#dictionary) + - [Tuple](#tuple) + - [Set](#set) + - [데이터 타입 체크](#checking-data-types) + - [Python 파일](#python-file) + - [💻 Exercises - Day 1](#-exercises---day-1) + - [Exercise: Level 1](#exercise-level-1) + - [Exercise: Level 2](#exercise-level-2) + - [Exercise: Level 3](#exercise-level-3) + +# 📘 Day 1 + +## 환영합니다 + +_30 days of Python_에 참여하기로 결정하신 것을 **축하드립니다**. 이 챌린지에서는 Python 프로그래머가 되기 위해 필요한 모든 것과 프로그래밍의 전체 개념을 배우게 됩니다. 챌린지가 끝나면 _30DaysOfPython_프로그래밍 챌린지 인증서를 받게 됩니다. + +챌린지에 적극적으로 참여하고 싶다면 [30DaysOfPython challenge](https://t.me/ThirtyDaysOfPython) 텔레그램 그룹에 가입할 수 있습니다. + +## 소개 + +Python은 범용 프로그래밍을 위한 고급 프로그래밍 언어입니다. 오픈 소스, 인터프리터, 객체 지향 프로그래밍 언어입니다. Python은 네덜란드 프로그래머 Guido van Rossum이 만들었습니다. Python 프로그래밍 언어의 이름은 영국 스케치 코미디 시리즈 *Month Python's Flying Circus* 에서 파생되었습니다. 첫 번째 버전은 1991년 2월 20일에 출시되었습니다. 이 30일간의 Python 챌린지는 최신 버전의 Python인 Python 3를 차근차근 배울 수 있도록 도와줄 것입니다. 주제는 30일로 나뉘며, 매일 이해하기 쉬운 설명, 실제 사례, 많은 실습 및 프로젝트가 포함된 여러 주제가 포함됩니다. + +이 챌린지는 Python 프로그래밍 언어를 배우고자 하는 초보자와 전문가를 위해 고안되었습니다. 챌린지를 완료하는 데 30~100일이 소요될 수 있으며 텔레그램 그룹에 적극적으로 참여하는 사람들이 챌린지를 완료할 확률이 높습니다. +시각적 학습자이거나 동영상을 선호하는 경우 이 [완전 초보를 위한 Python 동영상](https://www.youtube.com/watch?v=11OYpBrhdyM)으로 시작할 수 있습니다. + +## 왜 Python이느냐? + +인간의 언어에 매우 가깝고 배우기 쉽고 사용하기 쉬운 프로그래밍 언어입니다. +Python은 다양한 산업 및 회사(Google 포함)에서 사용됩니다. 웹 응용 프로그램, 데스크톱 응용 프로그램, 시스템 관리 및 기계 학습 라이브러리를 개발하는 데 사용되었습니다. Python은 데이터 과학 및 기계 학습 커뮤니티에서 널리 사용되는 언어입니다. 이것이 Python 학습을 시작하도록 설득하기에 충분하기를 바랍니다. Python은 세상을 지배하고 있으니 지배 당하기 전에 Python을 지배하십시오. +## 환경 설정 + +### Python 설치 + +Python 스크립트를 실행하려면 Python을 설치해야 합니다. Python을 [다운로드](https://www.python.org/)합시다. +Windows 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니다. + + + +macOS 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니다. + +[![Windows에서 설치](./images/installing_on_windows.png)](https://www.python.org/) + +Python이 설치되어 있는지 확인하려면 장치 터미널에 다음 명령을 작성하십시오. + +```shell +python --version +``` + +![Python Version](./images/python_versio.png) + +터미널에서 보시다시피 저는 현재 _Python 3.7.5_ 버전을 사용하고 있습니다. 귀하의 Python 버전은 내 버전과 다를 수 있지만 3.6 이상이어야 합니다. Python 버전을 볼 수 있다면 잘한 것입니다. 이제 컴퓨터에 Python이 설치되었습니다. 다음 섹션으로 계속 진행하십시오. + +### Python 셸 + +Python은 해석된 스크립팅 언어이므로 컴파일할 필요가 없습니다. 코드를 한 줄씩 실행한다는 의미입니다. Python은 _Python Shell(Python Interactive Shell)_과 함께 제공됩니다. 단일 Python 명령을 실행하고 결과를 얻는 데 사용됩니다. + +Python Shell은 사용자의 Python 코드를 기다립니다. 코드를 입력하면 코드를 해석하여 다음 줄에 결과를 표시합니다. +터미널이나 명령 프롬프트(cmd)를 열고 쓰기: + +```shell +python +``` + +![Python Scripting Shell](./images/opening_python_shell.png) + +Python 대화형 셸이 열리고 Python 코드(Python 스크립트)를 작성하기를 기다립니다. 기호 >>> 옆에 Python 스크립트를 작성하고 Enter를 누릅니다. +Python 스크립팅 셸에서 첫 번째 스크립트를 작성해 보겠습니다. + +![Python script on Python shell](./images/adding_on_python_shell.png) + +훌륭합니다. Python 대화형 셸에서 첫 번째 Python 스크립트를 작성했습니다. Python 대화형 셸을 어떻게 닫습니까? +셸을 닫으려면 기호 옆에 >> **exit()** 명령을 작성하고 Enter 키를 누릅니다. + +![Exit from python shell](./images/exit_from_shell.png) + +이제 Python 대화형 셸을 여는 방법과 종료하는 방법을 알았습니다. + +Python은 Python이 이해하는 스크립트를 작성하면 결과를 제공하고 그렇지 않으면 오류를 반환합니다. 고의적인 실수를 하고 Python이 무엇을 반환하는지 봅시다. + +![Invalid Syntax Error](./images/invalid_syntax_error.png) + +반환된 오류에서 볼 수 있듯이 Python은 우리가 저지른 실수와 _Syntax Error: invalid syntax_를 알고 있을 정도로 영리합니다. Python에서 x를 곱셈으로 사용하는 것은 (x)가 Python에서 유효한 구문이 아니기 때문에 구문 오류입니다. (**x**) 대신 곱셈에 별표(*)를 사용합니다. 반환된 오류는 수정해야 할 사항을 명확하게 보여줍니다. + +프로그램에서 오류를 식별하고 제거하는 프로세스를 *디버깅*이라고 합니다. **x** 대신 *를 넣어 디버깅해 봅시다. + +![Fixing Syntax Error](./images/fixing_syntax_error.png) + +버그가 수정되었고 코드가 실행되었으며 예상했던 결과를 얻었습니다. 프로그래머로서 매일 이러한 종류의 오류를 보게 될 것입니다. 디버깅 방법을 아는 것이 좋습니다. 디버깅을 잘하려면 어떤 종류의 오류가 발생했는지 이해해야 합니다. 발생할 수 있는 Python 오류 중 일부는 *SyntaxError*, *IndexError*, *NameError*, *ModuleNotFoundError*, *KeyError*, *ImportError*, *AttributeError*, *TypeError*, *ValueError*, *ZeroDivisionError* 등입니다. 이후 섹션에서 다른 Python **_오류 유형_**에 대해 자세히 알아볼 것입니다. + +Python 대화형 셸을 사용하는 방법을 더 연습해 보겠습니다. 터미널이나 명령 프롬프트로 이동하여 **python**이라는 단어를 씁니다. + +![Python Scripting Shell](./images/opening_python_shell.png) + +Python 대화형 셸이 열립니다. 몇 가지 기본적인 수학 연산(더하기, 빼기, 곱하기, 나누기, 나머지, 지수)을 수행해 보겠습니다. + +Python 코드를 작성하기 전에 먼저 몇 가지 수학을 수행해 보겠습니다: + +- 2 + 3 = 5 +- 3 - 2 = 1 +- 3 \* 2 = 6 +- 3 / 2 = 1.5 +- 3 ^ 2 = 3 x 3 = 9 + +Python에는 다음과 같은 추가 작업이 있습니다: + +- 3 % 2 = 1 => 나머지를 구함 +- 3 // 2 = 1 => 나머지를 제거 + +위의 수학식을 Python 코드로 바꿔봅시다. Python 셸이 열렸으며 셸 맨 처음에 주석을 작성하겠습니다. + +_comment_는 Python에 의해 실행되지 않는 코드의 일부입니다. 따라서 코드를 더 읽기 쉽게 만들기 위해 코드에 일부 텍스트를 남길 수 있습니다. Python은 주석 부분을 실행하지 않습니다. Python에서 주석은 해시(#) 기호로 시작합니다. +이것이 Python에서 주석을 작성하는 방법입니다 + +```shell + # 주석은 해시로 시작합니다. + # (#) 심볼로 시작하기 때문에 이것은 파이썬 주석입니다. +``` + +![Maths on python shell](./images/maths_on_python_shell.png) + +다음 섹션으로 이동하기 전에 Python 대화형 셸에서 더 많은 연습을 해 보겠습니다. 셸에서 _exit()_를 작성하여 열린 셸을 닫았다가 다시 열어 Python 셸에서 텍스트를 쓰는 방법을 연습해 봅시다. + +![Writing String on python shell](./images/writing_string_on_shell.png) + +### Visual Studio Code 설치 + +Python 대화형 셸은 작은 스크립트 코드를 시도하고 테스트하는 데 적합하지만 큰 프로젝트에는 적합하지 않습니다. 실제 작업 환경에서 개발자는 다양한 코드 편집기를 사용하여 코드를 작성합니다. 이 30일간의 Python 프로그래밍 챌린지에서는 Visual Studio 코드를 사용합니다. Visual Studio Code는 매우 인기 있는 오픈 소스 텍스트 편집기입니다. 나는 vscode의 팬이고 Visual Studio 코드를 [다운로드](https://code.visualstudio.com/)하는 것을 추천하고 싶지만, 다른 편집자를 선호한다면 가지고 있는 것을 자유롭게 따르십시오. + +[![Visual Studio Code](./images/vscode.png)](https://code.visualstudio.com/) + +Visual Studio Code를 설치하셨다면 어떻게 사용하는지 알아보겠습니다. +비디오를 선호하는 경우 Python용 Visual Studio Code[비디오 자습서](https://www.youtube.com/watch?v=bn7Cx4z-vSo)를 따를 수 있습니다. + +#### visual studio code를 사용하기 + +Visual Studio 아이콘을 두 번 클릭하여 Visual Studio 코드를 엽니다. 열면 이런 종류의 인터페이스가 나타납니다. 레이블이 지정된 아이콘을 따라해보세요. + +![Visual studio Code](./images/vscode_ui.png) + +바탕 화면에 30DaysOfPython이라는 폴더를 만듭니다. 그런 다음 Visual Studio 코드를 사용하여 엽시다. + +![Opening Project on Visual studio](./images/how_to_open_project_on_vscode.png) + +![Opening a project](./images/opening_project.png) + +파일을 열면 30DaysOfPython 프로젝트의 디렉토리 내부에 파일과 폴더를 생성하기 위한 바로 가기가 표시됩니다. 아래에서 볼 수 있듯이 첫 번째 파일인 helloworld.py를 만들었습니다. 당신도 똑같이 할 수 있습니다. + +![Creating a python file](./images/helloworld.png) + +하루동안 오래 코딩을 한 후에 코드 편집기를 닫고 싶습니까? 이렇게 열린 프로젝트를 닫으면 됩니다. + +![Closing project](./images/closing_opened_project.png) + +축하합니다. 개발 환경 설정을 완료했습니다. 코딩을 시작해 봅시다. + +## Python 기본 + +### Python 구문 + +Python 스크립트는 Python 대화형 셸 또는 코드 편집기에서 작성할 수 있습니다. Python 파일의 확장자는 .py입니다. + +### Python 들여 쓰기 + +들여쓰기는 텍스트의 공백입니다. 많은 언어에서 들여쓰기는 코드 가독성을 높이는 데 사용되지만 Python은 들여쓰기를 사용하여 코드 블록을 만듭니다. 다른 프로그래밍 언어에서는 중괄호를 사용하여 들여쓰기 대신 코드 블록을 만듭니다. Python 코드를 작성할 때 흔히 발생하는 버그 중 하나는 잘못된 들여쓰기입니다. + +![Indentation Error](./images/indentation.png) + +### 주석 + +주석은 코드를 더 읽기 쉽게 만들고 코드에 설명을 남기기 위해 매우 중요합니다. Python은 코드의 주석 부분을 실행하지 않습니다. +Python에서 해시(#)로 시작하는 모든 텍스트는 주석입니다. + +**예시:한 문장 주석** + +```shell + # This is the first comment + # This is the second comment + # Python is eating the world +``` + +**예시: 여러 문장 주석** + +Triple quote can be used for multiline comment if it is not assigned to a variable + +```shell +"""This is multiline comment +multiline comment takes multiple lines. +python is eating the world +""" +``` + +### 데이터 타입 + +Python에는 여러 유형의 데이터 유형이 있습니다. 가장 일반적인 것부터 시작하겠습니다. 다른 데이터 유형은 다른 섹션에서 자세히 다룰 것입니다. 당분간 다양한 데이터 유형을 살펴보고 익숙해지도록 합시다. 지금은 명확하게 이해하지 않아도 됩니다. + +#### Number + +- Integer: 정수(음수, 영 그리고 양수) + 예시: + ... -3, -2, -1, 0, 1, 2, 3 ... +- Float: 십진수 + 예시 + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... +- Complex + 예시 + 1 + j, 2 + 4j + +#### String + +작은따옴표 또는 큰따옴표 아래에 있는 하나 이상의 문자 모음입니다. 문자열이 두 문장 이상인 경우 삼중 따옴표를 사용합니다. + +**예시:** + +```py +'Asabeneh' +'Finland' +'Python' +'I love teaching' +'I hope you are enjoying the first day of 30DaysOfPython Challenge' +``` + +#### Boolean + +부울 데이터 유형은 True 또는 False 값입니다. T와 F는 항상 대문자여야 합니다. + +**예시:** + +```python + True # 불이 켜져있나요? 그러면 참입니다. + False # 불이 꺼져있나요? 그러면 거짓입니다. +``` + +#### List + +Python 리스트는 다른 데이터 유형 항목을 저장할 수 있는 정렬된 컬렉션입니다. 리스트는 JavaScript의 배열과 비슷합니다. + +**Example:** + +```py +[0, 1, 2, 3, 4, 5] # 모두 동일한 데이터 유형 - 숫자 리스트 +['Banana', 'Orange', 'Mango', 'Avocado'] # 모두 동일한 데이터 유형 - 문자열 리스트(과일) +['Finland','Estonia', 'Sweden','Norway'] # 모두 동일한 데이터 유형 - 문자열 리스트(국가) +['Banana', 10, False, 9.81] # 리스트의 다양한 데이터 유형 - 문자열, 정수, 부울 및 부동 소수점 +``` + +#### Dictionary + +Python 사전 개체는 키 값 쌍 형식의 정렬되지 않은 데이터 모음입니다. + +**Example:** + +```py +{ +'first_name':'Asabeneh', +'last_name':'Yetayeh', +'country':'Finland', +'age':250, +'is_married':True, +'skills':['JS', 'React', 'Node', 'Python'] +} +``` + +#### Tuple + +튜플은 목록과 같은 다양한 데이터 유형의 정렬된 모음이지만 튜플이 생성되면 수정할 수 없습니다. 그것들은 변할 수 없습니다. + +**Example:** + +```py +('Asabeneh', 'Pawel', 'Brook', 'Abraham', 'Lidiya') # Names +``` + +```py +('Earth', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Saturn', 'Uranus', 'Mercury') # planets +``` + +#### Set + +집합은 목록 및 튜플과 유사한 데이터 유형의 모음입니다. 목록 및 튜플과 달리 집합은 순서가 지정된 항목 모음이 아닙니다. 수학에서와 마찬가지로 Python에서 set은 고유한 항목만 저장합니다. + +이후 섹션에서는 각각의 모든 Python 데이터 유형에 대해 자세히 설명합니다. + +**Example:** + +```py +{2, 4, 3, 5} +{3.14, 9.81, 2.7} # order is not important in set +``` + +### 데이터 타입 체크 + +특정 데이터/변수의 데이터 유형을 확인하기 위해 **type** 기능을 사용합니다. 다음 터미널에서 다양한 Python 데이터 유형을 볼 수 있습니다: + +![Checking Data types](./images/checking_data_types.png) + +### Python 파일 + +먼저 프로젝트 폴더인 30DaysOfPython을 엽니다. 이 폴더가 없으면 30DaysOfPython이라는 폴더 이름을 만듭니다. 이 폴더 안에 helloworld.py라는 파일을 만듭니다. 이제 Visual Studio 코드를 사용하여 Python 대화형 셸에서 수행한 작업을 수행해 보겠습니다. + +Python 대화형 셸은 **print**를 사용하지 않고 인쇄했지만 Visual Studio 코드에서 결과를 보려면 내장 함수 *print()를 사용해야 합니다. *print()* 내장 함수는 *print('arument1', 'argument2', 'argument3')*와 같이 하나 이상의 인수를 사용합니다. 아래 예를 참조하십시오. + +**Example:** + +파일 이름은 helloworld.py. + +```py +# Day 1 - 30DaysOfPython Challenge + +print(2 + 3) # addition(+) +print(3 - 1) # subtraction(-) +print(2 * 3) # multiplication(*) +print(3 / 2) # division(/) +print(3 ** 2) # exponential(**) +print(3 % 2) # modulus(%) +print(3 // 2) # Floor division operator(//) + +# Checking data types +print(type(10)) # Int +print(type(3.14)) # Float +print(type(1 + 3j)) # Complex number +print(type('Asabeneh')) # String +print(type([1, 2, 3])) # List +print(type({'name':'Asabeneh'})) # Dictionary +print(type({9.8, 3.14, 2.7})) # Set +print(type((9.8, 3.14, 2.7))) # Tuple +``` + +Python 파일을 실행하려면 아래 이미지를 확인하세요. Visual Studio Code에서 녹색 버튼을 실행하거나 터미널에 *python helloworld.py*를 입력하여 Python 파일을 실행할 수 있습니다. + +![Running python script](./images/running_python_script.png) + +🌕 좋습니다. 당신은 방금 1일차 도전을 완료했고 당신은 위대한 여정에 있습니다. 이제 뇌와 근육을 위한 몇 가지 훈련을 해봅시다. + +## 💻 Exercises - Day 1 + +### Exercise: Level 1 + +1. 사용 중인 Python 버전 확인 +2. Python 대화형 셸을 열고 다음 작업을 수행합니다. 피연산자는 3과 4입니다. + - 더하기(+) + - 빼기(-) + - 곱하기(\*) + - 나머지(%) + - 나누기(/) + - 지수(\*\*) + - 정수 나누기(//) +3. Python 대화형 셸에 문자열을 씁니다. 문자열은 다음과 같습니다: + - 이름 + - 가족 이름 + - 국가 이름 + - I am enjoying 30 days of python +4. 다음 데이터의 데이터 유형을 확인하십시오.: + - 10 + - 9.8 + - 3.14 + - 4 - 4j + - ['Asabeneh', 'Python', 'Finland'] + - 이름 + - 가족 이름 + - 국가 이름 + +### Exercise: Level 2 + +1. 30DaysOfPython 폴더 안에 day_1이라는 폴더를 만듭니다. day_1 폴더 안에 python 파일 helloworld.py를 만들고 질문 1, 2, 3, 4를 반복하세요. Python 파일에서 작업할 때 _print()_를 사용하는 것을 잊지 마세요. 파일을 저장한 디렉토리로 이동하여 실행합니다. + +### Exercise: Level 3 + +1. Number(Integer, Float, Complex), String, Boolean, List, Tuple, Set 및 Dictionary와 같은 다양한 Python 데이터 유형에 대한 예제를 작성합니다. +2. 참고 [Euclidian distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) (2, 3) 과 (10, 8) 사이 + +🎉 축하합니다 ! 🎉 + +[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) \ No newline at end of file From 5051d4916aa90c2afad4b8ed6aad73474a5b3342 Mon Sep 17 00:00:00 2001 From: ShinYooJung Date: Wed, 7 Dec 2022 17:28:02 +0900 Subject: [PATCH 04/63] Add Day 2 Korean Translation --- .../02_variables_builtin_functions.md | 317 ++++++++++++++++++ 1 file changed, 317 insertions(+) create mode 100644 Korean/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md diff --git a/Korean/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md b/Korean/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md new file mode 100644 index 000000000..0e8506b28 --- /dev/null +++ b/Korean/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md @@ -0,0 +1,317 @@ +
+

30 Days Of Python: Day 2 - 변수, 내장 함수

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ Second Edition: July, 2021 +
+ +
+ +[<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md) + +![30DaysOfPython](../../images/30DaysOfPython_banner3@2x.png) + +- [📘 Day 2](#-day-2) + - [내장 함수](#내장-함수) + - [변수](#변수) + - [한 줄로 여러개의 변수 선언](#한-줄로-여러개의-변수-선언) + - [자료형](#자료형) + - [자료형 확인 및 형변환](#자료형-확인-및-형변환) + - [숫자](#숫자) + - [💻 Exercises - Day 2](#-exercises---day-2) + - [Exercises: Level 1](#exercises-level-1) + - [Exercises: Level 2](#exercises-level-2) + +# 📘 Day 2 + +## 내장 함수 + +파이썬에는 수많은 내장 함수가 있습니다. 내장 함수는 전역에서 사용 가능하고 그건 importing 이나 configuring없이 내장 함수를 사용 가능하다는 뜻입니다. 다음은 가장 자주 사용되는 파이썬 내장함수들 중 몇가지입니다: _print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_, and _dir()_. 밑의 표에서 [파이썬 공식문서](https://docs.python.org/3.9/library/functions.html) 에 쓰여진 파이썬 내장 함수의 전체 목록을 볼 수 있습니다. + +![Built-in Functions](../../images/builtin-functions.png) + +파이썬 쉘을 열고 가장 자주 사용되는 내장 함수를 사용해봅시다. + +![Built-in functions](../../images/builtin-functions_practice.png) + +다른 내장 함수를 사용해 더 연습해봅시다. + +![Help and Dir Built in Functions](../../images/help_and_dir_builtin.png) + +위의 터미널에서 볼 수 있듯이, 파이썬에는 reserved word가 있습니다. reserved word는 변수나 함수를 선언할때 사용되지 않습니다. 변수에 관해서는 다음 장에서 다룰것입니다. + +이제 당신은 내장 함수에 익숙해졌을 것이라 믿습니다. 한번 더 내장 함수의 연습을 하고 다음 장으로 넘어갑시다. +![Min Max Sum](../../images/builtin-functional-final.png) + +## 변수 + +변수는 컴퓨터 메모리에 정보를 저장합니다. Mnemonic 변수는 많은 프로그래밍 언어에서 사용하도록 권장됩니다. Mnemonic 변수는 쉽게 기억하고 연관지을 수 있는 변수 이름입니다. 한 변수는 정보가 저장되어있는 메모리 주소를 참조합니다. +변수 이름을 지정할 때는 시작 부분의 숫자, 특수 문자, 하이픈을 사용할 수 없습니다. 변수는 짧은 이름(예: x, y, z)을 가질 수 있지만 더 변수에 대한 설명을 담은 이름(이름, 성, 나이, 국가)을 사용하는 것을 추천합니다. + +파이썬 변수 이름 규칙 + +- 변수 이름은 문자 또는 밑줄 문자로 시작해야 합니다 +- 변수 이름은 숫자로 시작할 수 없습니다 +- 변수 이름에는 알파벳과 숫자와 밑줄(A-z, 0-9 및 \_)만 사용할 수 있습니다 +- 변수 이름은 대소문자를 구분합니다(firstname, Firstname, FirstName, FIRSTNAME은 서로 다른 변수) + +사용가능한 변수 이름들을 살펴봅시다 + +```shell +firstname +lastname +age +country +city +first_name +last_name +capital_city +_if # reserved word를 변수 이름으로 사용하고 싶은 경우 +year_2021 +year2021 +current_year_2021 +birth_year +num1 +num2 +``` + +사용할 수 없는 변수 이름들 + +```shell +first-name +first@name +first$name +num-1 +1num +``` + +우리는 많은 파이썬 개발자들이 채택한 표준 파이썬 변수 명명 방식을 사용할 것입니다. 파이썬 개발자들은 스네이크 케이스(snake_case) 변수 명명 규칙을 사용합니다. 우리는 두 개 이상의 단어를 포함하는 변수에 대해 각 단어 뒤에 밑줄 문자를 사용합니다(예: first_name, last_name, engine_rotation_speed). 아래 예제는 변수의 표준 명명 예제이며, 변수 이름이 둘 이상의 단어일 경우 밑줄이 필요합니다. + +변수에 특정 데이터 유형을 할당할 때 이를 변수 선언이라고 합니다. 예를 들어 아래 예제에서 내 이름은 first_name 변수에 할당됩니다. 등호 기호는 할당 연산자입니다. 할당은 변수에 데이터를 저장하는 것을 의미합니다. 파이썬에서 등호 기호는 수학에서의 등호가 아닙니다. + +_Example:_ + +```py +# Variables in Python +first_name = 'Asabeneh' +last_name = 'Yetayeh' +country = 'Finland' +city = 'Helsinki' +age = 250 +is_married = True +skills = ['HTML', 'CSS', 'JS', 'React', 'Python'] +person_info = { + 'firstname':'Asabeneh', + 'lastname':'Yetayeh', + 'country':'Finland', + 'city':'Helsinki' + } +``` + +내장 함수인 _print()_ 와 _len()_ 을 사용해봅시다. Print 함수는 인자의 수에 제한이 없습니다. 인자는 함수 괄호 안에 넣어 전달할 수 있는 값입니다. 아래 예제를 봅시다. + +**Example:** + +```py +print('Hello, World!') # Hello, World! 라는 글이 하나의 인자입니다 +print('Hello',',', 'World','!') # 여러개의 인자를 받을 수 있습니다, 네개의 인자가 넘겨졌습니다 +print(len('Hello, World!')) # 하나의 인자만을 받습니다 +``` + +위에서 정의된 변수들을 찍어보고 길이를 찾아봅시다: + +**Example:** + +```py +# 변수에 저장된 값 찍기 + +print('First name:', first_name) +print('First name length:', len(first_name)) +print('Last name: ', last_name) +print('Last name length: ', len(last_name)) +print('Country: ', country) +print('City: ', city) +print('Age: ', age) +print('Married: ', is_married) +print('Skills: ', skills) +print('Person information: ', person_info) +``` + +### 한 줄로 여러개의 변수 선언 + +하나의 줄에서 여러개의 변수를 선언할 수도 있습니다: + +**Example:** + +```py +first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True + +print(first_name, last_name, country, age, is_married) +print('First name:', first_name) +print('Last name: ', last_name) +print('Country: ', country) +print('Age: ', age) +print('Married: ', is_married) +``` + +내장 함수 _input()_ 을 사용해 사용자의 입력 받기. 사용자로부터 받은 정보를 first_name과 age 변수에 할당해봅시다. +**Example:** + +```py +first_name = input('What is your name: ') +age = input('How old are you? ') + +print(first_name) +print(age) +``` + +## 자료형 + +파이썬에는 몇 가지 자료형이 있습니다. 자료형을 식별하기 위해 내장 함수 _type()_ 을 사용합니다. 서로 다른 자료형을 잘 이해하는 데 집중해 주시기를 부탁드립니다. 프로그래밍에서 모든것은 자료형과 관련이 있습니다. 처음에 자료형을 소개했지만 모든 주제가 자료형과 관련이 있기 때문에 다시 나옵니다. 자료형에 대해서는 각 섹션에서 자세히 설명하겠습니다. + +## 자료형 확인 및 형변환 + +- 자료형 확인: 특정 정보/변수의 자료형을 확인하기위해 우리는 _type()_ 을 사용합니다 + **Example:** + +```py +# 다양한 파이썬 자료형 +# 다양한 자료형의 변수들을 선언해 봅시다. + +first_name = 'Asabeneh' # str +last_name = 'Yetayeh' # str +country = 'Finland' # str +city= 'Helsinki' # str +age = 250 # int, 제 실제 나이가 아닙니다, 걱정마세요 + +# Printing out types +print(type('Asabeneh')) # str +print(type(first_name)) # str +print(type(10)) # int +print(type(3.14)) # float +print(type(1 + 1j)) # complex +print(type(True)) # bool +print(type([1, 2, 3, 4])) # list +print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict +print(type((1,2))) # tuple +print(type(zip([1,2],[3,4]))) # set +``` + +- 형변환: 하나의 자료형을 다른 자료형으로 변환합니다. _int()_, _float()_, _str()_, _list_, _set_ 를 사용합니다. + 산술 연산을 수행할 때 문자열 숫자들을 먼저 int 나 float로 변환해야 합니다. 그렇지 않으면 오류가 반환됩니다. 만약 숫자를 문자열과 결합한다면, 그 숫자는 먼저 문자열로 변환되어야 합니다. 결합에 대해서는 String 섹션에서 설명하겠습니다. + + **Example:** + +```py +# int to float +num_int = 10 +print('num_int',num_int) # 10 +num_float = float(num_int) +print('num_float:', num_float) # 10.0 + +# float to int +gravity = 9.81 +print(int(gravity)) # 9 + +# int to str +num_int = 10 +print(num_int) # 10 +num_str = str(num_int) +print(num_str) # '10' + +# str to int or float +num_str = '10.6' +print('num_int', int(num_str)) # 10 +print('num_float', float(num_str)) # 10.6 + +# str to list +first_name = 'Asabeneh' +print(first_name) # 'Asabeneh' +first_name_to_list = list(first_name) +print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h'] +``` + +## 숫자 + +파이썬의 숫자 자료형: + +1. Integers: 정수(음수, 0 , 양수) + 예: + ... -3, -2, -1, 0, 1, 2, 3 ... + +2. 부동 소수점 숫자(10진수) + 예: + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... + +3. 복소수 + 예: + 1 + j, 2 + 4j, 1 - 1j + +🌕 당신은 정말 멋집니다. 여러분은 이제 막 2일차 도전을 마쳤고 위대함으로 가는 길에 두 걸음 앞서 있습니다. 이제 여러분의 뇌와 근육을 위한 운동을 하세요. + +## 💻 Exercises - Day 2 + +### Exercises: Level 1 + +1. 30DaysOfPython 내에 day_2라는 폴더를 생성하세요. 그 폴더 내에 variables.py 라는 파일을 생성하세요. +2. 'Day 2: 30 Days of python programming'이라는 파이썬 주석을 작성합니다. +3. first name 변수를 선언하고 변수에 값을 할당합니다. +4. last name 변수를 선언하고 변수에 값을 할당합니다. +5. full name 변수를 선언하고 변수에 값을 할당합니다. +6. country 변수를 선언하고 값을 할당합니다. +7. city 변수를 선언하고 값을 할당합니다. +8. age 변수를 선언하고 값을 할당합니다. +9. year 변수를 선언하고 값을 할당합니다. +10. is_married 변수를 선언하고 값을 할당합니다. +11. is_true 변수를 선언하고 값을 할당합니다. +12. is_light_on 변수를 선언하고 값을 할당합니다. +13. 한 줄에 여러개의 변수를 선언합니다. + +### Exercises: Level 2 + +1. Check the data type of all your variables using type() built-in function +1. Using the _len()_ built-in function, find the length of your first name +1. Compare the length of your first name and your last name +1. Declare 5 as num_one and 4 as num_two + 1. Add num_one and num_two and assign the value to a variable total + 2. Subtract num_two from num_one and assign the value to a variable diff + 3. Multiply num_two and num_one and assign the value to a variable product + 4. Divide num_one by num_two and assign the value to a variable division + 5. Use modulus division to find num_two divided by num_one and assign the value to a variable remainder + 6. Calculate num_one to the power of num_two and assign the value to a variable exp + 7. Find floor division of num_one by num_two and assign the value to a variable floor_division +1. The radius of a circle is 30 meters. + 1. Calculate the area of a circle and assign the value to a variable name of _area_of_circle_ + 2. Calculate the circumference of a circle and assign the value to a variable name of _circum_of_circle_ + 3. Take radius as user input and calculate the area. +1. Use the built-in input function to get first name, last name, country and age from a user and store the value to their corresponding variable names +1. Run help('keywords') in Python shell or in your file to check for the Python reserved words or keywords + +1. type() 내장 함수를 사용하여 모든 변수의 자료형을 확인합니다. +1. _len()_ 내장 함수를 사용하여 당신의 first name 의 길이를 찾습니다. +1. 당신의 first name 과 last name 의 길이를 비교합니다. +1. 5를 num_1로, 4를 num_2로 선언합니다. + 1. num_one과 num_two를 더하고 그 값을 변수 total 에 할당합니다. + 2. num_1에서 num_2를 빼고 그 값을 변수 diff 에 할당합니다. + 3. num_two와 num_one을 곱하여 그 값을 변수 product 에 할당합니다. + 4. num_one을 num_two로 나누고 그 값을 변수 division 에 할당합니다. + 5. 나머지 연산을 사용하여 num_two를 num_one으로 나눈 값을 찾고 변수 remainder 에 할당합니다. + 6. num_one을 num_two의 거듭제곱으로 계산하고 그 값을 변수 exp 에 할당합니다. + 7. num_one을 num_two로 나누고 소숫값은 버린 정수 값을 구하고 변수 floor_division 에 값을 할당합니다. +1. 원의 반지름은 30미터입니다. + 1. 원의 면적을 계산하여 _area_of_circle_ 이라는 이름의 변수에 값을 할당합니다. + 2. 원의 둘레를 계산하여 _circum_of_circum_ 이라는 이름의 변수에 값을 할당합니다. + 3. 반경을 사용자 입력으로 받아서 면적을 계산합니다. +1. 내장 함수 input을 사용하여 사용자로부터 이름, 성, 국가 및 나이를 얻고 해당 변수 이름에 값을 저장합니다. +1. Python 셸 또는 파일에서 help('keywords')을 실행하여 파이썬의 reserved words 또는 키워드를 확인합니다. + +🎉 축하합니다 ! 🎉 + +[<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md) From e708e3086d9eeebd81a3a2951b58c786d4af2117 Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Wed, 7 Dec 2022 19:36:46 +0900 Subject: [PATCH 05/63] Create korean --- korean | 1 + 1 file changed, 1 insertion(+) create mode 100644 korean diff --git a/korean b/korean new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/korean @@ -0,0 +1 @@ + From c1364a4a5ec8f1c8dc4819620ca68690ac6377d6 Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Thu, 8 Dec 2022 13:13:09 +0900 Subject: [PATCH 06/63] lang ko --- lang-ko/readme_ko.md | 136 +++++++++++++++++++++---------------------- 1 file changed, 68 insertions(+), 68 deletions(-) diff --git a/lang-ko/readme_ko.md b/lang-ko/readme_ko.md index 770ee5923..558efe95f 100644 --- a/lang-ko/readme_ko.md +++ b/lang-ko/readme_ko.md @@ -2,42 +2,42 @@ |# Day | Topics | |------|:---------------------------------------------------------:| -| 01 | [Introduction](./readme.md)| -| 02 | [Variables, Built-in Functions](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| -| 03 | [Operators](./03_Day_Operators/03_operators.md)| -| 04 | [Strings](./04_Day_Strings/04_strings.md)| -| 05 | [Lists](./05_Day_Lists/05_lists.md)| -| 06 | [Tuples](./06_Day_Tuples/06_tuples.md)| -| 07 | [Sets](./07_Day_Sets/07_sets.md)| -| 08 | [Dictionaries](./08_Day_Dictionaries/08_dictionaries.md)| -| 09 | [Conditionals](./09_Day_Conditionals/09_conditionals.md)| -| 10 | [Loops](./10_Day_Loops/10_loops.md)| -| 11 | [Functions](./11_Day_Functions/11_functions.md)| -| 12 | [Modules](./12_Day_Modules/12_modules.md)| -| 13 | [List Comprehension](./13_Day_List_comprehension/13_list_comprehension.md)| -| 14 | [Higher Order Functions](./14_Day_Higher_order_functions/14_higher_order_functions.md)| -| 15 | [Python Type Errors](./15_Day_Python_type_errors/15_python_type_errors.md)| -| 16 | [Python Date time](./16_Day_Python_date_time/16_python_datetime.md) | -| 17 | [Exception Handling](./17_Day_Exception_handling/17_exception_handling.md)| -| 18 | [Regular Expressions](./18_Day_Regular_expressions/18_regular_expressions.md)| -| 19 | [File Handling](./19_Day_File_handling/19_file_handling.md)| -| 20 | [Python Package Manager](./20_Day_Python_package_manager/20_python_package_manager.md)| -| 21 | [Classes and Objects](./21_Day_Classes_and_objects/21_classes_and_objects.md)| -| 22 | [Web Scraping](./22_Day_Web_scraping/22_web_scraping.md)| -| 23 | [Virtual Environment](./23_Day_Virtual_environment/23_virtual_environment.md)| -| 24 | [Statistics](./24_Day_Statistics/24_statistics.md)| -| 25 | [Pandas](./25_Day_Pandas/25_pandas.md)| -| 26 | [Python web](./26_Day_Python_web/26_python_web.md)| -| 27 | [Python with MongoDB](./27_Day_Python_with_mongodb/27_python_with_mongodb.md)| -| 28 | [API](./28_Day_API/28_API.md)| -| 29 | [Building API](./29_Day_Building_API/29_building_API.md)| -| 30 | [Conclusions](./30_Day_Conclusions/30_conclusions.md)| +| 01 | [Introduction](../readme_ko.md)| +| 02 | [Variables, Built-in Functions](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| +| 03 | [Operators](../03_Day_Operators/03_operators.md)| +| 04 | [Strings](../04_Day_Strings/04_strings.md)| +| 05 | [Lists](../05_Day_Lists/05_lists.md)| +| 06 | [Tuples](../06_Day_Tuples/06_tuples.md)| +| 07 | [Sets](../07_Day_Sets/07_sets.md)| +| 08 | [Dictionaries](../08_Day_Dictionaries/08_dictionaries.md)| +| 09 | [Conditionals](../09_Day_Conditionals/09_conditionals.md)| +| 10 | [Loops](../10_Day_Loops/10_loops.md)| +| 11 | [Functions](../11_Day_Functions/11_functions.md)| +| 12 | [Modules](../12_Day_Modules/12_modules.md)| +| 13 | [List Comprehension](../13_Day_List_comprehension/13_list_comprehension.md)| +| 14 | [Higher Order Functions](../14_Day_Higher_order_functions/14_higher_order_functions.md)| +| 15 | [Python Type Errors](../15_Day_Python_type_errors/15_python_type_errors.md)| +| 16 | [Python Date time](../16_Day_Python_date_time/16_python_datetime.md) | +| 17 | [Exception Handling](../17_Day_Exception_handling/17_exception_handling.md)| +| 18 | [Regular Expressions](../18_Day_Regular_expressions/18_regular_expressions.md)| +| 19 | [File Handling](../19_Day_File_handling/19_file_handling.md)| +| 20 | [Python Package Manager](../20_Day_Python_package_manager/20_python_package_manager.md)| +| 21 | [Classes and Objects](../21_Day_Classes_and_objects/21_classes_and_objects.md)| +| 22 | [Web Scraping](../22_Day_Web_scraping/22_web_scraping.md)| +| 23 | [Virtual Environment](../23_Day_Virtual_environment/23_virtual_environment.md)| +| 24 | [Statistics](../24_Day_Statistics/24_statistics.md)| +| 25 | [Pandas](../25_Day_Pandas/25_pandas.md)| +| 26 | [Python web](../26_Day_Python_web/26_python_web.md)| +| 27 | [Python with MongoDB](../27_Day_Python_with_mongodb/27_python_with_mongodb.md)| +| 28 | [API](../28_Day_API/28_API.md)| +| 29 | [Building API](../29_Day_Building_API/29_building_API.md)| +| 30 | [Conclusions](../30_Day_Conclusions/30_conclusions.md)| 🧡🧡🧡 HAPPY CODING 🧡🧡🧡
Support the author to create more educational materials
-Paypal Logo +Paypal Logo
@@ -56,25 +56,25 @@
-[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) +[Day 2 >>](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) -![30DaysOfPython](./images/30DaysOfPython_banner3@2x.png) +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) - [🐍 30 Days Of Python](#-30-days-of-python) - [📘 Day 1](#-day-1) - - [환영합니다](#welcome) - - [소개](#introduction) - - [왜 Python이느냐?](#why-python-) - - [환경 설정](#environment-setup) - - [Python 설치](#installing-python) - - [Python 셸](#python-shell) - - [Visual Studio Code 설치](#installing-visual-studio-code) - - [visual studio code를 사용하기](#how-to-use-visual-studio-code) - - [Python 기본](#basic-python) - - [Python 구문](#python-syntax) - - [Python 들여쓰기](#python-indentation) - - [주석](#comments) - - [데이터 타입](#data-types) + - [환영합니다](#환영합니다) + - [소개](#소개) + - [왜 Python이느냐?](#왜-python이느냐?) + - [환경 설정](#환경-설정) + - [Python 설치](#python-설치) + - [Python 셸](#python-셸) + - [Visual Studio Code 설치](#visual-studio-code-설치) + - [visual studio code를 사용하기](#visual-studio-code를-사용하기) + - [Python 기본](#python-기본) + - [Python 구문](#python-구문) + - [Python 들여쓰기](#python-들여쓰기) + - [주석](#주석) + - [데이터 타입](#데이터-타입) - [Number](#number) - [String](#string) - [Booleans](#booleans) @@ -82,8 +82,8 @@ - [Dictionary](#dictionary) - [Tuple](#tuple) - [Set](#set) - - [데이터 타입 체크](#checking-data-types) - - [Python 파일](#python-file) + - [데이터 타입 체크](#데이터-타입-체크) + - [Python 파일](#python-파일) - [💻 Exercises - Day 1](#-exercises---day-1) - [Exercise: Level 1](#exercise-level-1) - [Exercise: Level 2](#exercise-level-2) @@ -119,7 +119,7 @@ Windows 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니 macOS 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니다. -[![Windows에서 설치](./images/installing_on_windows.png)](https://www.python.org/) +[![Windows에서 설치](../images/installing_on_windows.png)](https://www.python.org/) Python이 설치되어 있는지 확인하려면 장치 터미널에 다음 명령을 작성하십시오. @@ -127,7 +127,7 @@ Python이 설치되어 있는지 확인하려면 장치 터미널에 다음 명 python --version ``` -![Python Version](./images/python_versio.png) +![Python Version](../images/python_versio.png) 터미널에서 보시다시피 저는 현재 _Python 3.7.5_ 버전을 사용하고 있습니다. 귀하의 Python 버전은 내 버전과 다를 수 있지만 3.6 이상이어야 합니다. Python 버전을 볼 수 있다면 잘한 것입니다. 이제 컴퓨터에 Python이 설치되었습니다. 다음 섹션으로 계속 진행하십시오. @@ -142,35 +142,35 @@ Python Shell은 사용자의 Python 코드를 기다립니다. 코드를 입력 python ``` -![Python Scripting Shell](./images/opening_python_shell.png) +![Python Scripting Shell](../images/opening_python_shell.png) Python 대화형 셸이 열리고 Python 코드(Python 스크립트)를 작성하기를 기다립니다. 기호 >>> 옆에 Python 스크립트를 작성하고 Enter를 누릅니다. Python 스크립팅 셸에서 첫 번째 스크립트를 작성해 보겠습니다. -![Python script on Python shell](./images/adding_on_python_shell.png) +![Python script on Python shell](../images/adding_on_python_shell.png) 훌륭합니다. Python 대화형 셸에서 첫 번째 Python 스크립트를 작성했습니다. Python 대화형 셸을 어떻게 닫습니까? 셸을 닫으려면 기호 옆에 >> **exit()** 명령을 작성하고 Enter 키를 누릅니다. -![Exit from python shell](./images/exit_from_shell.png) +![Exit from python shell](../images/exit_from_shell.png) 이제 Python 대화형 셸을 여는 방법과 종료하는 방법을 알았습니다. Python은 Python이 이해하는 스크립트를 작성하면 결과를 제공하고 그렇지 않으면 오류를 반환합니다. 고의적인 실수를 하고 Python이 무엇을 반환하는지 봅시다. -![Invalid Syntax Error](./images/invalid_syntax_error.png) +![Invalid Syntax Error](../images/invalid_syntax_error.png) 반환된 오류에서 볼 수 있듯이 Python은 우리가 저지른 실수와 _Syntax Error: invalid syntax_를 알고 있을 정도로 영리합니다. Python에서 x를 곱셈으로 사용하는 것은 (x)가 Python에서 유효한 구문이 아니기 때문에 구문 오류입니다. (**x**) 대신 곱셈에 별표(*)를 사용합니다. 반환된 오류는 수정해야 할 사항을 명확하게 보여줍니다. 프로그램에서 오류를 식별하고 제거하는 프로세스를 *디버깅*이라고 합니다. **x** 대신 *를 넣어 디버깅해 봅시다. -![Fixing Syntax Error](./images/fixing_syntax_error.png) +![Fixing Syntax Error](../images/fixing_syntax_error.png) 버그가 수정되었고 코드가 실행되었으며 예상했던 결과를 얻었습니다. 프로그래머로서 매일 이러한 종류의 오류를 보게 될 것입니다. 디버깅 방법을 아는 것이 좋습니다. 디버깅을 잘하려면 어떤 종류의 오류가 발생했는지 이해해야 합니다. 발생할 수 있는 Python 오류 중 일부는 *SyntaxError*, *IndexError*, *NameError*, *ModuleNotFoundError*, *KeyError*, *ImportError*, *AttributeError*, *TypeError*, *ValueError*, *ZeroDivisionError* 등입니다. 이후 섹션에서 다른 Python **_오류 유형_**에 대해 자세히 알아볼 것입니다. Python 대화형 셸을 사용하는 방법을 더 연습해 보겠습니다. 터미널이나 명령 프롬프트로 이동하여 **python**이라는 단어를 씁니다. -![Python Scripting Shell](./images/opening_python_shell.png) +![Python Scripting Shell](../images/opening_python_shell.png) Python 대화형 셸이 열립니다. 몇 가지 기본적인 수학 연산(더하기, 빼기, 곱하기, 나누기, 나머지, 지수)을 수행해 보겠습니다. @@ -197,17 +197,17 @@ _comment_는 Python에 의해 실행되지 않는 코드의 일부입니다. 따 # (#) 심볼로 시작하기 때문에 이것은 파이썬 주석입니다. ``` -![Maths on python shell](./images/maths_on_python_shell.png) +![Maths on python shell](../images/maths_on_python_shell.png) 다음 섹션으로 이동하기 전에 Python 대화형 셸에서 더 많은 연습을 해 보겠습니다. 셸에서 _exit()_를 작성하여 열린 셸을 닫았다가 다시 열어 Python 셸에서 텍스트를 쓰는 방법을 연습해 봅시다. -![Writing String on python shell](./images/writing_string_on_shell.png) +![Writing String on python shell](../images/writing_string_on_shell.png) ### Visual Studio Code 설치 Python 대화형 셸은 작은 스크립트 코드를 시도하고 테스트하는 데 적합하지만 큰 프로젝트에는 적합하지 않습니다. 실제 작업 환경에서 개발자는 다양한 코드 편집기를 사용하여 코드를 작성합니다. 이 30일간의 Python 프로그래밍 챌린지에서는 Visual Studio 코드를 사용합니다. Visual Studio Code는 매우 인기 있는 오픈 소스 텍스트 편집기입니다. 나는 vscode의 팬이고 Visual Studio 코드를 [다운로드](https://code.visualstudio.com/)하는 것을 추천하고 싶지만, 다른 편집자를 선호한다면 가지고 있는 것을 자유롭게 따르십시오. -[![Visual Studio Code](./images/vscode.png)](https://code.visualstudio.com/) +[![Visual Studio Code](../images/vscode.png)](https://code.visualstudio.com/) Visual Studio Code를 설치하셨다면 어떻게 사용하는지 알아보겠습니다. 비디오를 선호하는 경우 Python용 Visual Studio Code[비디오 자습서](https://www.youtube.com/watch?v=bn7Cx4z-vSo)를 따를 수 있습니다. @@ -216,21 +216,21 @@ Visual Studio Code를 설치하셨다면 어떻게 사용하는지 알아보겠 Visual Studio 아이콘을 두 번 클릭하여 Visual Studio 코드를 엽니다. 열면 이런 종류의 인터페이스가 나타납니다. 레이블이 지정된 아이콘을 따라해보세요. -![Visual studio Code](./images/vscode_ui.png) +![Visual studio Code](../images/vscode_ui.png) 바탕 화면에 30DaysOfPython이라는 폴더를 만듭니다. 그런 다음 Visual Studio 코드를 사용하여 엽시다. -![Opening Project on Visual studio](./images/how_to_open_project_on_vscode.png) +![Opening Project on Visual studio](../images/how_to_open_project_on_vscode.png) -![Opening a project](./images/opening_project.png) +![Opening a project](../images/opening_project.png) 파일을 열면 30DaysOfPython 프로젝트의 디렉토리 내부에 파일과 폴더를 생성하기 위한 바로 가기가 표시됩니다. 아래에서 볼 수 있듯이 첫 번째 파일인 helloworld.py를 만들었습니다. 당신도 똑같이 할 수 있습니다. -![Creating a python file](./images/helloworld.png) +![Creating a python file](../images/helloworld.png) 하루동안 오래 코딩을 한 후에 코드 편집기를 닫고 싶습니까? 이렇게 열린 프로젝트를 닫으면 됩니다. -![Closing project](./images/closing_opened_project.png) +![Closing project](../images/closing_opened_project.png) 축하합니다. 개발 환경 설정을 완료했습니다. 코딩을 시작해 봅시다. @@ -244,7 +244,7 @@ Python 스크립트는 Python 대화형 셸 또는 코드 편집기에서 작성 들여쓰기는 텍스트의 공백입니다. 많은 언어에서 들여쓰기는 코드 가독성을 높이는 데 사용되지만 Python은 들여쓰기를 사용하여 코드 블록을 만듭니다. 다른 프로그래밍 언어에서는 중괄호를 사용하여 들여쓰기 대신 코드 블록을 만듭니다. Python 코드를 작성할 때 흔히 발생하는 버그 중 하나는 잘못된 들여쓰기입니다. -![Indentation Error](./images/indentation.png) +![Indentation Error](../images/indentation.png) ### 주석 @@ -372,7 +372,7 @@ Python 사전 개체는 키 값 쌍 형식의 정렬되지 않은 데이터 모 특정 데이터/변수의 데이터 유형을 확인하기 위해 **type** 기능을 사용합니다. 다음 터미널에서 다양한 Python 데이터 유형을 볼 수 있습니다: -![Checking Data types](./images/checking_data_types.png) +![Checking Data types](../images/checking_data_types.png) ### Python 파일 @@ -408,7 +408,7 @@ print(type((9.8, 3.14, 2.7))) # Tuple Python 파일을 실행하려면 아래 이미지를 확인하세요. Visual Studio Code에서 녹색 버튼을 실행하거나 터미널에 *python helloworld.py*를 입력하여 Python 파일을 실행할 수 있습니다. -![Running python script](./images/running_python_script.png) +![Running python script](../images/running_python_script.png) 🌕 좋습니다. 당신은 방금 1일차 도전을 완료했고 당신은 위대한 여정에 있습니다. 이제 뇌와 근육을 위한 몇 가지 훈련을 해봅시다. @@ -451,4 +451,4 @@ Python 파일을 실행하려면 아래 이미지를 확인하세요. Visual Stu 🎉 축하합니다 ! 🎉 -[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) \ No newline at end of file +[Day 2 >>](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) \ No newline at end of file From 54af60ae4bc16430254fcfb961e2d3ce3abee55e Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Thu, 8 Dec 2022 13:15:32 +0900 Subject: [PATCH 07/63] lang ko --- lang-ko/readme_ko.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lang-ko/readme_ko.md b/lang-ko/readme_ko.md index 558efe95f..bc6286096 100644 --- a/lang-ko/readme_ko.md +++ b/lang-ko/readme_ko.md @@ -2,7 +2,7 @@ |# Day | Topics | |------|:---------------------------------------------------------:| -| 01 | [Introduction](../readme_ko.md)| +| 01 | [Introduction](./readme_ko.md)| | 02 | [Variables, Built-in Functions](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| | 03 | [Operators](../03_Day_Operators/03_operators.md)| | 04 | [Strings](../04_Day_Strings/04_strings.md)| From 9ca1e1b177acbef495a4132a5ce7c33ed0c63982 Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 20:27:40 +0900 Subject: [PATCH 08/63] Delete korean --- korean | 1 - 1 file changed, 1 deletion(-) delete mode 100644 korean diff --git a/korean b/korean deleted file mode 100644 index 8b1378917..000000000 --- a/korean +++ /dev/null @@ -1 +0,0 @@ - From 34124a1cc410bbce839c555f8bf90fc3f7a10702 Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 20:27:55 +0900 Subject: [PATCH 09/63] Create readme.md --- korean/readme.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 korean/readme.md diff --git a/korean/readme.md b/korean/readme.md new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/korean/readme.md @@ -0,0 +1 @@ + From dc86d99e83a478afad26b4eca504f9ee59ebf805 Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 20:28:20 +0900 Subject: [PATCH 10/63] Create 03_Day_Operators --- korean/03_Day_Operators | 317 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 317 insertions(+) create mode 100644 korean/03_Day_Operators diff --git a/korean/03_Day_Operators b/korean/03_Day_Operators new file mode 100644 index 000000000..0fcfeb994 --- /dev/null +++ b/korean/03_Day_Operators @@ -0,0 +1,317 @@ +
+

30 Days Of Python: Day 3 - Operators

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ Second Edition: July, 2021 +
+
+ +[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 Day 3](#-day-3) + - [Boolean](#boolean) + - [Operators](#operators) + - [Assignment Operators](#assignment-operators) + - [Arithmetic Operators:](#arithmetic-operators) + - [Comparison Operators](#comparison-operators) + - [Logical Operators](#logical-operators) + - [💻 Exercises - Day 3](#-exercises---day-3) + +# 📘 Day 3 + +## Boolean + +A boolean data type represents one of the two values: _True_ or _False_. The use of these data types will be clear once we start using the comparison operator. The first letter **T** for True and **F** for False should be capital unlike JavaScript. +**Example: Boolean Values** + +```py +print(True) +print(False) +``` + +## Operators + +Python language supports several types of operators. In this section, we will focus on few of them. + +### Assignment Operators + +Assignment operators are used to assign values to variables. Let us take = as an example. Equal sign in mathematics shows that two values are equal, however in Python it means we are storing a value in a certain variable and we call it assignment or a assigning value to a variable. The table below shows the different types of python assignment operators, taken from [w3school](https://www.w3schools.com/python/python_operators.asp). + +![Assignment Operators](../images/assignment_operators.png) + +### Arithmetic Operators: + +- Addition(+): a + b +- Subtraction(-): a - b +- Multiplication(*): a * b +- Division(/): a / b +- Modulus(%): a % b +- Floor division(//): a // b +- Exponentiation(**): a ** b + +![Arithmetic Operators](../images/arithmetic_operators.png) + +**Example:Integers** + +```py +# Arithmetic Operations in Python +# Integers + +print('Addition: ', 1 + 2) # 3 +print('Subtraction: ', 2 - 1) # 1 +print('Multiplication: ', 2 * 3) # 6 +print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number +print('Division: ', 6 / 2) # 3.0 +print('Division: ', 7 / 2) # 3.5 +print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining +print ('Division without the remainder: ',7 // 3) # 2 +print('Modulus: ', 3 % 2) # 1, Gives the remainder +print('Exponentiation: ', 2 ** 3) # 9 it means 2 * 2 * 2 +``` + +**Example:Floats** + +```py +# Floating numbers +print('Floating Point Number, PI', 3.14) +print('Floating Point Number, gravity', 9.81) +``` + +**Example:Complex numbers** + +```py +# Complex numbers +print('Complex number: ', 1 + 1j) +print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j)) +``` + +Let's declare a variable and assign a number data type. I am going to use single character variable but remember do not develop a habit of declaring such types of variables. Variable names should be all the time mnemonic. + +**Example:** + +```python +# Declaring the variable at the top first + +a = 3 # a is a variable name and 3 is an integer data type +b = 2 # b is a variable name and 3 is an integer data type + +# Arithmetic operations and assigning the result to a variable +total = a + b +diff = a - b +product = a * b +division = a / b +remainder = a % b +floor_division = a // b +exponential = a ** b + +# I should have used sum instead of total but sum is a built-in function - try to avoid overriding built-in functions +print(total) # if you do not label your print with some string, you never know where the result is coming from +print('a + b = ', total) +print('a - b = ', diff) +print('a * b = ', product) +print('a / b = ', division) +print('a % b = ', remainder) +print('a // b = ', floor_division) +print('a ** b = ', exponentiation) +``` + +**Example:** + +```py +print('== Addition, Subtraction, Multiplication, Division, Modulus ==') + +# Declaring values and organizing them together +num_one = 3 +num_two = 4 + +# Arithmetic operations +total = num_one + num_two +diff = num_two - num_one +product = num_one * num_two +div = num_two / num_one +remainder = num_two % num_one + +# Printing values with label +print('total: ', total) +print('difference: ', diff) +print('product: ', product) +print('division: ', div) +print('remainder: ', remainder) +``` + +Let us start start connecting the dots and start making use of what we already know to calculate (area, volume,density, weight, perimeter, distance, force). + +**Example:** + +```py +# Calculating area of a circle +radius = 10 # radius of a circle +area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power +print('Area of a circle:', area_of_circle) + +# Calculating area of a rectangle +length = 10 +width = 20 +area_of_rectangle = length * width +print('Area of rectangle:', area_of_rectangle) + +# Calculating a weight of an object +mass = 75 +gravity = 9.81 +weight = mass * gravity +print(weight, 'N') # Adding unit to the weight + +# Calculate the density of a liquid +mass = 75 # in Kg +volume = 0.075 # in cubic meter +density = mass / volume # 1000 Kg/m^3 + +``` + +### Comparison Operators + +In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows Python comparison operators which was taken from [w3shool](https://www.w3schools.com/python/python_operators.asp). + +![Comparison Operators](../images/comparison_operators.png) +**Example: Comparison Operators** + +```py +print(3 > 2) # True, because 3 is greater than 2 +print(3 >= 2) # True, because 3 is greater than 2 +print(3 < 2) # False, because 3 is greater than 2 +print(2 < 3) # True, because 2 is less than 3 +print(2 <= 3) # True, because 2 is less than 3 +print(3 == 2) # False, because 3 is not equal to 2 +print(3 != 2) # True, because 3 is not equal to 2 +print(len('mango') == len('avocado')) # False +print(len('mango') != len('avocado')) # True +print(len('mango') < len('avocado')) # True +print(len('milk') != len('meat')) # False +print(len('milk') == len('meat')) # True +print(len('tomato') == len('potato')) # True +print(len('python') > len('dragon')) # False + + +# Comparing something gives either a True or False + +print('True == True: ', True == True) +print('True == False: ', True == False) +print('False == False:', False == False) +``` + +In addition to the above comparison operator Python uses: + +- _is_: Returns true if both variables are the same object(x is y) +- _is not_: Returns true if both variables are not the same object(x is not y) +- _in_: Returns True if the queried list contains a certain item(x in y) +- _not in_: Returns True if the queried list doesn't have a certain item(x in y) + +```py +print('1 is 1', 1 is 1) # True - because the data values are the same +print('1 is not 2', 1 is not 2) # True - because 1 is not 2 +print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string +print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B +print('coding' in 'coding for all') # True - because coding for all has the word coding +print('a in an:', 'a' in 'an') # True +print('4 is 2 ** 2:', 4 is 2 ** 2) # True +``` + +### Logical Operators + +Unlike other programming languages python uses keywords _and_, _or_ and _not_ for logical operators. Logical operators are used to combine conditional statements: + +![Logical Operators](../images/logical_operators.png) + +```py +print(3 > 2 and 4 > 3) # True - because both statements are true +print(3 > 2 and 4 < 3) # False - because the second statement is false +print(3 < 2 and 4 < 3) # False - because both statements are false +print('True and True: ', True and True) +print(3 > 2 or 4 > 3) # True - because both statements are true +print(3 > 2 or 4 < 3) # True - because one of the statements is true +print(3 < 2 or 4 < 3) # False - because both statements are false +print('True or False:', True or False) +print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False +print(not True) # False - Negation, the not operator turns true to false +print(not False) # True +print(not not True) # True +print(not not False) # False + +``` + +🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps ahead on your way to greatness. Now do some exercises for your brain and your muscles. + +## 💻 Exercises - Day 3 + +1. Declare your age as integer variable +2. Declare your height as a float variable +3. Declare a variable that store a complex number +4. Write a script that prompts the user to enter base and height of the triangle and calculate an area of this triangle (area = 0.5 x b x h). + +```py + Enter base: 20 + Enter height: 10 + The area of the triangle is 100 +``` + +5. Write a script that prompts the user to enter side a, side b, and side c of the triangle. Calculate the perimeter of the triangle (perimeter = a + b + c). + +```py +Enter side a: 5 +Enter side b: 4 +Enter side c: 3 +The perimeter of the triangle is 12 +``` + +6. Get length and width of a rectangle using prompt. Calculate its area (area = length x width) and perimeter (perimeter = 2 x (length + width)) +7. Get radius of a circle using prompt. Calculate the area (area = pi x r x r) and circumference (c = 2 x pi x r) where pi = 3.14. +8. Calculate the slope, x-intercept and y-intercept of y = 2x -2 +9. Slope is (m = y2-y1/x2-x1). Find the slope and [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) between point (2, 2) and point (6,10) +10. Compare the slopes in tasks 8 and 9. +11. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is going to be 0. +12. Find the length of 'python' and 'dragon' and make a falsy comparison statement. +13. Use _and_ operator to check if 'on' is found in both 'python' and 'dragon' +14. _I hope this course is not full of jargon_. Use _in_ operator to check if _jargon_ is in the sentence. +15. There is no 'on' in both dragon and python +16. Find the length of the text _python_ and convert the value to float and convert it to string +17. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using python? +18. Check if the floor division of 7 by 3 is equal to the int converted value of 2.7. +19. Check if type of '10' is equal to type of 10 +20. Check if int('9.8') is equal to 10 +21. Writ a script that prompts the user to enter hours and rate per hour. Calculate pay of the person? + +```py +Enter hours: 40 +Enter rate per hour: 28 +Your weekly earning is 1120 +``` + +22. Write a script that prompts the user to enter number of years. Calculate the number of seconds a person can live. Assume a person can live hundred years + +```py +Enter number of years you have lived: 100 +You have lived for 3153600000 seconds. +``` + +23. Write a Python script that displays the following table + +```py +1 1 1 1 1 +2 1 2 4 8 +3 1 3 9 27 +4 1 4 16 64 +5 1 5 25 125 +``` + +🎉 CONGRATULATIONS ! 🎉 + +[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md) From aefe0a748cb0497e165d4f794a584671586f8e8e Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 20:28:45 +0900 Subject: [PATCH 11/63] Delete 03_Day_Operators --- korean/03_Day_Operators | 317 ---------------------------------------- 1 file changed, 317 deletions(-) delete mode 100644 korean/03_Day_Operators diff --git a/korean/03_Day_Operators b/korean/03_Day_Operators deleted file mode 100644 index 0fcfeb994..000000000 --- a/korean/03_Day_Operators +++ /dev/null @@ -1,317 +0,0 @@ -
-

30 Days Of Python: Day 3 - Operators

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- Second Edition: July, 2021 -
-
- -[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md) - -![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) - -- [📘 Day 3](#-day-3) - - [Boolean](#boolean) - - [Operators](#operators) - - [Assignment Operators](#assignment-operators) - - [Arithmetic Operators:](#arithmetic-operators) - - [Comparison Operators](#comparison-operators) - - [Logical Operators](#logical-operators) - - [💻 Exercises - Day 3](#-exercises---day-3) - -# 📘 Day 3 - -## Boolean - -A boolean data type represents one of the two values: _True_ or _False_. The use of these data types will be clear once we start using the comparison operator. The first letter **T** for True and **F** for False should be capital unlike JavaScript. -**Example: Boolean Values** - -```py -print(True) -print(False) -``` - -## Operators - -Python language supports several types of operators. In this section, we will focus on few of them. - -### Assignment Operators - -Assignment operators are used to assign values to variables. Let us take = as an example. Equal sign in mathematics shows that two values are equal, however in Python it means we are storing a value in a certain variable and we call it assignment or a assigning value to a variable. The table below shows the different types of python assignment operators, taken from [w3school](https://www.w3schools.com/python/python_operators.asp). - -![Assignment Operators](../images/assignment_operators.png) - -### Arithmetic Operators: - -- Addition(+): a + b -- Subtraction(-): a - b -- Multiplication(*): a * b -- Division(/): a / b -- Modulus(%): a % b -- Floor division(//): a // b -- Exponentiation(**): a ** b - -![Arithmetic Operators](../images/arithmetic_operators.png) - -**Example:Integers** - -```py -# Arithmetic Operations in Python -# Integers - -print('Addition: ', 1 + 2) # 3 -print('Subtraction: ', 2 - 1) # 1 -print('Multiplication: ', 2 * 3) # 6 -print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number -print('Division: ', 6 / 2) # 3.0 -print('Division: ', 7 / 2) # 3.5 -print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining -print ('Division without the remainder: ',7 // 3) # 2 -print('Modulus: ', 3 % 2) # 1, Gives the remainder -print('Exponentiation: ', 2 ** 3) # 9 it means 2 * 2 * 2 -``` - -**Example:Floats** - -```py -# Floating numbers -print('Floating Point Number, PI', 3.14) -print('Floating Point Number, gravity', 9.81) -``` - -**Example:Complex numbers** - -```py -# Complex numbers -print('Complex number: ', 1 + 1j) -print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j)) -``` - -Let's declare a variable and assign a number data type. I am going to use single character variable but remember do not develop a habit of declaring such types of variables. Variable names should be all the time mnemonic. - -**Example:** - -```python -# Declaring the variable at the top first - -a = 3 # a is a variable name and 3 is an integer data type -b = 2 # b is a variable name and 3 is an integer data type - -# Arithmetic operations and assigning the result to a variable -total = a + b -diff = a - b -product = a * b -division = a / b -remainder = a % b -floor_division = a // b -exponential = a ** b - -# I should have used sum instead of total but sum is a built-in function - try to avoid overriding built-in functions -print(total) # if you do not label your print with some string, you never know where the result is coming from -print('a + b = ', total) -print('a - b = ', diff) -print('a * b = ', product) -print('a / b = ', division) -print('a % b = ', remainder) -print('a // b = ', floor_division) -print('a ** b = ', exponentiation) -``` - -**Example:** - -```py -print('== Addition, Subtraction, Multiplication, Division, Modulus ==') - -# Declaring values and organizing them together -num_one = 3 -num_two = 4 - -# Arithmetic operations -total = num_one + num_two -diff = num_two - num_one -product = num_one * num_two -div = num_two / num_one -remainder = num_two % num_one - -# Printing values with label -print('total: ', total) -print('difference: ', diff) -print('product: ', product) -print('division: ', div) -print('remainder: ', remainder) -``` - -Let us start start connecting the dots and start making use of what we already know to calculate (area, volume,density, weight, perimeter, distance, force). - -**Example:** - -```py -# Calculating area of a circle -radius = 10 # radius of a circle -area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power -print('Area of a circle:', area_of_circle) - -# Calculating area of a rectangle -length = 10 -width = 20 -area_of_rectangle = length * width -print('Area of rectangle:', area_of_rectangle) - -# Calculating a weight of an object -mass = 75 -gravity = 9.81 -weight = mass * gravity -print(weight, 'N') # Adding unit to the weight - -# Calculate the density of a liquid -mass = 75 # in Kg -volume = 0.075 # in cubic meter -density = mass / volume # 1000 Kg/m^3 - -``` - -### Comparison Operators - -In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows Python comparison operators which was taken from [w3shool](https://www.w3schools.com/python/python_operators.asp). - -![Comparison Operators](../images/comparison_operators.png) -**Example: Comparison Operators** - -```py -print(3 > 2) # True, because 3 is greater than 2 -print(3 >= 2) # True, because 3 is greater than 2 -print(3 < 2) # False, because 3 is greater than 2 -print(2 < 3) # True, because 2 is less than 3 -print(2 <= 3) # True, because 2 is less than 3 -print(3 == 2) # False, because 3 is not equal to 2 -print(3 != 2) # True, because 3 is not equal to 2 -print(len('mango') == len('avocado')) # False -print(len('mango') != len('avocado')) # True -print(len('mango') < len('avocado')) # True -print(len('milk') != len('meat')) # False -print(len('milk') == len('meat')) # True -print(len('tomato') == len('potato')) # True -print(len('python') > len('dragon')) # False - - -# Comparing something gives either a True or False - -print('True == True: ', True == True) -print('True == False: ', True == False) -print('False == False:', False == False) -``` - -In addition to the above comparison operator Python uses: - -- _is_: Returns true if both variables are the same object(x is y) -- _is not_: Returns true if both variables are not the same object(x is not y) -- _in_: Returns True if the queried list contains a certain item(x in y) -- _not in_: Returns True if the queried list doesn't have a certain item(x in y) - -```py -print('1 is 1', 1 is 1) # True - because the data values are the same -print('1 is not 2', 1 is not 2) # True - because 1 is not 2 -print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string -print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B -print('coding' in 'coding for all') # True - because coding for all has the word coding -print('a in an:', 'a' in 'an') # True -print('4 is 2 ** 2:', 4 is 2 ** 2) # True -``` - -### Logical Operators - -Unlike other programming languages python uses keywords _and_, _or_ and _not_ for logical operators. Logical operators are used to combine conditional statements: - -![Logical Operators](../images/logical_operators.png) - -```py -print(3 > 2 and 4 > 3) # True - because both statements are true -print(3 > 2 and 4 < 3) # False - because the second statement is false -print(3 < 2 and 4 < 3) # False - because both statements are false -print('True and True: ', True and True) -print(3 > 2 or 4 > 3) # True - because both statements are true -print(3 > 2 or 4 < 3) # True - because one of the statements is true -print(3 < 2 or 4 < 3) # False - because both statements are false -print('True or False:', True or False) -print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False -print(not True) # False - Negation, the not operator turns true to false -print(not False) # True -print(not not True) # True -print(not not False) # False - -``` - -🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps ahead on your way to greatness. Now do some exercises for your brain and your muscles. - -## 💻 Exercises - Day 3 - -1. Declare your age as integer variable -2. Declare your height as a float variable -3. Declare a variable that store a complex number -4. Write a script that prompts the user to enter base and height of the triangle and calculate an area of this triangle (area = 0.5 x b x h). - -```py - Enter base: 20 - Enter height: 10 - The area of the triangle is 100 -``` - -5. Write a script that prompts the user to enter side a, side b, and side c of the triangle. Calculate the perimeter of the triangle (perimeter = a + b + c). - -```py -Enter side a: 5 -Enter side b: 4 -Enter side c: 3 -The perimeter of the triangle is 12 -``` - -6. Get length and width of a rectangle using prompt. Calculate its area (area = length x width) and perimeter (perimeter = 2 x (length + width)) -7. Get radius of a circle using prompt. Calculate the area (area = pi x r x r) and circumference (c = 2 x pi x r) where pi = 3.14. -8. Calculate the slope, x-intercept and y-intercept of y = 2x -2 -9. Slope is (m = y2-y1/x2-x1). Find the slope and [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) between point (2, 2) and point (6,10) -10. Compare the slopes in tasks 8 and 9. -11. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is going to be 0. -12. Find the length of 'python' and 'dragon' and make a falsy comparison statement. -13. Use _and_ operator to check if 'on' is found in both 'python' and 'dragon' -14. _I hope this course is not full of jargon_. Use _in_ operator to check if _jargon_ is in the sentence. -15. There is no 'on' in both dragon and python -16. Find the length of the text _python_ and convert the value to float and convert it to string -17. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using python? -18. Check if the floor division of 7 by 3 is equal to the int converted value of 2.7. -19. Check if type of '10' is equal to type of 10 -20. Check if int('9.8') is equal to 10 -21. Writ a script that prompts the user to enter hours and rate per hour. Calculate pay of the person? - -```py -Enter hours: 40 -Enter rate per hour: 28 -Your weekly earning is 1120 -``` - -22. Write a script that prompts the user to enter number of years. Calculate the number of seconds a person can live. Assume a person can live hundred years - -```py -Enter number of years you have lived: 100 -You have lived for 3153600000 seconds. -``` - -23. Write a Python script that displays the following table - -```py -1 1 1 1 1 -2 1 2 4 8 -3 1 3 9 27 -4 1 4 16 64 -5 1 5 25 125 -``` - -🎉 CONGRATULATIONS ! 🎉 - -[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md) From d43714ca16dc3b114e5ab80cbf5b8324ab5556c0 Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 20:29:12 +0900 Subject: [PATCH 12/63] Create 03_operators.md --- korean/03_Day_Operators/03_operators.md | 317 ++++++++++++++++++++++++ 1 file changed, 317 insertions(+) create mode 100644 korean/03_Day_Operators/03_operators.md diff --git a/korean/03_Day_Operators/03_operators.md b/korean/03_Day_Operators/03_operators.md new file mode 100644 index 000000000..0fcfeb994 --- /dev/null +++ b/korean/03_Day_Operators/03_operators.md @@ -0,0 +1,317 @@ +
+

30 Days Of Python: Day 3 - Operators

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ Second Edition: July, 2021 +
+
+ +[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 Day 3](#-day-3) + - [Boolean](#boolean) + - [Operators](#operators) + - [Assignment Operators](#assignment-operators) + - [Arithmetic Operators:](#arithmetic-operators) + - [Comparison Operators](#comparison-operators) + - [Logical Operators](#logical-operators) + - [💻 Exercises - Day 3](#-exercises---day-3) + +# 📘 Day 3 + +## Boolean + +A boolean data type represents one of the two values: _True_ or _False_. The use of these data types will be clear once we start using the comparison operator. The first letter **T** for True and **F** for False should be capital unlike JavaScript. +**Example: Boolean Values** + +```py +print(True) +print(False) +``` + +## Operators + +Python language supports several types of operators. In this section, we will focus on few of them. + +### Assignment Operators + +Assignment operators are used to assign values to variables. Let us take = as an example. Equal sign in mathematics shows that two values are equal, however in Python it means we are storing a value in a certain variable and we call it assignment or a assigning value to a variable. The table below shows the different types of python assignment operators, taken from [w3school](https://www.w3schools.com/python/python_operators.asp). + +![Assignment Operators](../images/assignment_operators.png) + +### Arithmetic Operators: + +- Addition(+): a + b +- Subtraction(-): a - b +- Multiplication(*): a * b +- Division(/): a / b +- Modulus(%): a % b +- Floor division(//): a // b +- Exponentiation(**): a ** b + +![Arithmetic Operators](../images/arithmetic_operators.png) + +**Example:Integers** + +```py +# Arithmetic Operations in Python +# Integers + +print('Addition: ', 1 + 2) # 3 +print('Subtraction: ', 2 - 1) # 1 +print('Multiplication: ', 2 * 3) # 6 +print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number +print('Division: ', 6 / 2) # 3.0 +print('Division: ', 7 / 2) # 3.5 +print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining +print ('Division without the remainder: ',7 // 3) # 2 +print('Modulus: ', 3 % 2) # 1, Gives the remainder +print('Exponentiation: ', 2 ** 3) # 9 it means 2 * 2 * 2 +``` + +**Example:Floats** + +```py +# Floating numbers +print('Floating Point Number, PI', 3.14) +print('Floating Point Number, gravity', 9.81) +``` + +**Example:Complex numbers** + +```py +# Complex numbers +print('Complex number: ', 1 + 1j) +print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j)) +``` + +Let's declare a variable and assign a number data type. I am going to use single character variable but remember do not develop a habit of declaring such types of variables. Variable names should be all the time mnemonic. + +**Example:** + +```python +# Declaring the variable at the top first + +a = 3 # a is a variable name and 3 is an integer data type +b = 2 # b is a variable name and 3 is an integer data type + +# Arithmetic operations and assigning the result to a variable +total = a + b +diff = a - b +product = a * b +division = a / b +remainder = a % b +floor_division = a // b +exponential = a ** b + +# I should have used sum instead of total but sum is a built-in function - try to avoid overriding built-in functions +print(total) # if you do not label your print with some string, you never know where the result is coming from +print('a + b = ', total) +print('a - b = ', diff) +print('a * b = ', product) +print('a / b = ', division) +print('a % b = ', remainder) +print('a // b = ', floor_division) +print('a ** b = ', exponentiation) +``` + +**Example:** + +```py +print('== Addition, Subtraction, Multiplication, Division, Modulus ==') + +# Declaring values and organizing them together +num_one = 3 +num_two = 4 + +# Arithmetic operations +total = num_one + num_two +diff = num_two - num_one +product = num_one * num_two +div = num_two / num_one +remainder = num_two % num_one + +# Printing values with label +print('total: ', total) +print('difference: ', diff) +print('product: ', product) +print('division: ', div) +print('remainder: ', remainder) +``` + +Let us start start connecting the dots and start making use of what we already know to calculate (area, volume,density, weight, perimeter, distance, force). + +**Example:** + +```py +# Calculating area of a circle +radius = 10 # radius of a circle +area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power +print('Area of a circle:', area_of_circle) + +# Calculating area of a rectangle +length = 10 +width = 20 +area_of_rectangle = length * width +print('Area of rectangle:', area_of_rectangle) + +# Calculating a weight of an object +mass = 75 +gravity = 9.81 +weight = mass * gravity +print(weight, 'N') # Adding unit to the weight + +# Calculate the density of a liquid +mass = 75 # in Kg +volume = 0.075 # in cubic meter +density = mass / volume # 1000 Kg/m^3 + +``` + +### Comparison Operators + +In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows Python comparison operators which was taken from [w3shool](https://www.w3schools.com/python/python_operators.asp). + +![Comparison Operators](../images/comparison_operators.png) +**Example: Comparison Operators** + +```py +print(3 > 2) # True, because 3 is greater than 2 +print(3 >= 2) # True, because 3 is greater than 2 +print(3 < 2) # False, because 3 is greater than 2 +print(2 < 3) # True, because 2 is less than 3 +print(2 <= 3) # True, because 2 is less than 3 +print(3 == 2) # False, because 3 is not equal to 2 +print(3 != 2) # True, because 3 is not equal to 2 +print(len('mango') == len('avocado')) # False +print(len('mango') != len('avocado')) # True +print(len('mango') < len('avocado')) # True +print(len('milk') != len('meat')) # False +print(len('milk') == len('meat')) # True +print(len('tomato') == len('potato')) # True +print(len('python') > len('dragon')) # False + + +# Comparing something gives either a True or False + +print('True == True: ', True == True) +print('True == False: ', True == False) +print('False == False:', False == False) +``` + +In addition to the above comparison operator Python uses: + +- _is_: Returns true if both variables are the same object(x is y) +- _is not_: Returns true if both variables are not the same object(x is not y) +- _in_: Returns True if the queried list contains a certain item(x in y) +- _not in_: Returns True if the queried list doesn't have a certain item(x in y) + +```py +print('1 is 1', 1 is 1) # True - because the data values are the same +print('1 is not 2', 1 is not 2) # True - because 1 is not 2 +print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string +print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B +print('coding' in 'coding for all') # True - because coding for all has the word coding +print('a in an:', 'a' in 'an') # True +print('4 is 2 ** 2:', 4 is 2 ** 2) # True +``` + +### Logical Operators + +Unlike other programming languages python uses keywords _and_, _or_ and _not_ for logical operators. Logical operators are used to combine conditional statements: + +![Logical Operators](../images/logical_operators.png) + +```py +print(3 > 2 and 4 > 3) # True - because both statements are true +print(3 > 2 and 4 < 3) # False - because the second statement is false +print(3 < 2 and 4 < 3) # False - because both statements are false +print('True and True: ', True and True) +print(3 > 2 or 4 > 3) # True - because both statements are true +print(3 > 2 or 4 < 3) # True - because one of the statements is true +print(3 < 2 or 4 < 3) # False - because both statements are false +print('True or False:', True or False) +print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False +print(not True) # False - Negation, the not operator turns true to false +print(not False) # True +print(not not True) # True +print(not not False) # False + +``` + +🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps ahead on your way to greatness. Now do some exercises for your brain and your muscles. + +## 💻 Exercises - Day 3 + +1. Declare your age as integer variable +2. Declare your height as a float variable +3. Declare a variable that store a complex number +4. Write a script that prompts the user to enter base and height of the triangle and calculate an area of this triangle (area = 0.5 x b x h). + +```py + Enter base: 20 + Enter height: 10 + The area of the triangle is 100 +``` + +5. Write a script that prompts the user to enter side a, side b, and side c of the triangle. Calculate the perimeter of the triangle (perimeter = a + b + c). + +```py +Enter side a: 5 +Enter side b: 4 +Enter side c: 3 +The perimeter of the triangle is 12 +``` + +6. Get length and width of a rectangle using prompt. Calculate its area (area = length x width) and perimeter (perimeter = 2 x (length + width)) +7. Get radius of a circle using prompt. Calculate the area (area = pi x r x r) and circumference (c = 2 x pi x r) where pi = 3.14. +8. Calculate the slope, x-intercept and y-intercept of y = 2x -2 +9. Slope is (m = y2-y1/x2-x1). Find the slope and [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) between point (2, 2) and point (6,10) +10. Compare the slopes in tasks 8 and 9. +11. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is going to be 0. +12. Find the length of 'python' and 'dragon' and make a falsy comparison statement. +13. Use _and_ operator to check if 'on' is found in both 'python' and 'dragon' +14. _I hope this course is not full of jargon_. Use _in_ operator to check if _jargon_ is in the sentence. +15. There is no 'on' in both dragon and python +16. Find the length of the text _python_ and convert the value to float and convert it to string +17. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using python? +18. Check if the floor division of 7 by 3 is equal to the int converted value of 2.7. +19. Check if type of '10' is equal to type of 10 +20. Check if int('9.8') is equal to 10 +21. Writ a script that prompts the user to enter hours and rate per hour. Calculate pay of the person? + +```py +Enter hours: 40 +Enter rate per hour: 28 +Your weekly earning is 1120 +``` + +22. Write a script that prompts the user to enter number of years. Calculate the number of seconds a person can live. Assume a person can live hundred years + +```py +Enter number of years you have lived: 100 +You have lived for 3153600000 seconds. +``` + +23. Write a Python script that displays the following table + +```py +1 1 1 1 1 +2 1 2 4 8 +3 1 3 9 27 +4 1 4 16 64 +5 1 5 25 125 +``` + +🎉 CONGRATULATIONS ! 🎉 + +[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md) From abeb87a1989971621be103db58df5ca63822a3af Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 21:14:09 +0900 Subject: [PATCH 13/63] Update 03_operators.md --- korean/03_Day_Operators/03_operators.md | 104 ++++++++++++------------ 1 file changed, 52 insertions(+), 52 deletions(-) diff --git a/korean/03_Day_Operators/03_operators.md b/korean/03_Day_Operators/03_operators.md index 0fcfeb994..d54c49812 100644 --- a/korean/03_Day_Operators/03_operators.md +++ b/korean/03_Day_Operators/03_operators.md @@ -17,50 +17,50 @@ ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) -- [📘 Day 3](#-day-3) - - [Boolean](#boolean) - - [Operators](#operators) - - [Assignment Operators](#assignment-operators) - - [Arithmetic Operators:](#arithmetic-operators) - - [Comparison Operators](#comparison-operators) - - [Logical Operators](#logical-operators) - - [💻 Exercises - Day 3](#-exercises---day-3) +- [📘 3일차](#3일차) + - [불리언](#불리언) + - [연산자](#연산자) + - [대입 연산자](#대입 연산자) + - [산술 연산자:](#산술 연산자) + - [비교 연산자](#비교 연산자) + - [논리 연산자](#논리 연산자) + - [💻 3일차: 실습](#3일차: 실습) -# 📘 Day 3 +# 📘 3일차 -## Boolean +## 불리언 -A boolean data type represents one of the two values: _True_ or _False_. The use of these data types will be clear once we start using the comparison operator. The first letter **T** for True and **F** for False should be capital unlike JavaScript. -**Example: Boolean Values** +불리언 데이터 타입은 True 또는 False 두 값 중 하나를 나타냅니다. 비교 연산자를 사용하면 이 데이터 타입의 사용이 명확해질 것입니다. 첫 번째 문자 **T** 는 참, **F** 는 거짓으로 표현되는 자바 스크립트와 달리 대문자여야 합니다. +**예시: 불리언 값** ```py print(True) print(False) ``` -## Operators +## 연산자 -Python language supports several types of operators. In this section, we will focus on few of them. +파이썬은 몇 가지 타입의 연산자를 지원합니다. 이 섹션에서 이것에 대해 알아볼 것입니다. -### Assignment Operators +### 대입 연산자 -Assignment operators are used to assign values to variables. Let us take = as an example. Equal sign in mathematics shows that two values are equal, however in Python it means we are storing a value in a certain variable and we call it assignment or a assigning value to a variable. The table below shows the different types of python assignment operators, taken from [w3school](https://www.w3schools.com/python/python_operators.asp). +대입 연산자는 변수에 값을 대입할 때 사용됩니다. = 로 예시를 들어보겠습니다. 수학에서 등호란 두 값이 동일하다는 것을 의미하지만, 파이썬에서는 특정 변수가 값을 가지고 있으며, 이 변수에 값을 대입한다고 합니다. 아래 표는 [w3school](https://www.w3schools.com/python/python_operators.asp)에서 가져온 다양한 유형의 파이썬 할당 연산자를 보여줍니다. -![Assignment Operators](../images/assignment_operators.png) +![대입 연산자](../images/assignment_operators.png) -### Arithmetic Operators: +### 산술 연산자: -- Addition(+): a + b -- Subtraction(-): a - b -- Multiplication(*): a * b -- Division(/): a / b -- Modulus(%): a % b -- Floor division(//): a // b -- Exponentiation(**): a ** b +- 더하기(+): a + b +- 빼기(-): a - b +- 곱하기(*): a * b +- 나누기(/): a / b +- 나머지 연산(%): a % b +- 버림 나눗셈(//): a // b +- 지수(**): a ** b -![Arithmetic Operators](../images/arithmetic_operators.png) +![산술 연산자](../images/arithmetic_operators.png) -**Example:Integers** +**예시: Integers** ```py # Arithmetic Operations in Python @@ -69,16 +69,16 @@ Assignment operators are used to assign values to variables. Let us take = as an print('Addition: ', 1 + 2) # 3 print('Subtraction: ', 2 - 1) # 1 print('Multiplication: ', 2 * 3) # 6 -print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number +print ('Division: ', 4 / 2) # 2.0 파이썬의 나누기는 부동 소수를 제공합니다. print('Division: ', 6 / 2) # 3.0 print('Division: ', 7 / 2) # 3.5 -print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining +print('Division without the remainder: ', 7 // 2) # 3, 부동 소수 또는 나머지가 없는 값을 제공합니다. print ('Division without the remainder: ',7 // 3) # 2 -print('Modulus: ', 3 % 2) # 1, Gives the remainder -print('Exponentiation: ', 2 ** 3) # 9 it means 2 * 2 * 2 +print('Modulus: ', 3 % 2) # 1, 나머지를 제공합니다. +print('Exponentiation: ', 2 ** 3) # 9 2 * 2 * 2 를 의미합니다. ``` -**Example:Floats** +**예시: Floats** ```py # Floating numbers @@ -86,7 +86,7 @@ print('Floating Point Number, PI', 3.14) print('Floating Point Number, gravity', 9.81) ``` -**Example:Complex numbers** +**예시: 복소수** ```py # Complex numbers @@ -94,17 +94,17 @@ print('Complex number: ', 1 + 1j) print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j)) ``` -Let's declare a variable and assign a number data type. I am going to use single character variable but remember do not develop a habit of declaring such types of variables. Variable names should be all the time mnemonic. +변수를 선언하고 숫자 데이터 유형을 지정합니다. 여기서는 단일 문자 변수를 사용할 것이지만, 이런 유형의 변수를 선언하는 습관은 좋지 않다는 것을 기억하셔야 합니다. 변수 이름은 항상 기억해야 합니다. **Example:** ```python -# Declaring the variable at the top first +# 첫 번째로 변수를 먼저 선언합니다. -a = 3 # a is a variable name and 3 is an integer data type -b = 2 # b is a variable name and 3 is an integer data type +a = 3 # a는 변수의 이름이며 정수 데이터 타입입니다. +b = 2 # b는 변수의 이름이며 정수 데이터 타입입니다. -# Arithmetic operations and assigning the result to a variable +# 산술 연산 및 결과를 변수에 대입합니다. total = a + b diff = a - b product = a * b @@ -113,8 +113,8 @@ remainder = a % b floor_division = a // b exponential = a ** b -# I should have used sum instead of total but sum is a built-in function - try to avoid overriding built-in functions -print(total) # if you do not label your print with some string, you never know where the result is coming from +# sum 대신 total을 사용했어야 하지만 sum은 내장 함수입니다. 내장 함수를 재정의하지 않도록 하십시오. +print(total) # 만약 몇몇 출력에 문자열로 표시를 하지 않는다면, 어디서 결과가 오는지 알지 못할 것입니다. print('a + b = ', total) print('a - b = ', diff) print('a * b = ', product) @@ -129,18 +129,18 @@ print('a ** b = ', exponentiation) ```py print('== Addition, Subtraction, Multiplication, Division, Modulus ==') -# Declaring values and organizing them together +# 값을 선언하고 함께 정리 num_one = 3 num_two = 4 -# Arithmetic operations +# 산술 연산 total = num_one + num_two diff = num_two - num_one product = num_one * num_two div = num_two / num_one remainder = num_two % num_one -# Printing values with label +# 레이블로 값 출력 print('total: ', total) print('difference: ', diff) print('product: ', product) @@ -148,36 +148,36 @@ print('division: ', div) print('remainder: ', remainder) ``` -Let us start start connecting the dots and start making use of what we already know to calculate (area, volume,density, weight, perimeter, distance, force). +이제 점 연결을 시작하고 이미 알고 있는 계산 방법(면적, 부피, 밀도, 무게, 둘레, 거리, 힘)을 사용해 보겠습니다. **Example:** ```py -# Calculating area of a circle -radius = 10 # radius of a circle -area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power +# 원의 넓이 계산 +radius = 10 # 원의 반지름 +area_of_circle = 3.14 * radius ** 2 # 두 개의 * 기호는 지수를 의미합니다 print('Area of a circle:', area_of_circle) -# Calculating area of a rectangle +# 직사각형의 넓이 계산 length = 10 width = 20 area_of_rectangle = length * width print('Area of rectangle:', area_of_rectangle) -# Calculating a weight of an object +# 개체의 무게 계산 mass = 75 gravity = 9.81 weight = mass * gravity -print(weight, 'N') # Adding unit to the weight +print(weight, 'N') # 무게에 단위 추가 -# Calculate the density of a liquid +# 액체의 밀도 계산 mass = 75 # in Kg volume = 0.075 # in cubic meter density = mass / volume # 1000 Kg/m^3 ``` -### Comparison Operators +### 비교 연산자 In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows Python comparison operators which was taken from [w3shool](https://www.w3schools.com/python/python_operators.asp). From d0d51e2673f5acb0d328110201e78773bfdd84f0 Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 21:43:35 +0900 Subject: [PATCH 14/63] Update 03_operators.md --- korean/03_Day_Operators/03_operators.md | 144 ++++++++++++------------ 1 file changed, 72 insertions(+), 72 deletions(-) diff --git a/korean/03_Day_Operators/03_operators.md b/korean/03_Day_Operators/03_operators.md index d54c49812..e50972fc5 100644 --- a/korean/03_Day_Operators/03_operators.md +++ b/korean/03_Day_Operators/03_operators.md @@ -20,11 +20,11 @@ - [📘 3일차](#3일차) - [불리언](#불리언) - [연산자](#연산자) - - [대입 연산자](#대입 연산자) - - [산술 연산자:](#산술 연산자) - - [비교 연산자](#비교 연산자) - - [논리 연산자](#논리 연산자) - - [💻 3일차: 실습](#3일차: 실습) + - [대입 연산자](#대입-연산자) + - [산술 연산자:](#산술-연산자) + - [비교 연산자](#비교-연산자) + - [논리 연산자](#논리-연산자) + - [💻 3일차: 실습](3일차:-실습) # 📘 3일차 @@ -179,83 +179,83 @@ density = mass / volume # 1000 Kg/m^3 ### 비교 연산자 -In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows Python comparison operators which was taken from [w3shool](https://www.w3schools.com/python/python_operators.asp). +프로그래밍에서 우리는 비교 연산자를 사용하여 두 값을 비교합니다. 우리는 값이 다른 값보다 크거나 작거나 같은지 확인합니다. 다음 표는[w3shool](https://www.w3schools.com/python/python_operators.asp)에서 가져온 파이썬의 비교 연산자를 보여줍니다. ![Comparison Operators](../images/comparison_operators.png) -**Example: Comparison Operators** +**Example: 비교 연산자** ```py -print(3 > 2) # True, because 3 is greater than 2 -print(3 >= 2) # True, because 3 is greater than 2 -print(3 < 2) # False, because 3 is greater than 2 -print(2 < 3) # True, because 2 is less than 3 -print(2 <= 3) # True, because 2 is less than 3 -print(3 == 2) # False, because 3 is not equal to 2 -print(3 != 2) # True, because 3 is not equal to 2 -print(len('mango') == len('avocado')) # False -print(len('mango') != len('avocado')) # True -print(len('mango') < len('avocado')) # True -print(len('milk') != len('meat')) # False -print(len('milk') == len('meat')) # True -print(len('tomato') == len('potato')) # True -print(len('python') > len('dragon')) # False - - -# Comparing something gives either a True or False +print(3 > 2) # 참, 3이 2보다 크기 때문에 +print(3 >= 2) # 참, 3이 2보다 크기 때문에 +print(3 < 2) # 거짓, 3이 더 크기 때문에 +print(2 < 3) # 참, 2가 3보다 작기 때문에 +print(2 <= 3) # 참, 2가 3보다 작기 때문에 +print(3 == 2) # 거짓, 3과 2는 같지 않기 때문에 +print(3 != 2) # 참, 3은 2와 다르기 때문에 +print(len('mango') == len('avocado')) # 거짓 +print(len('mango') != len('avocado')) # 참 +print(len('mango') < len('avocado')) # 참 +print(len('milk') != len('meat')) # 거짓 +print(len('milk') == len('meat')) # 참 +print(len('tomato') == len('potato')) # 참 +print(len('python') > len('dragon')) # 거짓 + + +# 무언가를 비교하면 참 또는 거짓이 됩니다. print('True == True: ', True == True) print('True == False: ', True == False) print('False == False:', False == False) ``` -In addition to the above comparison operator Python uses: +위의 비교 연산자 외에 파이썬은 다음과 같은 연산자를 사용합니다: -- _is_: Returns true if both variables are the same object(x is y) -- _is not_: Returns true if both variables are not the same object(x is not y) -- _in_: Returns True if the queried list contains a certain item(x in y) -- _not in_: Returns True if the queried list doesn't have a certain item(x in y) +- _is_: 두 변수가 동일할 경우 참을 반환합니다.(x is y) +- _is not_: 두 변수가 동일하지 않을 경우 참을 반환합니다.(x is not y) +- _in_: 제시된 목록에 특정 항목이 포함된 경우 참을 반환합니다.(x in y) +- _not in_: 제시된 목록에 특정 항목이 없으면 참을 반환합니다.(x in y) ```py -print('1 is 1', 1 is 1) # True - because the data values are the same -print('1 is not 2', 1 is not 2) # True - because 1 is not 2 -print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string -print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B -print('coding' in 'coding for all') # True - because coding for all has the word coding -print('a in an:', 'a' in 'an') # True -print('4 is 2 ** 2:', 4 is 2 ** 2) # True +print('1 is 1', 1 is 1) # 참 - 데이터 값이 동일하기 때문에 +print('1 is not 2', 1 is not 2) # 참 - 1과 2는 다르기 때문에 +print('A in Asabeneh', 'A' in 'Asabeneh') # 참 - 문자열에서 A를 찾을 수 있습니다 +print('B in Asabeneh', 'B' in 'Asabeneh') # 거짓 - 대문자 B가 없습니다 +print('coding' in 'coding for all') # 참 - coding이라는 단어를 coding for all이 가지고 있기 때문에 +print('a in an:', 'a' in 'an') # 참 +print('4 is 2 ** 2:', 4 is 2 ** 2) # 참 ``` -### Logical Operators +### 논리 연산자 -Unlike other programming languages python uses keywords _and_, _or_ and _not_ for logical operators. Logical operators are used to combine conditional statements: +다른 프로그래밍 언어와 달리 파이썬은 논리 연산자를 위해 _and_, _or_, _not_ 키워드를 사용합니다. 논리 연산자는 다음과 같은 조건문을 결합하는 데 사용됩니다. ![Logical Operators](../images/logical_operators.png) ```py -print(3 > 2 and 4 > 3) # True - because both statements are true -print(3 > 2 and 4 < 3) # False - because the second statement is false -print(3 < 2 and 4 < 3) # False - because both statements are false +print(3 > 2 and 4 > 3) # 참 - 두 개의 문장이 참이기 때문에 +print(3 > 2 and 4 < 3) # 거짓 - 두 번째 문장이 거짓이기 때문에 +print(3 < 2 and 4 < 3) # 거짓 - 두 가지 문장 모두 거짓이기 때문에 print('True and True: ', True and True) -print(3 > 2 or 4 > 3) # True - because both statements are true -print(3 > 2 or 4 < 3) # True - because one of the statements is true -print(3 < 2 or 4 < 3) # False - because both statements are false +print(3 > 2 or 4 > 3) # 참 - 두 가지 문장 모두 참이기 때문에 +print(3 > 2 or 4 < 3) # 참 - 두 가지 중 하나의 문장이 참이기 때문에 +print(3 < 2 or 4 < 3) # 거짓 - 두 가지 문장 모두 거짓이기 때문에 print('True or False:', True or False) -print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False -print(not True) # False - Negation, the not operator turns true to false +print(not 3 > 2) # 거짓 - 3이 2보다 큰 것은 참이기 때문에, 참이 아닐 경우 거짓을 줍니다. +print(not True) # 거짓 - 부정으로 참에서 거짓으로 바뀝니다. print(not False) # True print(not not True) # True print(not not False) # False ``` -🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps ahead on your way to greatness. Now do some exercises for your brain and your muscles. +🌕 당신은 무한한 에너지를 가지고 있어요. 여러분은 이제 막 3일차 도전을 마쳤고 위대함으로 가는 길에 세 걸음 앞서 있습니다. 이제 여러분의 뇌와 근육을 위한 운동을 하세요. -## 💻 Exercises - Day 3 +## 💻 3일차: 실습 -1. Declare your age as integer variable -2. Declare your height as a float variable -3. Declare a variable that store a complex number -4. Write a script that prompts the user to enter base and height of the triangle and calculate an area of this triangle (area = 0.5 x b x h). +1. 나이를 정수 변수로 선언합니다. +2. 자신의 키를 플로트 변수로 선언합니다. +3. 복소수를 저장하는 변수 선언합니다. +4. 삼각형의 밑면과 높이를 입력하도록 사용자에게 지시하는 스크립트를 작성하고 이 삼각형의 면적(면적 = 0.5 x b x h)을 계산합니다. ```py Enter base: 20 @@ -263,7 +263,7 @@ print(not not False) # False The area of the triangle is 100 ``` -5. Write a script that prompts the user to enter side a, side b, and side c of the triangle. Calculate the perimeter of the triangle (perimeter = a + b + c). +5. 삼각형의 측면 a, 측면 b, 측면 c를 입력하라는 메시지를 표시하는 스크립트를 작성합니다. 삼각형의 둘레(지름 = a + b + c)를 계산합니다. ```py Enter side a: 5 @@ -272,22 +272,22 @@ Enter side c: 3 The perimeter of the triangle is 12 ``` -6. Get length and width of a rectangle using prompt. Calculate its area (area = length x width) and perimeter (perimeter = 2 x (length + width)) -7. Get radius of a circle using prompt. Calculate the area (area = pi x r x r) and circumference (c = 2 x pi x r) where pi = 3.14. -8. Calculate the slope, x-intercept and y-intercept of y = 2x -2 -9. Slope is (m = y2-y1/x2-x1). Find the slope and [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) between point (2, 2) and point (6,10) -10. Compare the slopes in tasks 8 and 9. -11. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is going to be 0. -12. Find the length of 'python' and 'dragon' and make a falsy comparison statement. -13. Use _and_ operator to check if 'on' is found in both 'python' and 'dragon' -14. _I hope this course is not full of jargon_. Use _in_ operator to check if _jargon_ is in the sentence. -15. There is no 'on' in both dragon and python -16. Find the length of the text _python_ and convert the value to float and convert it to string -17. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using python? -18. Check if the floor division of 7 by 3 is equal to the int converted value of 2.7. -19. Check if type of '10' is equal to type of 10 -20. Check if int('9.8') is equal to 10 -21. Writ a script that prompts the user to enter hours and rate per hour. Calculate pay of the person? +6. 프롬프트를 사용하여 직사각형의 길이와 너비를 가져옵니다. 면적(면적 = 길이 x 폭) 및 둘레(면적 = 2 x (길이 + 폭)) 계산합니다. +7. 프롬프트를 사용하여 원의 반지름을 구합니다. 면적(면적 = 픽스 r x r)과 원주(c = 2 x 픽스 r)를 계산합니다. 여기서 pi = 3.14입니다. +8. y = 2x-2의 기울기, x-제곱 및 y-제곱을 계산합니다. +9. 기울기는 (m = y2-y1/x2-x1)입니다. 기울기와 [유클리드 거리](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) 점(2,2)과 점(6,10) 사이를 구합니다. +10. 과제 8과 9의 기울기를 비교합니다. +11. y 값(y = x^2 + 6x + 9)을 계산합니다. 다른 x 값을 사용하고 y 값이 0이 되는 x 값을 계산해 보십시오. +12. 'python'과 'dragon'의 길이를 찾아 거짓 비교를 합니다. +13. _and_ 연산자를 사용하여 'python'과 'dragon' 모두에 'on'이 있는지 확인합니다. +14. _나는 이 강좌가 전문용어로 가득하지 않기를 바랍니다. _in_ 연산자를 사용하여 _jargon_ 이 문장에 있는지 확인합니다. +15. dragon과 python 모두 'On'이 없습니다. +16. _python_ 텍스트의 길이를 찾아서 값을 float로 변환하고 문자열로 변환합니다. +17. 짝수는 2로 나누고 나머지는 0입니다. 파이썬을 사용하여 숫자가 짝수인지 아닌지 어떻게 확인합니까? +18. 7 x 3의 나눗셈 버림이 2.7의 int 변환값과 동일한지 확인합니다. +19. '10'의 유형이 10의 유형과 동일한지 확인합니다. +20. if int('9)를 확인합니다.8')는 10과 같습니다. +21. 사용자에게 시간 및 시간당 요금을 입력하도록 요청하는 스크립트를 작성합니다. 그 사람의 급여를 계산합니까? ```py Enter hours: 40 @@ -295,14 +295,14 @@ Enter rate per hour: 28 Your weekly earning is 1120 ``` -22. Write a script that prompts the user to enter number of years. Calculate the number of seconds a person can live. Assume a person can live hundred years +22. 사용자에게 년 수를 입력하도록 요청하는 스크립트를 작성합니다. 사람이 살 수 있는 시간을 초 단위로 계산합니다. 사람이 100년을 살 수 있다고 가정합시다. ```py Enter number of years you have lived: 100 You have lived for 3153600000 seconds. ``` -23. Write a Python script that displays the following table +23. 다음을 표시하는 파이썬 스크립트를 작성합니다. ```py 1 1 1 1 1 @@ -312,6 +312,6 @@ You have lived for 3153600000 seconds. 5 1 5 25 125 ``` -🎉 CONGRATULATIONS ! 🎉 +🎉 축하합니다 ! 🎉 [<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md) From 2eb6c20726b0559b49988451f6e4ef94da0f5995 Mon Sep 17 00:00:00 2001 From: kjs1019 <68845945+kjs1019@users.noreply.github.com> Date: Thu, 8 Dec 2022 21:52:31 +0900 Subject: [PATCH 15/63] Update 03_operators.md --- korean/03_Day_Operators/03_operators.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/korean/03_Day_Operators/03_operators.md b/korean/03_Day_Operators/03_operators.md index e50972fc5..1cfff93d4 100644 --- a/korean/03_Day_Operators/03_operators.md +++ b/korean/03_Day_Operators/03_operators.md @@ -17,14 +17,14 @@ ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) -- [📘 3일차](#3일차) +- [📘 3일차](#-3일차) - [불리언](#불리언) - [연산자](#연산자) - [대입 연산자](#대입-연산자) - [산술 연산자:](#산술-연산자) - [비교 연산자](#비교-연산자) - [논리 연산자](#논리-연산자) - - [💻 3일차: 실습](3일차:-실습) + - [💻 3일차: 실습](#-3일차-실습) # 📘 3일차 @@ -250,7 +250,7 @@ print(not not False) # False 🌕 당신은 무한한 에너지를 가지고 있어요. 여러분은 이제 막 3일차 도전을 마쳤고 위대함으로 가는 길에 세 걸음 앞서 있습니다. 이제 여러분의 뇌와 근육을 위한 운동을 하세요. -## 💻 3일차: 실습 +## 💻 3일차 실습 1. 나이를 정수 변수로 선언합니다. 2. 자신의 키를 플로트 변수로 선언합니다. @@ -283,10 +283,10 @@ The perimeter of the triangle is 12 14. _나는 이 강좌가 전문용어로 가득하지 않기를 바랍니다. _in_ 연산자를 사용하여 _jargon_ 이 문장에 있는지 확인합니다. 15. dragon과 python 모두 'On'이 없습니다. 16. _python_ 텍스트의 길이를 찾아서 값을 float로 변환하고 문자열로 변환합니다. -17. 짝수는 2로 나누고 나머지는 0입니다. 파이썬을 사용하여 숫자가 짝수인지 아닌지 어떻게 확인합니까? +17. 짝수는 2로 나누고 나머지는 0입니다. 파이썬을 사용하여 숫자가 짝수인지 아닌지 어떻게 확인하겠습니까? 18. 7 x 3의 나눗셈 버림이 2.7의 int 변환값과 동일한지 확인합니다. 19. '10'의 유형이 10의 유형과 동일한지 확인합니다. -20. if int('9)를 확인합니다.8')는 10과 같습니다. +20. if int('9.8')이 10과 같은지 확인합니다. 21. 사용자에게 시간 및 시간당 요금을 입력하도록 요청하는 스크립트를 작성합니다. 그 사람의 급여를 계산합니까? ```py From 2929ed04cd8a4aae68969846954e452f0ac6b2a8 Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Fri, 9 Dec 2022 10:27:16 +0900 Subject: [PATCH 16/63] kor ver --- Korean/04_strings_ko.md | 591 ++++++++++++++++++++++++++++++++++++++++ Korean/readme_ko.md | 454 ++++++++++++++++++++++++++++++ 2 files changed, 1045 insertions(+) create mode 100644 Korean/04_strings_ko.md create mode 100644 Korean/readme_ko.md diff --git a/Korean/04_strings_ko.md b/Korean/04_strings_ko.md new file mode 100644 index 000000000..b2d92dee8 --- /dev/null +++ b/Korean/04_strings_ko.md @@ -0,0 +1,591 @@ +
+ 30 Days Of Python: Day 4 - Strings Twitter Follow +
+

Author: Asabeneh Yetayeh
Second Edition: July, 2021

+
+ +[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_lists.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [Day 4](#day-4) + - [문자열](#strings) + - [문자열 만들기](#creating-a-string) + - [문자열 연결](#string-concatenation) + - [문자열의 이스케이프 시퀀스](#escape-sequences-in-strings) + - [문자열 포매팅](#string-formatting) + - [올드 스타일 문자열 포매팅(% 연산자)](#old-style-string-formatting--operator) + - [새로운 스타일 문자열 포매팅(str.format)](#new-style-string-formatting-strformat) + - [문자열 Interpolation / f-Strings (Python 3.6+)](#string-interpolation--f-strings-python-36) + - [문자 시퀀스로서의 Python 문자열](#python-strings-as-sequences-of-characters) + - [언패킹 문자](#unpacking-characters) + - [인덱스로 문자열의 문자에 액세스](#accessing-characters-in-strings-by-index) + - [파이썬 문자열 슬라이싱](#slicing-python-strings) + - [문자열 리버스](#reversing-a-string) + - [슬라이싱하는 동안 문자 건너뛰기](#skipping-characters-while-slicing) + - [문자열 메서드](#string-methods) + - [💻 Exercises - Day 4](#-exercises---day-4) + +# Day 4 + +## 문자열 + +텍스트는 문자열 데이터 유형입니다. 텍스트로 작성된 모든 데이터 유형은 문자열입니다. 작은따옴표, 큰따옴표 또는 삼중따옴표 아래의 모든 데이터는 문자열입니다. 문자열 데이터 유형을 처리하기 위한 다양한 문자열 메서드와 내장 함수가 있습니다. 문자열의 길이를 확인하려면 len() 메서드를 사용하십시오. + +### 문자열 만들기 + +```py +letter = 'P' # A string could be a single character or a bunch of texts +print(letter) # P +print(len(letter)) # 1 +greeting = 'Hello, World!' # String could be made using a single or double quote,"Hello, World!" +print(greeting) # Hello, World! +print(len(greeting)) # 13 +sentence = "I hope you are enjoying 30 days of Python Challenge" +print(sentence) +``` + +여러 줄 문자열은 세 개의 작은따옴표(''') 또는 세 개의 큰따옴표(""")를 사용하여 생성됩니다. 아래 예를 참조하십시오. + +```py +multiline_string = '''I am a teacher and enjoy teaching. +I didn't find anything as rewarding as empowering people. +That is why I created 30 days of python.''' +print(multiline_string) + +# Another way of doing the same thing +multiline_string = """I am a teacher and enjoy teaching. +I didn't find anything as rewarding as empowering people. +That is why I created 30 days of python.""" +print(multiline_string) +``` + +### 문자열 연결 + +문자열을 함께 연결할 수 있습니다. 문자열을 병합하거나 연결하는 것을 연결이라고 합니다. 아래 예를 참조하십시오. + +```py +first_name = 'Asabeneh' +last_name = 'Yetayeh' +space = ' ' +full_name = first_name + space + last_name +print(full_name) # Asabeneh Yetayeh +# Checking the length of a string using len() built-in function +print(len(first_name)) # 8 +print(len(last_name)) # 7 +print(len(first_name) > len(last_name)) # True +print(len(full_name)) # 16 +``` + +### 문자열의 이스케이프 시퀀스 + +Python 및 기타 프로그래밍 언어에서 \ 다음에 오는 문자는 이스케이프 시퀀스입니다. 가장 일반적인 이스케이프 문자를 살펴보겠습니다. + +- \n: 새로운 라인 +- \t: 탭은(8칸)을 의미합니다. +- \\: 백슬래시 +- \': 작은따옴표(') +- \": 큰따옴표(") + +이제 위의 이스케이프 시퀀스를 예제와 함께 사용하는 방법을 살펴보겠습니다. + +```py +print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # line break +print('Days\tTopics\tExercises') # adding tab space or 4 spaces +print('Day 1\t3\t5') +print('Day 2\t3\t5') +print('Day 3\t3\t5') +print('Day 4\t3\t5') +print('This is a backslash symbol (\\)') # To write a backslash +print('In every programming language it starts with \"Hello, World!\"') # to write a double quote inside a single quote + +# output +I hope every one is enjoying the Python Challenge. +Are you ? +Days Topics Exercises +Day 1 5 5 +Day 2 6 20 +Day 3 5 23 +Day 4 1 35 +This is a backslash symbol (\) +In every programming language it starts with "Hello, World!" +``` + +### 문자열 포매팅 + +#### 올드 스타일 문자열 형식화(% 연산자) + +Python에는 문자열 형식을 지정하는 여러 가지 방법이 있습니다. 이 섹션에서는 그 중 일부를 다룰 것입니다. "%" 연산자는 "인수 지정자", "%s"와 같은 특수 기호와 함께 일반 텍스트를 포함하는 형식 문자열과 함께 "튜플"(고정 크기 목록)로 묶인 변수 세트의 형식을 지정하는 데 사용됩니다. , "%d", "%f", "%. 자릿수 f". + +- %s - 문자열(또는 숫자와 같은 문자열 표현이 있는 모든 객체) +- %d - 정수 +- %f - 부동 소수점 숫자 +- "%. number of digits f" - 정밀도가 고정된 부동 소수점 숫자 + +```py +# Strings only +first_name = 'Asabeneh' +last_name = 'Yetayeh' +language = 'Python' +formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language) +print(formated_string) + +# Strings and numbers +radius = 10 +pi = 3.14 +area = pi * radius ** 2 +formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the point + +python_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas'] +formated_string = 'The following are python libraries:%s' % (python_libraries) +print(formated_string) # "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']" +``` + +#### 새로운스타일 문자열 형식화(str.format) + +이 형식은 Python 버전 3에서 도입되었습니다. + +```py + +first_name = 'Asabeneh' +last_name = 'Yetayeh' +language = 'Python' +formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language) +print(formated_string) +a = 4 +b = 3 + +print('{} + {} = {}'.format(a, b, a + b)) +print('{} - {} = {}'.format(a, b, a - b)) +print('{} * {} = {}'.format(a, b, a * b)) +print('{} / {} = {:.2f}'.format(a, b, a / b)) # limits it to two digits after decimal +print('{} % {} = {}'.format(a, b, a % b)) +print('{} // {} = {}'.format(a, b, a // b)) +print('{} ** {} = {}'.format(a, b, a ** b)) + +# output +4 + 3 = 7 +4 - 3 = 1 +4 * 3 = 12 +4 / 3 = 1.33 +4 % 3 = 1 +4 // 3 = 1 +4 ** 3 = 64 + +# Strings and numbers +radius = 10 +pi = 3.14 +area = pi * radius ** 2 +formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal +print(formated_string) + +``` + +#### 문자열 Interpolation / f-Strings (Python 3.6+) + +또 다른 새로운 문자열 형식화는 문자열 보간법인 f-문자열입니다. 문자열은 f로 시작하고 해당 위치에 데이터를 주입할 수 있습니다. + +```py +a = 4 +b = 3 +print(f'{a} + {b} = {a +b}') +print(f'{a} - {b} = {a - b}') +print(f'{a} * {b} = {a * b}') +print(f'{a} / {b} = {a / b:.2f}') +print(f'{a} % {b} = {a % b}') +print(f'{a} // {b} = {a // b}') +print(f'{a} ** {b} = {a ** b}') +``` + +### 문자 시퀀스로서의 Python 문자열 + +Python 문자열은 문자 시퀀스이며, 기본 액세스 방법을 다른 Python 순서 객체 시퀀스(목록 및 튜플)와 공유합니다. 문자열(및 모든 시퀀스의 개별 멤버)에서 단일 문자를 추출하는 가장 간단한 방법은 해당 변수로 압축을 푸는 것입니다. + +#### 언패킹 문자 + +``` +language = 'Python' +a,b,c,d,e,f = language # unpacking sequence characters into variables +print(a) # P +print(b) # y +print(c) # t +print(d) # h +print(e) # o +print(f) # n +``` + +#### 인덱스로 문자열의 문자에 액세스 + +프로그래밍에서 카운팅은 0부터 시작합니다. 따라서 문자열의 첫 번째 문자는 인덱스가 0이고 문자열의 마지막 문자는 문자열의 길이에서 1을 뺀 값입니다. + +![String index](../images/string_index.png) + +```py +language = 'Python' +first_letter = language[0] +print(first_letter) # P +second_letter = language[1] +print(second_letter) # y +last_index = len(language) - 1 +last_letter = language[last_index] +print(last_letter) # n +``` + +오른쪽 끝에서 시작하려면 음수 인덱싱을 사용할 수 있습니다. -1은 마지막 인덱스입니다. + +```py +language = 'Python' +last_letter = language[-1] +print(last_letter) # n +second_last = language[-2] +print(second_last) # o +``` + +#### 파이썬 문자열 슬라이싱 + +파이썬에서는 문자열을 하위 문자열로 슬라이스할 수 있습니다. + +```py +language = 'Python' +first_three = language[0:3] # starts at zero index and up to 3 but not include 3 +print(first_three) #Pyt +last_three = language[3:6] +print(last_three) # hon +# Another way +last_three = language[-3:] +print(last_three) # hon +last_three = language[3:] +print(last_three) # hon +``` + +#### 문자열 리버스 + +파이썬에서 문자열을 쉽게 뒤집을 수 있습니다. + +```py +greeting = 'Hello, World!' +print(greeting[::-1]) # !dlroW ,olleH +``` + +#### 슬라이싱하는 동안 문자 건너뛰기 + +슬라이스 메소드에 단계 인수를 전달하여 슬라이스하는 동안 문자를 건너뛸 수 있습니다. + +```py +language = 'Python' +pto = language[0:6:2] # +print(pto) # Pto +``` + +### 문자열 메서드 + +문자열을 형식화할 수 있는 많은 문자열 메서드가 있습니다. 다음 예제에서 일부 문자열 메서드를 참조하십시오. + +- capitalize(): 문자열의 첫 번째 문자를 대문자로 변환 + +```py +challenge = 'thirty days of python' +print(challenge.capitalize()) # 'Thirty days of python' +``` + +- count(): 문자열에서 하위 문자열의 발생을 반환합니다. count(substring, start=.., end=..). 시작은 카운트를 위한 시작 인덱싱이고 끝은 카운트할 마지막 인덱스입니다. + +```py +challenge = 'thirty days of python' +print(challenge.count('y')) # 3 +print(challenge.count('y', 7, 14)) # 1, +print(challenge.count('th')) # 2` +``` + +- endswith(): 문자열이 지정된 끝으로 끝나는지 확인합니다. + +```py +challenge = 'thirty days of python' +print(challenge.endswith('on')) # True +print(challenge.endswith('tion')) # False +``` + +- expandtabs(): 탭 문자를 공백으로 바꿉니다. 기본 탭 크기는 8입니다. 탭 크기 인수를 사용합니다. + +```py +challenge = 'thirty\tdays\tof\tpython' +print(challenge.expandtabs()) # 'thirty days of python' +print(challenge.expandtabs(10)) # 'thirty days of python' +``` + +- find(): 하위 문자열이 처음 나타나는 인덱스를 반환합니다. 찾을 수 없으면 -1을 반환합니다. + +```py +challenge = 'thirty days of python' +print(challenge.count('y')) # 3 +print(challenge.count('y', 7, 14)) # 1, +print(challenge.count('th')) # 2` +``` + +- rfind(): 하위 문자열이 마지막으로 나타나는 인덱스를 반환합니다. 찾을 수 없으면 -1을 반환합니다. + +```py +challenge = 'thirty days of python' +print(challenge.rfind('y')) # 5 +print(challenge.rfind('th')) # 1 +``` + +- format(): 문자열을 더 나은 출력으로 포맷합니다.
문자열 형식에 대한 자세한 내용은 이 [링크](https://www.programiz.com/python-programming/methods/string/format) 를 확인하세요. + +```py +first_name = 'Asabeneh' +last_name = 'Yetayeh' +age = 250 +job = 'teacher' +country = 'Finland' +sentence = 'I am {} {}. I am a {}. I am {} years old. I live in {}.'.format(first_name, last_name, age, job, country) +print(sentence) # I am Asabeneh Yetayeh. I am 250 years old. I am a teacher. I live in Finland. + +radius = 10 +pi = 3.14 +area = pi * radius ** 2 +result = 'The area of a circle with radius {} is {}'.format(str(radius), str(area)) +print(result) # The area of a circle with radius 10 is 314 +``` + +- index(): 하위 문자열의 가장 낮은 색인을 반환하고 추가 인수는 시작 및 끝 색인을 나타냅니다(기본값 0 및 문자열 길이 - 1). 하위 문자열을 찾을 수 없으면 valueError가 발생합니다. + +```py +challenge = 'thirty days of python' +sub_string = 'da' +print(challenge.index(sub_string)) # 7 +print(challenge.index(sub_string, 9)) # error +``` + +- rindex(): 하위 문자열의 가장 높은 색인을 반환합니다. 추가 인수는 시작 및 끝 색인을 나타냅니다(기본값 0 및 문자열 길이 - 1). + +```py +challenge = 'thirty days of python' +sub_string = 'da' +print(challenge.rindex(sub_string)) # 8 +print(challenge.rindex(sub_string, 9)) # error +``` + +- isalnum(): 영숫자 확인 + +```py +challenge = 'ThirtyDaysPython' +print(challenge.isalnum()) # True + +challenge = '30DaysPython' +print(challenge.isalnum()) # True + +challenge = 'thirty days of python' +print(challenge.isalnum()) # False, space is not an alphanumeric character + +challenge = 'thirty days of python 2019' +print(challenge.isalnum()) # False +``` + +- isalpha(): 모든 문자열 요소가 알파벳 문자(az 및 AZ)인지 확인합니다. + +```py +challenge = 'thirty days of python' +print(challenge.isalpha()) # False, space is once again excluded +challenge = 'ThirtyDaysPython' +print(challenge.isalpha()) # True +num = '123' +print(num.isalpha()) # False +``` + +- isdecimal(): 문자열의 모든 문자가 십진수(0-9)인지 확인합니다. + +```py +challenge = 'thirty days of python' +print(challenge.isdecimal()) # False +challenge = '123' +print(challenge.isdecimal()) # True +challenge = '\u00B2' +print(challenge.isdigit()) # False +challenge = '12 3' +print(challenge.isdecimal()) # False, space not allowed +``` + +- isdigit(): 문자열의 모든 문자가 숫자인지 확인합니다(숫자는 0-9 및 일부 다른 유니코드 문자). + +```py +challenge = 'Thirty' +print(challenge.isdigit()) # False +challenge = '30' +print(challenge.isdigit()) # True +challenge = '\u00B2' +print(challenge.isdigit()) # True +``` + +- isnumeric(): 문자열의 모든 문자가 숫자인지 또는 숫자와 관련된 것인지 확인합니다(isdigit()와 마찬가지로 ½과 같은 더 많은 기호를 허용합니다). + +```py +num = '10' +print(num.isnumeric()) # True +num = '\u00BD' # ½ +print(num.isnumeric()) # True +num = '10.5' +print(num.isnumeric()) # False +``` + +- isidentifier(): 유효한 식별자를 확인합니다. 문자열이 유효한 변수 이름인지 확인합니다. + +```py +challenge = '30DaysOfPython' +print(challenge.isidentifier()) # False, because it starts with a number +challenge = 'thirty_days_of_python' +print(challenge.isidentifier()) # True +``` + +- islower(): 문자열의 모든 알파벳 문자가 소문자인지 확인 + +```py +challenge = 'thirty days of python' +print(challenge.islower()) # True +challenge = 'Thirty days of python' +print(challenge.islower()) # False +``` + +- islower(): 문자열의 모든 알파벳 문자가 소문자인지 확인 + +```py +challenge = 'thirty days of python' +print(challenge.isupper()) # False +challenge = 'THIRTY DAYS OF PYTHON' +print(challenge.isupper()) # True +``` + +- join(): 연결된 문자열을 반환합니다. + +```py +web_tech = ['HTML', 'CSS', 'JavaScript', 'React'] +result = ' '.join(web_tech) +print(result) # 'HTML CSS JavaScript React' +``` + +```py +web_tech = ['HTML', 'CSS', 'JavaScript', 'React'] +result = '# '.join(web_tech) +print(result) # 'HTML# CSS# JavaScript# React' +``` + +- strip(): 문자열의 시작과 끝에서 시작하여 주어진 모든 문자를 제거합니다. + +```py +challenge = 'thirty days of pythoonnn' +print(challenge.strip('noth')) # 'irty days of py' +``` + +- replace(): 하위 문자열을 주어진 문자열로 대체합니다. + +```py +challenge = 'thirty days of python' +print(challenge.replace('python', 'coding')) # 'thirty days of coding' +``` + +- split(): 주어진 문자열 또는 공백을 구분 기호로 사용하여 문자열을 분할합니다. + +```py +challenge = 'thirty days of python' +print(challenge.split()) # ['thirty', 'days', 'of', 'python'] +challenge = 'thirty, days, of, python' +print(challenge.split(', ')) # ['thirty', 'days', 'of', 'python'] +``` + +- title(): 제목 케이스 문자열을 반환합니다. + +```py +challenge = 'thirty days of python' +print(challenge.title()) # Thirty Days Of Python +``` + +- swapcase(): 모든 대문자를 소문자로, 모든 소문자를 대문자로 변환 + +```py +challenge = 'thirty days of python' +print(challenge.swapcase()) # THIRTY DAYS OF PYTHON +challenge = 'Thirty Days Of Python' +print(challenge.swapcase()) # tHIRTY dAYS oF pYTHON +``` + +- startswith(): 문자열이 지정된 문자열로 시작하는지 확인 + +```py +challenge = 'thirty days of python' +print(challenge.startswith('thirty')) # True + +challenge = '30 days of python' +print(challenge.startswith('thirty')) # False +``` + +🌕 당신은 특별한 사람이고 놀라운 잠재력을 가지고 있습니다. 당신은 방금 4일 차 도전을 완료했고 당신은 위대함을 향한 당신의 길에 4걸음 남았습니다. 이제 뇌와 근육을 위한 몇 가지 훈련을 하십시오. + +## 💻 Exercises - Day 4 + +1. 문자열 'Thirty', 'Days', 'Of', 'Python'을 단일 문자열 'Thirty Days Of Python'에 연결합니다. +2. 문자열 'Coding', 'For' , 'All'을 단일 문자열 'Coding For All'에 연결합니다. +3. company라는 변수를 선언하고 초기 값 "Coding For All"에 할당합니다. +4. *print()* 를 사용하여 회사 변수를 인쇄합니다. +5. *len()* 메서드와 *print()* 를 사용하여 회사 문자열의 길이를 인쇄합니다. +6. *upper()* 메서드를 사용하여 모든 문자를 대문자로 변경합니다. +7. *lower()* 메서드를 사용하여 모든 문자를 소문자로 변경합니다. +8. 문자열 *Coding For All* 의 값을 형식화하려면 capitalize(), title(), swapcase() 메소드를 사용하십시오. +9. *Coding For All* 문자열의 첫 번째 단어를 잘라냅니다. +10. Index, find 또는 기타 방법을 사용하여 *Coding For All* 문자열에 단어 Coding이 포함되어 있는지 확인합니다. +11. 문자열 'Coding For All'의 코딩이라는 단어를 Python으로 바꿉니다. +12. replace 메서드 또는 기타 메서드를 사용하여 모두를 위한 Python을 모두를 위한 Python으로 변경합니다. +13. 공백을 구분 기호로 사용하여 문자열 'Coding For All'을 분할합니다(split()). +14. "Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon"은 쉼표에서 문자열을 나눕니다. +15. 문자열 *Coding For All* 에서 인덱스 0에 있는 문자는 무엇입니까? +16. 문자열 *Coding For All* 에서 인덱스 0에 있는 문자는 무엇입니까? +17. "Coding For All" 문자열에서 인덱스 10에 있는 문자는 무엇입니까? +18. 'Python For Everyone'이라는 이름의 약어 또는 약어를 만듭니다. +19. 'Coding For All'이라는 이름의 약어 또는 약어를 만듭니다. +20. Index를 사용하여 Coding For All에서 C가 처음 나타나는 위치를 결정합니다. +21. Index를 사용하여 Coding For All에서 F가 처음 나타나는 위치를 결정합니다. +22. Coding For All People에서 l이 마지막으로 나타나는 위치를 결정하려면 rfind를 사용하십시오. +23. 색인 또는 찾기를 사용하여 다음 문장에서 'because'라는 단어가 처음 나타나는 위치를 찾습니다. +24. 색인 또는 찾기를 사용하여 다음 문장에서 'because'라는 단어가 처음 나타나는 위치를 찾습니다. +25. 색인 또는 찾기를 사용하여 다음 문장에서 'because'라는 단어가 처음 나타나는 위치를 찾습니다. +26. 색인 또는 찾기를 사용하여 다음 문장에서 'because'라는 단어가 처음 나타나는 위치를 찾습니다. +27. 다음 문장에서 'because because because'라는 구문을 잘라냅니다. +28. 'Coding For All'은 하위 문자열 *Coding* 으로 시작합니까? +29. 'Coding For All'은 하위 문자열 *코딩* 으로 끝납니까? +30. ' Coding For All ' , 주어진 문자열에서 왼쪽 및 오른쪽 후행 공백을 제거합니다. +31. 다음 변수 중 isidentifier() 메서드를 사용할 때 True를 반환하는 변수는 무엇입니까? + - 30DaysOfPython + - thirty_days_of_python +32. 다음 목록에는 일부 파이썬 라이브러리의 이름이 포함되어 있습니다: ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']. 공백 문자열이 있는 해시로 목록에 가입하십시오. +33. 새 줄 이스케이프 시퀀스를 사용하여 다음 문장을 구분합니다. + ```py + I am enjoying this challenge. + I just wonder what is next. + ``` +34. 새 줄 이스케이프 시퀀스를 사용하여 다음 문장을 구분합니다. + ```py + Name Age Country City + Asabeneh 250 Finland Helsinki + ``` +35. 문자열 형식 지정 방법을 사용하여 다음을 표시합니다: + +```sh +radius = 10 +area = 3.14 * radius ** 2 +The area of a circle with radius 10 is 314 meters square. +``` + +1. 문자열 형식화 방법을 사용하여 다음을 작성하십시오: + +```sh +8 + 6 = 14 +8 - 6 = 2 +8 * 6 = 48 +8 / 6 = 1.33 +8 % 6 = 2 +8 // 6 = 1 +8 ** 6 = 262144 +``` + +🎉 축하합니다! 🎉 + +[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_lists.md) diff --git a/Korean/readme_ko.md b/Korean/readme_ko.md new file mode 100644 index 000000000..bc6286096 --- /dev/null +++ b/Korean/readme_ko.md @@ -0,0 +1,454 @@ +# 🐍 30 Days Of Python + +|# Day | Topics | +|------|:---------------------------------------------------------:| +| 01 | [Introduction](./readme_ko.md)| +| 02 | [Variables, Built-in Functions](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| +| 03 | [Operators](../03_Day_Operators/03_operators.md)| +| 04 | [Strings](../04_Day_Strings/04_strings.md)| +| 05 | [Lists](../05_Day_Lists/05_lists.md)| +| 06 | [Tuples](../06_Day_Tuples/06_tuples.md)| +| 07 | [Sets](../07_Day_Sets/07_sets.md)| +| 08 | [Dictionaries](../08_Day_Dictionaries/08_dictionaries.md)| +| 09 | [Conditionals](../09_Day_Conditionals/09_conditionals.md)| +| 10 | [Loops](../10_Day_Loops/10_loops.md)| +| 11 | [Functions](../11_Day_Functions/11_functions.md)| +| 12 | [Modules](../12_Day_Modules/12_modules.md)| +| 13 | [List Comprehension](../13_Day_List_comprehension/13_list_comprehension.md)| +| 14 | [Higher Order Functions](../14_Day_Higher_order_functions/14_higher_order_functions.md)| +| 15 | [Python Type Errors](../15_Day_Python_type_errors/15_python_type_errors.md)| +| 16 | [Python Date time](../16_Day_Python_date_time/16_python_datetime.md) | +| 17 | [Exception Handling](../17_Day_Exception_handling/17_exception_handling.md)| +| 18 | [Regular Expressions](../18_Day_Regular_expressions/18_regular_expressions.md)| +| 19 | [File Handling](../19_Day_File_handling/19_file_handling.md)| +| 20 | [Python Package Manager](../20_Day_Python_package_manager/20_python_package_manager.md)| +| 21 | [Classes and Objects](../21_Day_Classes_and_objects/21_classes_and_objects.md)| +| 22 | [Web Scraping](../22_Day_Web_scraping/22_web_scraping.md)| +| 23 | [Virtual Environment](../23_Day_Virtual_environment/23_virtual_environment.md)| +| 24 | [Statistics](../24_Day_Statistics/24_statistics.md)| +| 25 | [Pandas](../25_Day_Pandas/25_pandas.md)| +| 26 | [Python web](../26_Day_Python_web/26_python_web.md)| +| 27 | [Python with MongoDB](../27_Day_Python_with_mongodb/27_python_with_mongodb.md)| +| 28 | [API](../28_Day_API/28_API.md)| +| 29 | [Building API](../29_Day_Building_API/29_building_API.md)| +| 30 | [Conclusions](../30_Day_Conclusions/30_conclusions.md)| + +🧡🧡🧡 HAPPY CODING 🧡🧡🧡 + +
+Support the author to create more educational materials
+Paypal Logo +
+ +
+

30 Days Of Python: Day 1 - Introduction

+ + + + + Twitter Follow + + + Author: + Asabeneh Yetayeh
+ Second Edition: July, 2021 +
+
+ + +[Day 2 >>](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [🐍 30 Days Of Python](#-30-days-of-python) +- [📘 Day 1](#-day-1) + - [환영합니다](#환영합니다) + - [소개](#소개) + - [왜 Python이느냐?](#왜-python이느냐?) + - [환경 설정](#환경-설정) + - [Python 설치](#python-설치) + - [Python 셸](#python-셸) + - [Visual Studio Code 설치](#visual-studio-code-설치) + - [visual studio code를 사용하기](#visual-studio-code를-사용하기) + - [Python 기본](#python-기본) + - [Python 구문](#python-구문) + - [Python 들여쓰기](#python-들여쓰기) + - [주석](#주석) + - [데이터 타입](#데이터-타입) + - [Number](#number) + - [String](#string) + - [Booleans](#booleans) + - [List](#list) + - [Dictionary](#dictionary) + - [Tuple](#tuple) + - [Set](#set) + - [데이터 타입 체크](#데이터-타입-체크) + - [Python 파일](#python-파일) + - [💻 Exercises - Day 1](#-exercises---day-1) + - [Exercise: Level 1](#exercise-level-1) + - [Exercise: Level 2](#exercise-level-2) + - [Exercise: Level 3](#exercise-level-3) + +# 📘 Day 1 + +## 환영합니다 + +_30 days of Python_에 참여하기로 결정하신 것을 **축하드립니다**. 이 챌린지에서는 Python 프로그래머가 되기 위해 필요한 모든 것과 프로그래밍의 전체 개념을 배우게 됩니다. 챌린지가 끝나면 _30DaysOfPython_프로그래밍 챌린지 인증서를 받게 됩니다. + +챌린지에 적극적으로 참여하고 싶다면 [30DaysOfPython challenge](https://t.me/ThirtyDaysOfPython) 텔레그램 그룹에 가입할 수 있습니다. + +## 소개 + +Python은 범용 프로그래밍을 위한 고급 프로그래밍 언어입니다. 오픈 소스, 인터프리터, 객체 지향 프로그래밍 언어입니다. Python은 네덜란드 프로그래머 Guido van Rossum이 만들었습니다. Python 프로그래밍 언어의 이름은 영국 스케치 코미디 시리즈 *Month Python's Flying Circus* 에서 파생되었습니다. 첫 번째 버전은 1991년 2월 20일에 출시되었습니다. 이 30일간의 Python 챌린지는 최신 버전의 Python인 Python 3를 차근차근 배울 수 있도록 도와줄 것입니다. 주제는 30일로 나뉘며, 매일 이해하기 쉬운 설명, 실제 사례, 많은 실습 및 프로젝트가 포함된 여러 주제가 포함됩니다. + +이 챌린지는 Python 프로그래밍 언어를 배우고자 하는 초보자와 전문가를 위해 고안되었습니다. 챌린지를 완료하는 데 30~100일이 소요될 수 있으며 텔레그램 그룹에 적극적으로 참여하는 사람들이 챌린지를 완료할 확률이 높습니다. +시각적 학습자이거나 동영상을 선호하는 경우 이 [완전 초보를 위한 Python 동영상](https://www.youtube.com/watch?v=11OYpBrhdyM)으로 시작할 수 있습니다. + +## 왜 Python이느냐? + +인간의 언어에 매우 가깝고 배우기 쉽고 사용하기 쉬운 프로그래밍 언어입니다. +Python은 다양한 산업 및 회사(Google 포함)에서 사용됩니다. 웹 응용 프로그램, 데스크톱 응용 프로그램, 시스템 관리 및 기계 학습 라이브러리를 개발하는 데 사용되었습니다. Python은 데이터 과학 및 기계 학습 커뮤니티에서 널리 사용되는 언어입니다. 이것이 Python 학습을 시작하도록 설득하기에 충분하기를 바랍니다. Python은 세상을 지배하고 있으니 지배 당하기 전에 Python을 지배하십시오. +## 환경 설정 + +### Python 설치 + +Python 스크립트를 실행하려면 Python을 설치해야 합니다. Python을 [다운로드](https://www.python.org/)합시다. +Windows 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니다. + + + +macOS 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니다. + +[![Windows에서 설치](../images/installing_on_windows.png)](https://www.python.org/) + +Python이 설치되어 있는지 확인하려면 장치 터미널에 다음 명령을 작성하십시오. + +```shell +python --version +``` + +![Python Version](../images/python_versio.png) + +터미널에서 보시다시피 저는 현재 _Python 3.7.5_ 버전을 사용하고 있습니다. 귀하의 Python 버전은 내 버전과 다를 수 있지만 3.6 이상이어야 합니다. Python 버전을 볼 수 있다면 잘한 것입니다. 이제 컴퓨터에 Python이 설치되었습니다. 다음 섹션으로 계속 진행하십시오. + +### Python 셸 + +Python은 해석된 스크립팅 언어이므로 컴파일할 필요가 없습니다. 코드를 한 줄씩 실행한다는 의미입니다. Python은 _Python Shell(Python Interactive Shell)_과 함께 제공됩니다. 단일 Python 명령을 실행하고 결과를 얻는 데 사용됩니다. + +Python Shell은 사용자의 Python 코드를 기다립니다. 코드를 입력하면 코드를 해석하여 다음 줄에 결과를 표시합니다. +터미널이나 명령 프롬프트(cmd)를 열고 쓰기: + +```shell +python +``` + +![Python Scripting Shell](../images/opening_python_shell.png) + +Python 대화형 셸이 열리고 Python 코드(Python 스크립트)를 작성하기를 기다립니다. 기호 >>> 옆에 Python 스크립트를 작성하고 Enter를 누릅니다. +Python 스크립팅 셸에서 첫 번째 스크립트를 작성해 보겠습니다. + +![Python script on Python shell](../images/adding_on_python_shell.png) + +훌륭합니다. Python 대화형 셸에서 첫 번째 Python 스크립트를 작성했습니다. Python 대화형 셸을 어떻게 닫습니까? +셸을 닫으려면 기호 옆에 >> **exit()** 명령을 작성하고 Enter 키를 누릅니다. + +![Exit from python shell](../images/exit_from_shell.png) + +이제 Python 대화형 셸을 여는 방법과 종료하는 방법을 알았습니다. + +Python은 Python이 이해하는 스크립트를 작성하면 결과를 제공하고 그렇지 않으면 오류를 반환합니다. 고의적인 실수를 하고 Python이 무엇을 반환하는지 봅시다. + +![Invalid Syntax Error](../images/invalid_syntax_error.png) + +반환된 오류에서 볼 수 있듯이 Python은 우리가 저지른 실수와 _Syntax Error: invalid syntax_를 알고 있을 정도로 영리합니다. Python에서 x를 곱셈으로 사용하는 것은 (x)가 Python에서 유효한 구문이 아니기 때문에 구문 오류입니다. (**x**) 대신 곱셈에 별표(*)를 사용합니다. 반환된 오류는 수정해야 할 사항을 명확하게 보여줍니다. + +프로그램에서 오류를 식별하고 제거하는 프로세스를 *디버깅*이라고 합니다. **x** 대신 *를 넣어 디버깅해 봅시다. + +![Fixing Syntax Error](../images/fixing_syntax_error.png) + +버그가 수정되었고 코드가 실행되었으며 예상했던 결과를 얻었습니다. 프로그래머로서 매일 이러한 종류의 오류를 보게 될 것입니다. 디버깅 방법을 아는 것이 좋습니다. 디버깅을 잘하려면 어떤 종류의 오류가 발생했는지 이해해야 합니다. 발생할 수 있는 Python 오류 중 일부는 *SyntaxError*, *IndexError*, *NameError*, *ModuleNotFoundError*, *KeyError*, *ImportError*, *AttributeError*, *TypeError*, *ValueError*, *ZeroDivisionError* 등입니다. 이후 섹션에서 다른 Python **_오류 유형_**에 대해 자세히 알아볼 것입니다. + +Python 대화형 셸을 사용하는 방법을 더 연습해 보겠습니다. 터미널이나 명령 프롬프트로 이동하여 **python**이라는 단어를 씁니다. + +![Python Scripting Shell](../images/opening_python_shell.png) + +Python 대화형 셸이 열립니다. 몇 가지 기본적인 수학 연산(더하기, 빼기, 곱하기, 나누기, 나머지, 지수)을 수행해 보겠습니다. + +Python 코드를 작성하기 전에 먼저 몇 가지 수학을 수행해 보겠습니다: + +- 2 + 3 = 5 +- 3 - 2 = 1 +- 3 \* 2 = 6 +- 3 / 2 = 1.5 +- 3 ^ 2 = 3 x 3 = 9 + +Python에는 다음과 같은 추가 작업이 있습니다: + +- 3 % 2 = 1 => 나머지를 구함 +- 3 // 2 = 1 => 나머지를 제거 + +위의 수학식을 Python 코드로 바꿔봅시다. Python 셸이 열렸으며 셸 맨 처음에 주석을 작성하겠습니다. + +_comment_는 Python에 의해 실행되지 않는 코드의 일부입니다. 따라서 코드를 더 읽기 쉽게 만들기 위해 코드에 일부 텍스트를 남길 수 있습니다. Python은 주석 부분을 실행하지 않습니다. Python에서 주석은 해시(#) 기호로 시작합니다. +이것이 Python에서 주석을 작성하는 방법입니다 + +```shell + # 주석은 해시로 시작합니다. + # (#) 심볼로 시작하기 때문에 이것은 파이썬 주석입니다. +``` + +![Maths on python shell](../images/maths_on_python_shell.png) + +다음 섹션으로 이동하기 전에 Python 대화형 셸에서 더 많은 연습을 해 보겠습니다. 셸에서 _exit()_를 작성하여 열린 셸을 닫았다가 다시 열어 Python 셸에서 텍스트를 쓰는 방법을 연습해 봅시다. + +![Writing String on python shell](../images/writing_string_on_shell.png) + +### Visual Studio Code 설치 + +Python 대화형 셸은 작은 스크립트 코드를 시도하고 테스트하는 데 적합하지만 큰 프로젝트에는 적합하지 않습니다. 실제 작업 환경에서 개발자는 다양한 코드 편집기를 사용하여 코드를 작성합니다. 이 30일간의 Python 프로그래밍 챌린지에서는 Visual Studio 코드를 사용합니다. Visual Studio Code는 매우 인기 있는 오픈 소스 텍스트 편집기입니다. 나는 vscode의 팬이고 Visual Studio 코드를 [다운로드](https://code.visualstudio.com/)하는 것을 추천하고 싶지만, 다른 편집자를 선호한다면 가지고 있는 것을 자유롭게 따르십시오. + +[![Visual Studio Code](../images/vscode.png)](https://code.visualstudio.com/) + +Visual Studio Code를 설치하셨다면 어떻게 사용하는지 알아보겠습니다. +비디오를 선호하는 경우 Python용 Visual Studio Code[비디오 자습서](https://www.youtube.com/watch?v=bn7Cx4z-vSo)를 따를 수 있습니다. + +#### visual studio code를 사용하기 + +Visual Studio 아이콘을 두 번 클릭하여 Visual Studio 코드를 엽니다. 열면 이런 종류의 인터페이스가 나타납니다. 레이블이 지정된 아이콘을 따라해보세요. + +![Visual studio Code](../images/vscode_ui.png) + +바탕 화면에 30DaysOfPython이라는 폴더를 만듭니다. 그런 다음 Visual Studio 코드를 사용하여 엽시다. + +![Opening Project on Visual studio](../images/how_to_open_project_on_vscode.png) + +![Opening a project](../images/opening_project.png) + +파일을 열면 30DaysOfPython 프로젝트의 디렉토리 내부에 파일과 폴더를 생성하기 위한 바로 가기가 표시됩니다. 아래에서 볼 수 있듯이 첫 번째 파일인 helloworld.py를 만들었습니다. 당신도 똑같이 할 수 있습니다. + +![Creating a python file](../images/helloworld.png) + +하루동안 오래 코딩을 한 후에 코드 편집기를 닫고 싶습니까? 이렇게 열린 프로젝트를 닫으면 됩니다. + +![Closing project](../images/closing_opened_project.png) + +축하합니다. 개발 환경 설정을 완료했습니다. 코딩을 시작해 봅시다. + +## Python 기본 + +### Python 구문 + +Python 스크립트는 Python 대화형 셸 또는 코드 편집기에서 작성할 수 있습니다. Python 파일의 확장자는 .py입니다. + +### Python 들여 쓰기 + +들여쓰기는 텍스트의 공백입니다. 많은 언어에서 들여쓰기는 코드 가독성을 높이는 데 사용되지만 Python은 들여쓰기를 사용하여 코드 블록을 만듭니다. 다른 프로그래밍 언어에서는 중괄호를 사용하여 들여쓰기 대신 코드 블록을 만듭니다. Python 코드를 작성할 때 흔히 발생하는 버그 중 하나는 잘못된 들여쓰기입니다. + +![Indentation Error](../images/indentation.png) + +### 주석 + +주석은 코드를 더 읽기 쉽게 만들고 코드에 설명을 남기기 위해 매우 중요합니다. Python은 코드의 주석 부분을 실행하지 않습니다. +Python에서 해시(#)로 시작하는 모든 텍스트는 주석입니다. + +**예시:한 문장 주석** + +```shell + # This is the first comment + # This is the second comment + # Python is eating the world +``` + +**예시: 여러 문장 주석** + +Triple quote can be used for multiline comment if it is not assigned to a variable + +```shell +"""This is multiline comment +multiline comment takes multiple lines. +python is eating the world +""" +``` + +### 데이터 타입 + +Python에는 여러 유형의 데이터 유형이 있습니다. 가장 일반적인 것부터 시작하겠습니다. 다른 데이터 유형은 다른 섹션에서 자세히 다룰 것입니다. 당분간 다양한 데이터 유형을 살펴보고 익숙해지도록 합시다. 지금은 명확하게 이해하지 않아도 됩니다. + +#### Number + +- Integer: 정수(음수, 영 그리고 양수) + 예시: + ... -3, -2, -1, 0, 1, 2, 3 ... +- Float: 십진수 + 예시 + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... +- Complex + 예시 + 1 + j, 2 + 4j + +#### String + +작은따옴표 또는 큰따옴표 아래에 있는 하나 이상의 문자 모음입니다. 문자열이 두 문장 이상인 경우 삼중 따옴표를 사용합니다. + +**예시:** + +```py +'Asabeneh' +'Finland' +'Python' +'I love teaching' +'I hope you are enjoying the first day of 30DaysOfPython Challenge' +``` + +#### Boolean + +부울 데이터 유형은 True 또는 False 값입니다. T와 F는 항상 대문자여야 합니다. + +**예시:** + +```python + True # 불이 켜져있나요? 그러면 참입니다. + False # 불이 꺼져있나요? 그러면 거짓입니다. +``` + +#### List + +Python 리스트는 다른 데이터 유형 항목을 저장할 수 있는 정렬된 컬렉션입니다. 리스트는 JavaScript의 배열과 비슷합니다. + +**Example:** + +```py +[0, 1, 2, 3, 4, 5] # 모두 동일한 데이터 유형 - 숫자 리스트 +['Banana', 'Orange', 'Mango', 'Avocado'] # 모두 동일한 데이터 유형 - 문자열 리스트(과일) +['Finland','Estonia', 'Sweden','Norway'] # 모두 동일한 데이터 유형 - 문자열 리스트(국가) +['Banana', 10, False, 9.81] # 리스트의 다양한 데이터 유형 - 문자열, 정수, 부울 및 부동 소수점 +``` + +#### Dictionary + +Python 사전 개체는 키 값 쌍 형식의 정렬되지 않은 데이터 모음입니다. + +**Example:** + +```py +{ +'first_name':'Asabeneh', +'last_name':'Yetayeh', +'country':'Finland', +'age':250, +'is_married':True, +'skills':['JS', 'React', 'Node', 'Python'] +} +``` + +#### Tuple + +튜플은 목록과 같은 다양한 데이터 유형의 정렬된 모음이지만 튜플이 생성되면 수정할 수 없습니다. 그것들은 변할 수 없습니다. + +**Example:** + +```py +('Asabeneh', 'Pawel', 'Brook', 'Abraham', 'Lidiya') # Names +``` + +```py +('Earth', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Saturn', 'Uranus', 'Mercury') # planets +``` + +#### Set + +집합은 목록 및 튜플과 유사한 데이터 유형의 모음입니다. 목록 및 튜플과 달리 집합은 순서가 지정된 항목 모음이 아닙니다. 수학에서와 마찬가지로 Python에서 set은 고유한 항목만 저장합니다. + +이후 섹션에서는 각각의 모든 Python 데이터 유형에 대해 자세히 설명합니다. + +**Example:** + +```py +{2, 4, 3, 5} +{3.14, 9.81, 2.7} # order is not important in set +``` + +### 데이터 타입 체크 + +특정 데이터/변수의 데이터 유형을 확인하기 위해 **type** 기능을 사용합니다. 다음 터미널에서 다양한 Python 데이터 유형을 볼 수 있습니다: + +![Checking Data types](../images/checking_data_types.png) + +### Python 파일 + +먼저 프로젝트 폴더인 30DaysOfPython을 엽니다. 이 폴더가 없으면 30DaysOfPython이라는 폴더 이름을 만듭니다. 이 폴더 안에 helloworld.py라는 파일을 만듭니다. 이제 Visual Studio 코드를 사용하여 Python 대화형 셸에서 수행한 작업을 수행해 보겠습니다. + +Python 대화형 셸은 **print**를 사용하지 않고 인쇄했지만 Visual Studio 코드에서 결과를 보려면 내장 함수 *print()를 사용해야 합니다. *print()* 내장 함수는 *print('arument1', 'argument2', 'argument3')*와 같이 하나 이상의 인수를 사용합니다. 아래 예를 참조하십시오. + +**Example:** + +파일 이름은 helloworld.py. + +```py +# Day 1 - 30DaysOfPython Challenge + +print(2 + 3) # addition(+) +print(3 - 1) # subtraction(-) +print(2 * 3) # multiplication(*) +print(3 / 2) # division(/) +print(3 ** 2) # exponential(**) +print(3 % 2) # modulus(%) +print(3 // 2) # Floor division operator(//) + +# Checking data types +print(type(10)) # Int +print(type(3.14)) # Float +print(type(1 + 3j)) # Complex number +print(type('Asabeneh')) # String +print(type([1, 2, 3])) # List +print(type({'name':'Asabeneh'})) # Dictionary +print(type({9.8, 3.14, 2.7})) # Set +print(type((9.8, 3.14, 2.7))) # Tuple +``` + +Python 파일을 실행하려면 아래 이미지를 확인하세요. Visual Studio Code에서 녹색 버튼을 실행하거나 터미널에 *python helloworld.py*를 입력하여 Python 파일을 실행할 수 있습니다. + +![Running python script](../images/running_python_script.png) + +🌕 좋습니다. 당신은 방금 1일차 도전을 완료했고 당신은 위대한 여정에 있습니다. 이제 뇌와 근육을 위한 몇 가지 훈련을 해봅시다. + +## 💻 Exercises - Day 1 + +### Exercise: Level 1 + +1. 사용 중인 Python 버전 확인 +2. Python 대화형 셸을 열고 다음 작업을 수행합니다. 피연산자는 3과 4입니다. + - 더하기(+) + - 빼기(-) + - 곱하기(\*) + - 나머지(%) + - 나누기(/) + - 지수(\*\*) + - 정수 나누기(//) +3. Python 대화형 셸에 문자열을 씁니다. 문자열은 다음과 같습니다: + - 이름 + - 가족 이름 + - 국가 이름 + - I am enjoying 30 days of python +4. 다음 데이터의 데이터 유형을 확인하십시오.: + - 10 + - 9.8 + - 3.14 + - 4 - 4j + - ['Asabeneh', 'Python', 'Finland'] + - 이름 + - 가족 이름 + - 국가 이름 + +### Exercise: Level 2 + +1. 30DaysOfPython 폴더 안에 day_1이라는 폴더를 만듭니다. day_1 폴더 안에 python 파일 helloworld.py를 만들고 질문 1, 2, 3, 4를 반복하세요. Python 파일에서 작업할 때 _print()_를 사용하는 것을 잊지 마세요. 파일을 저장한 디렉토리로 이동하여 실행합니다. + +### Exercise: Level 3 + +1. Number(Integer, Float, Complex), String, Boolean, List, Tuple, Set 및 Dictionary와 같은 다양한 Python 데이터 유형에 대한 예제를 작성합니다. +2. 참고 [Euclidian distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) (2, 3) 과 (10, 8) 사이 + +🎉 축하합니다 ! 🎉 + +[Day 2 >>](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) \ No newline at end of file From 088e613ddeb4ce7e7e32685393a0033f702e4aab Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Fri, 9 Dec 2022 10:34:56 +0900 Subject: [PATCH 17/63] rm lang-ko --- lang-ko/readme_ko.md | 454 ------------------------------------------- 1 file changed, 454 deletions(-) delete mode 100644 lang-ko/readme_ko.md diff --git a/lang-ko/readme_ko.md b/lang-ko/readme_ko.md deleted file mode 100644 index bc6286096..000000000 --- a/lang-ko/readme_ko.md +++ /dev/null @@ -1,454 +0,0 @@ -# 🐍 30 Days Of Python - -|# Day | Topics | -|------|:---------------------------------------------------------:| -| 01 | [Introduction](./readme_ko.md)| -| 02 | [Variables, Built-in Functions](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| -| 03 | [Operators](../03_Day_Operators/03_operators.md)| -| 04 | [Strings](../04_Day_Strings/04_strings.md)| -| 05 | [Lists](../05_Day_Lists/05_lists.md)| -| 06 | [Tuples](../06_Day_Tuples/06_tuples.md)| -| 07 | [Sets](../07_Day_Sets/07_sets.md)| -| 08 | [Dictionaries](../08_Day_Dictionaries/08_dictionaries.md)| -| 09 | [Conditionals](../09_Day_Conditionals/09_conditionals.md)| -| 10 | [Loops](../10_Day_Loops/10_loops.md)| -| 11 | [Functions](../11_Day_Functions/11_functions.md)| -| 12 | [Modules](../12_Day_Modules/12_modules.md)| -| 13 | [List Comprehension](../13_Day_List_comprehension/13_list_comprehension.md)| -| 14 | [Higher Order Functions](../14_Day_Higher_order_functions/14_higher_order_functions.md)| -| 15 | [Python Type Errors](../15_Day_Python_type_errors/15_python_type_errors.md)| -| 16 | [Python Date time](../16_Day_Python_date_time/16_python_datetime.md) | -| 17 | [Exception Handling](../17_Day_Exception_handling/17_exception_handling.md)| -| 18 | [Regular Expressions](../18_Day_Regular_expressions/18_regular_expressions.md)| -| 19 | [File Handling](../19_Day_File_handling/19_file_handling.md)| -| 20 | [Python Package Manager](../20_Day_Python_package_manager/20_python_package_manager.md)| -| 21 | [Classes and Objects](../21_Day_Classes_and_objects/21_classes_and_objects.md)| -| 22 | [Web Scraping](../22_Day_Web_scraping/22_web_scraping.md)| -| 23 | [Virtual Environment](../23_Day_Virtual_environment/23_virtual_environment.md)| -| 24 | [Statistics](../24_Day_Statistics/24_statistics.md)| -| 25 | [Pandas](../25_Day_Pandas/25_pandas.md)| -| 26 | [Python web](../26_Day_Python_web/26_python_web.md)| -| 27 | [Python with MongoDB](../27_Day_Python_with_mongodb/27_python_with_mongodb.md)| -| 28 | [API](../28_Day_API/28_API.md)| -| 29 | [Building API](../29_Day_Building_API/29_building_API.md)| -| 30 | [Conclusions](../30_Day_Conclusions/30_conclusions.md)| - -🧡🧡🧡 HAPPY CODING 🧡🧡🧡 - -
-Support the author to create more educational materials
-Paypal Logo -
- -
-

30 Days Of Python: Day 1 - Introduction

- - - - - Twitter Follow - - - Author: - Asabeneh Yetayeh
- Second Edition: July, 2021 -
-
- - -[Day 2 >>](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) - -![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) - -- [🐍 30 Days Of Python](#-30-days-of-python) -- [📘 Day 1](#-day-1) - - [환영합니다](#환영합니다) - - [소개](#소개) - - [왜 Python이느냐?](#왜-python이느냐?) - - [환경 설정](#환경-설정) - - [Python 설치](#python-설치) - - [Python 셸](#python-셸) - - [Visual Studio Code 설치](#visual-studio-code-설치) - - [visual studio code를 사용하기](#visual-studio-code를-사용하기) - - [Python 기본](#python-기본) - - [Python 구문](#python-구문) - - [Python 들여쓰기](#python-들여쓰기) - - [주석](#주석) - - [데이터 타입](#데이터-타입) - - [Number](#number) - - [String](#string) - - [Booleans](#booleans) - - [List](#list) - - [Dictionary](#dictionary) - - [Tuple](#tuple) - - [Set](#set) - - [데이터 타입 체크](#데이터-타입-체크) - - [Python 파일](#python-파일) - - [💻 Exercises - Day 1](#-exercises---day-1) - - [Exercise: Level 1](#exercise-level-1) - - [Exercise: Level 2](#exercise-level-2) - - [Exercise: Level 3](#exercise-level-3) - -# 📘 Day 1 - -## 환영합니다 - -_30 days of Python_에 참여하기로 결정하신 것을 **축하드립니다**. 이 챌린지에서는 Python 프로그래머가 되기 위해 필요한 모든 것과 프로그래밍의 전체 개념을 배우게 됩니다. 챌린지가 끝나면 _30DaysOfPython_프로그래밍 챌린지 인증서를 받게 됩니다. - -챌린지에 적극적으로 참여하고 싶다면 [30DaysOfPython challenge](https://t.me/ThirtyDaysOfPython) 텔레그램 그룹에 가입할 수 있습니다. - -## 소개 - -Python은 범용 프로그래밍을 위한 고급 프로그래밍 언어입니다. 오픈 소스, 인터프리터, 객체 지향 프로그래밍 언어입니다. Python은 네덜란드 프로그래머 Guido van Rossum이 만들었습니다. Python 프로그래밍 언어의 이름은 영국 스케치 코미디 시리즈 *Month Python's Flying Circus* 에서 파생되었습니다. 첫 번째 버전은 1991년 2월 20일에 출시되었습니다. 이 30일간의 Python 챌린지는 최신 버전의 Python인 Python 3를 차근차근 배울 수 있도록 도와줄 것입니다. 주제는 30일로 나뉘며, 매일 이해하기 쉬운 설명, 실제 사례, 많은 실습 및 프로젝트가 포함된 여러 주제가 포함됩니다. - -이 챌린지는 Python 프로그래밍 언어를 배우고자 하는 초보자와 전문가를 위해 고안되었습니다. 챌린지를 완료하는 데 30~100일이 소요될 수 있으며 텔레그램 그룹에 적극적으로 참여하는 사람들이 챌린지를 완료할 확률이 높습니다. -시각적 학습자이거나 동영상을 선호하는 경우 이 [완전 초보를 위한 Python 동영상](https://www.youtube.com/watch?v=11OYpBrhdyM)으로 시작할 수 있습니다. - -## 왜 Python이느냐? - -인간의 언어에 매우 가깝고 배우기 쉽고 사용하기 쉬운 프로그래밍 언어입니다. -Python은 다양한 산업 및 회사(Google 포함)에서 사용됩니다. 웹 응용 프로그램, 데스크톱 응용 프로그램, 시스템 관리 및 기계 학습 라이브러리를 개발하는 데 사용되었습니다. Python은 데이터 과학 및 기계 학습 커뮤니티에서 널리 사용되는 언어입니다. 이것이 Python 학습을 시작하도록 설득하기에 충분하기를 바랍니다. Python은 세상을 지배하고 있으니 지배 당하기 전에 Python을 지배하십시오. -## 환경 설정 - -### Python 설치 - -Python 스크립트를 실행하려면 Python을 설치해야 합니다. Python을 [다운로드](https://www.python.org/)합시다. -Windows 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니다. - - - -macOS 사용자인 경우. 빨간색 동그라미 친 버튼을 클릭합니다. - -[![Windows에서 설치](../images/installing_on_windows.png)](https://www.python.org/) - -Python이 설치되어 있는지 확인하려면 장치 터미널에 다음 명령을 작성하십시오. - -```shell -python --version -``` - -![Python Version](../images/python_versio.png) - -터미널에서 보시다시피 저는 현재 _Python 3.7.5_ 버전을 사용하고 있습니다. 귀하의 Python 버전은 내 버전과 다를 수 있지만 3.6 이상이어야 합니다. Python 버전을 볼 수 있다면 잘한 것입니다. 이제 컴퓨터에 Python이 설치되었습니다. 다음 섹션으로 계속 진행하십시오. - -### Python 셸 - -Python은 해석된 스크립팅 언어이므로 컴파일할 필요가 없습니다. 코드를 한 줄씩 실행한다는 의미입니다. Python은 _Python Shell(Python Interactive Shell)_과 함께 제공됩니다. 단일 Python 명령을 실행하고 결과를 얻는 데 사용됩니다. - -Python Shell은 사용자의 Python 코드를 기다립니다. 코드를 입력하면 코드를 해석하여 다음 줄에 결과를 표시합니다. -터미널이나 명령 프롬프트(cmd)를 열고 쓰기: - -```shell -python -``` - -![Python Scripting Shell](../images/opening_python_shell.png) - -Python 대화형 셸이 열리고 Python 코드(Python 스크립트)를 작성하기를 기다립니다. 기호 >>> 옆에 Python 스크립트를 작성하고 Enter를 누릅니다. -Python 스크립팅 셸에서 첫 번째 스크립트를 작성해 보겠습니다. - -![Python script on Python shell](../images/adding_on_python_shell.png) - -훌륭합니다. Python 대화형 셸에서 첫 번째 Python 스크립트를 작성했습니다. Python 대화형 셸을 어떻게 닫습니까? -셸을 닫으려면 기호 옆에 >> **exit()** 명령을 작성하고 Enter 키를 누릅니다. - -![Exit from python shell](../images/exit_from_shell.png) - -이제 Python 대화형 셸을 여는 방법과 종료하는 방법을 알았습니다. - -Python은 Python이 이해하는 스크립트를 작성하면 결과를 제공하고 그렇지 않으면 오류를 반환합니다. 고의적인 실수를 하고 Python이 무엇을 반환하는지 봅시다. - -![Invalid Syntax Error](../images/invalid_syntax_error.png) - -반환된 오류에서 볼 수 있듯이 Python은 우리가 저지른 실수와 _Syntax Error: invalid syntax_를 알고 있을 정도로 영리합니다. Python에서 x를 곱셈으로 사용하는 것은 (x)가 Python에서 유효한 구문이 아니기 때문에 구문 오류입니다. (**x**) 대신 곱셈에 별표(*)를 사용합니다. 반환된 오류는 수정해야 할 사항을 명확하게 보여줍니다. - -프로그램에서 오류를 식별하고 제거하는 프로세스를 *디버깅*이라고 합니다. **x** 대신 *를 넣어 디버깅해 봅시다. - -![Fixing Syntax Error](../images/fixing_syntax_error.png) - -버그가 수정되었고 코드가 실행되었으며 예상했던 결과를 얻었습니다. 프로그래머로서 매일 이러한 종류의 오류를 보게 될 것입니다. 디버깅 방법을 아는 것이 좋습니다. 디버깅을 잘하려면 어떤 종류의 오류가 발생했는지 이해해야 합니다. 발생할 수 있는 Python 오류 중 일부는 *SyntaxError*, *IndexError*, *NameError*, *ModuleNotFoundError*, *KeyError*, *ImportError*, *AttributeError*, *TypeError*, *ValueError*, *ZeroDivisionError* 등입니다. 이후 섹션에서 다른 Python **_오류 유형_**에 대해 자세히 알아볼 것입니다. - -Python 대화형 셸을 사용하는 방법을 더 연습해 보겠습니다. 터미널이나 명령 프롬프트로 이동하여 **python**이라는 단어를 씁니다. - -![Python Scripting Shell](../images/opening_python_shell.png) - -Python 대화형 셸이 열립니다. 몇 가지 기본적인 수학 연산(더하기, 빼기, 곱하기, 나누기, 나머지, 지수)을 수행해 보겠습니다. - -Python 코드를 작성하기 전에 먼저 몇 가지 수학을 수행해 보겠습니다: - -- 2 + 3 = 5 -- 3 - 2 = 1 -- 3 \* 2 = 6 -- 3 / 2 = 1.5 -- 3 ^ 2 = 3 x 3 = 9 - -Python에는 다음과 같은 추가 작업이 있습니다: - -- 3 % 2 = 1 => 나머지를 구함 -- 3 // 2 = 1 => 나머지를 제거 - -위의 수학식을 Python 코드로 바꿔봅시다. Python 셸이 열렸으며 셸 맨 처음에 주석을 작성하겠습니다. - -_comment_는 Python에 의해 실행되지 않는 코드의 일부입니다. 따라서 코드를 더 읽기 쉽게 만들기 위해 코드에 일부 텍스트를 남길 수 있습니다. Python은 주석 부분을 실행하지 않습니다. Python에서 주석은 해시(#) 기호로 시작합니다. -이것이 Python에서 주석을 작성하는 방법입니다 - -```shell - # 주석은 해시로 시작합니다. - # (#) 심볼로 시작하기 때문에 이것은 파이썬 주석입니다. -``` - -![Maths on python shell](../images/maths_on_python_shell.png) - -다음 섹션으로 이동하기 전에 Python 대화형 셸에서 더 많은 연습을 해 보겠습니다. 셸에서 _exit()_를 작성하여 열린 셸을 닫았다가 다시 열어 Python 셸에서 텍스트를 쓰는 방법을 연습해 봅시다. - -![Writing String on python shell](../images/writing_string_on_shell.png) - -### Visual Studio Code 설치 - -Python 대화형 셸은 작은 스크립트 코드를 시도하고 테스트하는 데 적합하지만 큰 프로젝트에는 적합하지 않습니다. 실제 작업 환경에서 개발자는 다양한 코드 편집기를 사용하여 코드를 작성합니다. 이 30일간의 Python 프로그래밍 챌린지에서는 Visual Studio 코드를 사용합니다. Visual Studio Code는 매우 인기 있는 오픈 소스 텍스트 편집기입니다. 나는 vscode의 팬이고 Visual Studio 코드를 [다운로드](https://code.visualstudio.com/)하는 것을 추천하고 싶지만, 다른 편집자를 선호한다면 가지고 있는 것을 자유롭게 따르십시오. - -[![Visual Studio Code](../images/vscode.png)](https://code.visualstudio.com/) - -Visual Studio Code를 설치하셨다면 어떻게 사용하는지 알아보겠습니다. -비디오를 선호하는 경우 Python용 Visual Studio Code[비디오 자습서](https://www.youtube.com/watch?v=bn7Cx4z-vSo)를 따를 수 있습니다. - -#### visual studio code를 사용하기 - -Visual Studio 아이콘을 두 번 클릭하여 Visual Studio 코드를 엽니다. 열면 이런 종류의 인터페이스가 나타납니다. 레이블이 지정된 아이콘을 따라해보세요. - -![Visual studio Code](../images/vscode_ui.png) - -바탕 화면에 30DaysOfPython이라는 폴더를 만듭니다. 그런 다음 Visual Studio 코드를 사용하여 엽시다. - -![Opening Project on Visual studio](../images/how_to_open_project_on_vscode.png) - -![Opening a project](../images/opening_project.png) - -파일을 열면 30DaysOfPython 프로젝트의 디렉토리 내부에 파일과 폴더를 생성하기 위한 바로 가기가 표시됩니다. 아래에서 볼 수 있듯이 첫 번째 파일인 helloworld.py를 만들었습니다. 당신도 똑같이 할 수 있습니다. - -![Creating a python file](../images/helloworld.png) - -하루동안 오래 코딩을 한 후에 코드 편집기를 닫고 싶습니까? 이렇게 열린 프로젝트를 닫으면 됩니다. - -![Closing project](../images/closing_opened_project.png) - -축하합니다. 개발 환경 설정을 완료했습니다. 코딩을 시작해 봅시다. - -## Python 기본 - -### Python 구문 - -Python 스크립트는 Python 대화형 셸 또는 코드 편집기에서 작성할 수 있습니다. Python 파일의 확장자는 .py입니다. - -### Python 들여 쓰기 - -들여쓰기는 텍스트의 공백입니다. 많은 언어에서 들여쓰기는 코드 가독성을 높이는 데 사용되지만 Python은 들여쓰기를 사용하여 코드 블록을 만듭니다. 다른 프로그래밍 언어에서는 중괄호를 사용하여 들여쓰기 대신 코드 블록을 만듭니다. Python 코드를 작성할 때 흔히 발생하는 버그 중 하나는 잘못된 들여쓰기입니다. - -![Indentation Error](../images/indentation.png) - -### 주석 - -주석은 코드를 더 읽기 쉽게 만들고 코드에 설명을 남기기 위해 매우 중요합니다. Python은 코드의 주석 부분을 실행하지 않습니다. -Python에서 해시(#)로 시작하는 모든 텍스트는 주석입니다. - -**예시:한 문장 주석** - -```shell - # This is the first comment - # This is the second comment - # Python is eating the world -``` - -**예시: 여러 문장 주석** - -Triple quote can be used for multiline comment if it is not assigned to a variable - -```shell -"""This is multiline comment -multiline comment takes multiple lines. -python is eating the world -""" -``` - -### 데이터 타입 - -Python에는 여러 유형의 데이터 유형이 있습니다. 가장 일반적인 것부터 시작하겠습니다. 다른 데이터 유형은 다른 섹션에서 자세히 다룰 것입니다. 당분간 다양한 데이터 유형을 살펴보고 익숙해지도록 합시다. 지금은 명확하게 이해하지 않아도 됩니다. - -#### Number - -- Integer: 정수(음수, 영 그리고 양수) - 예시: - ... -3, -2, -1, 0, 1, 2, 3 ... -- Float: 십진수 - 예시 - ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... -- Complex - 예시 - 1 + j, 2 + 4j - -#### String - -작은따옴표 또는 큰따옴표 아래에 있는 하나 이상의 문자 모음입니다. 문자열이 두 문장 이상인 경우 삼중 따옴표를 사용합니다. - -**예시:** - -```py -'Asabeneh' -'Finland' -'Python' -'I love teaching' -'I hope you are enjoying the first day of 30DaysOfPython Challenge' -``` - -#### Boolean - -부울 데이터 유형은 True 또는 False 값입니다. T와 F는 항상 대문자여야 합니다. - -**예시:** - -```python - True # 불이 켜져있나요? 그러면 참입니다. - False # 불이 꺼져있나요? 그러면 거짓입니다. -``` - -#### List - -Python 리스트는 다른 데이터 유형 항목을 저장할 수 있는 정렬된 컬렉션입니다. 리스트는 JavaScript의 배열과 비슷합니다. - -**Example:** - -```py -[0, 1, 2, 3, 4, 5] # 모두 동일한 데이터 유형 - 숫자 리스트 -['Banana', 'Orange', 'Mango', 'Avocado'] # 모두 동일한 데이터 유형 - 문자열 리스트(과일) -['Finland','Estonia', 'Sweden','Norway'] # 모두 동일한 데이터 유형 - 문자열 리스트(국가) -['Banana', 10, False, 9.81] # 리스트의 다양한 데이터 유형 - 문자열, 정수, 부울 및 부동 소수점 -``` - -#### Dictionary - -Python 사전 개체는 키 값 쌍 형식의 정렬되지 않은 데이터 모음입니다. - -**Example:** - -```py -{ -'first_name':'Asabeneh', -'last_name':'Yetayeh', -'country':'Finland', -'age':250, -'is_married':True, -'skills':['JS', 'React', 'Node', 'Python'] -} -``` - -#### Tuple - -튜플은 목록과 같은 다양한 데이터 유형의 정렬된 모음이지만 튜플이 생성되면 수정할 수 없습니다. 그것들은 변할 수 없습니다. - -**Example:** - -```py -('Asabeneh', 'Pawel', 'Brook', 'Abraham', 'Lidiya') # Names -``` - -```py -('Earth', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Saturn', 'Uranus', 'Mercury') # planets -``` - -#### Set - -집합은 목록 및 튜플과 유사한 데이터 유형의 모음입니다. 목록 및 튜플과 달리 집합은 순서가 지정된 항목 모음이 아닙니다. 수학에서와 마찬가지로 Python에서 set은 고유한 항목만 저장합니다. - -이후 섹션에서는 각각의 모든 Python 데이터 유형에 대해 자세히 설명합니다. - -**Example:** - -```py -{2, 4, 3, 5} -{3.14, 9.81, 2.7} # order is not important in set -``` - -### 데이터 타입 체크 - -특정 데이터/변수의 데이터 유형을 확인하기 위해 **type** 기능을 사용합니다. 다음 터미널에서 다양한 Python 데이터 유형을 볼 수 있습니다: - -![Checking Data types](../images/checking_data_types.png) - -### Python 파일 - -먼저 프로젝트 폴더인 30DaysOfPython을 엽니다. 이 폴더가 없으면 30DaysOfPython이라는 폴더 이름을 만듭니다. 이 폴더 안에 helloworld.py라는 파일을 만듭니다. 이제 Visual Studio 코드를 사용하여 Python 대화형 셸에서 수행한 작업을 수행해 보겠습니다. - -Python 대화형 셸은 **print**를 사용하지 않고 인쇄했지만 Visual Studio 코드에서 결과를 보려면 내장 함수 *print()를 사용해야 합니다. *print()* 내장 함수는 *print('arument1', 'argument2', 'argument3')*와 같이 하나 이상의 인수를 사용합니다. 아래 예를 참조하십시오. - -**Example:** - -파일 이름은 helloworld.py. - -```py -# Day 1 - 30DaysOfPython Challenge - -print(2 + 3) # addition(+) -print(3 - 1) # subtraction(-) -print(2 * 3) # multiplication(*) -print(3 / 2) # division(/) -print(3 ** 2) # exponential(**) -print(3 % 2) # modulus(%) -print(3 // 2) # Floor division operator(//) - -# Checking data types -print(type(10)) # Int -print(type(3.14)) # Float -print(type(1 + 3j)) # Complex number -print(type('Asabeneh')) # String -print(type([1, 2, 3])) # List -print(type({'name':'Asabeneh'})) # Dictionary -print(type({9.8, 3.14, 2.7})) # Set -print(type((9.8, 3.14, 2.7))) # Tuple -``` - -Python 파일을 실행하려면 아래 이미지를 확인하세요. Visual Studio Code에서 녹색 버튼을 실행하거나 터미널에 *python helloworld.py*를 입력하여 Python 파일을 실행할 수 있습니다. - -![Running python script](../images/running_python_script.png) - -🌕 좋습니다. 당신은 방금 1일차 도전을 완료했고 당신은 위대한 여정에 있습니다. 이제 뇌와 근육을 위한 몇 가지 훈련을 해봅시다. - -## 💻 Exercises - Day 1 - -### Exercise: Level 1 - -1. 사용 중인 Python 버전 확인 -2. Python 대화형 셸을 열고 다음 작업을 수행합니다. 피연산자는 3과 4입니다. - - 더하기(+) - - 빼기(-) - - 곱하기(\*) - - 나머지(%) - - 나누기(/) - - 지수(\*\*) - - 정수 나누기(//) -3. Python 대화형 셸에 문자열을 씁니다. 문자열은 다음과 같습니다: - - 이름 - - 가족 이름 - - 국가 이름 - - I am enjoying 30 days of python -4. 다음 데이터의 데이터 유형을 확인하십시오.: - - 10 - - 9.8 - - 3.14 - - 4 - 4j - - ['Asabeneh', 'Python', 'Finland'] - - 이름 - - 가족 이름 - - 국가 이름 - -### Exercise: Level 2 - -1. 30DaysOfPython 폴더 안에 day_1이라는 폴더를 만듭니다. day_1 폴더 안에 python 파일 helloworld.py를 만들고 질문 1, 2, 3, 4를 반복하세요. Python 파일에서 작업할 때 _print()_를 사용하는 것을 잊지 마세요. 파일을 저장한 디렉토리로 이동하여 실행합니다. - -### Exercise: Level 3 - -1. Number(Integer, Float, Complex), String, Boolean, List, Tuple, Set 및 Dictionary와 같은 다양한 Python 데이터 유형에 대한 예제를 작성합니다. -2. 참고 [Euclidian distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) (2, 3) 과 (10, 8) 사이 - -🎉 축하합니다 ! 🎉 - -[Day 2 >>](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) \ No newline at end of file From f1a3d948b2c264f1bb5bb21e528cea7cf0234d4a Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Fri, 9 Dec 2022 11:25:02 +0900 Subject: [PATCH 18/63] Day 07 10 md --- Korean/07_sets_ko.md | 417 +++++++++++++++++++++++++++++++++++++++ Korean/10_loops_ko.md | 448 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 865 insertions(+) create mode 100644 Korean/07_sets_ko.md create mode 100644 Korean/10_loops_ko.md diff --git a/Korean/07_sets_ko.md b/Korean/07_sets_ko.md new file mode 100644 index 000000000..46092fb72 --- /dev/null +++ b/Korean/07_sets_ko.md @@ -0,0 +1,417 @@ +
30 Days Of Python: Day 7 - Sets Twitter Follow +
+

Author: Asabeneh Yetayeh
Second Edition: July, 2021

+
+ +[<< Day 6](../06_Day_Tuples/06_tuples.md) | [Day 8 >>](../08_Day_Dictionaries/08_dictionaries.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 Day 7](#-day-7) + - [Sets](#sets) + - [세트 만들기](#세트-만들기) + - [세트의 길이 구하기](#세트의-길이-구하기) + - [세트의 항목에 액세스](#세트의-항목에-엑세스) + - [항목 확인](#항목-확인) + - [세트에 항목 추가](#세트에-항목-추가) + - [세트에서 항목 제거](#세트에서-항목-제거) + - [세트의 항목 지우기](#세트의-항목-지우기) + - [세트 삭제](#세트-삭제) + - [목록을 집합으로 변환](#목록을-집합으로-변환) + - [집합 결합](#집합-결합) + - [교차 항목 찾기](#교차-항목-찾기) + - [하위 집합 및 수퍼 집합 확인](#하위-집합-및-수퍼-집합-확인) + - [두 세트 간의 차이 확인](#두-세트-간의-차이-확인) + - [두 집합 간의 대칭적 차이 찾기](#두-집합-간의-대칭적-차이-찾기) + - [집합 결합](#집합-결합) + - [💻 Exercises: Day 7](#-exercises-day-7) + - [Exercises: Level 1](#exercises-level-1) + - [Exercises: Level 2](#exercises-level-2) + - [Exercises: Level 3](#exercises-level-3) + +# 📘 Day 7 + +## Sets + +세트는 항목의 모음입니다. 초등학교 또는 고등학교 수학 수업으로 돌아가겠습니다. 집합의 수학 정의는 Python에서도 적용될 수 있습니다. 집합은 순서가 지정되지 않고 인덱싱되지 않은 개별 요소의 모음입니다. Python에서 집합은 고유한 항목을 저장하는 데 사용되며 집합 간에 *합집합* , *교차* , *차이* , *대칭적 차이* , *하위 집합* , *상위 집합* 및 *분리 집합* 을 찾을 수 있습니다. + +### 세트 만들기 + +중괄호 {}를 사용하여 세트 또는 *set()* 내장 함수를 생성합니다. + +- 빈 세트 만들기 + +```py +# syntax +st = {} +# or +st = set() +``` + +- 초기 항목으로 세트 만들기 + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +``` + +**예시:** + +```py +# syntax +fruits = {'banana', 'orange', 'mango', 'lemon'} +``` + +### 세트의 길이 구하기 + +**len()** 메서드를 사용하여 집합의 길이를 찾습니다. + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +len(set) +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +len(fruits) +``` + +### 세트의 항목에 액세스 + +루프를 사용하여 항목에 액세스합니다. 우리는 루프 섹션에서 이것을 볼 것입니다 + +### 항목 확인 + +목록에 항목이 있는지 확인하기 위해 멤버십 연산자 *에서* 사용합니다. + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +print("Does set st contain item3? ", 'item3' in st) # Does set st contain item3? True +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +print('mango' in fruits ) # True +``` + +### 세트에 항목 추가 + +세트가 생성되면 항목을 변경할 수 없으며 항목을 추가할 수도 있습니다. + +- *add()* 를 사용하여 하나의 항목 추가 + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +st.add('item5') +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +fruits.add('lime') +``` + +- *update()* 를 사용하여 여러 항목 추가 *update()* 를 사용하면 세트에 여러 항목을 추가할 수 있습니다. *update()* 는 목록 인수를 사용합니다. + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +st.update(['item5','item6','item7']) +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +vegetables = ('tomato', 'potato', 'cabbage','onion', 'carrot') +fruits.update(vegetables) +``` + +### 세트에서 항목 제거 + +*remove()* 메서드를 사용하여 집합에서 항목을 제거할 수 있습니다. 항목을 찾을 수 없으면 *remove()* 메서드는 오류를 발생시키므로 해당 항목이 주어진 집합에 있는지 확인하는 것이 좋습니다. 그러나, *discard()* 메서드는 오류를 발생시키지 않습니다. + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +st.remove('item2') +``` + +pop() 메서드는 목록에서 임의의 항목을 제거하고 제거된 항목을 반환합니다. + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +fruits.pop() # removes a random item from the set + +``` + +제거된 항목에 관심이 있는 경우. + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +removed_item = fruits.pop() +``` + +### 세트의 항목 지우기 + +세트를 지우거나 비우려면 *clear* 메소드를 사용합니다. + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +st.clear() +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +fruits.clear() +print(fruits) # set() +``` + +### 세트 삭제 + +세트 자체를 삭제하려면 *del* 연산자를 사용합니다. + +```py +# syntax +st = {'item1', 'item2', 'item3', 'item4'} +del st +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +del fruits +``` + +### 목록을 집합으로 변환 + +리스트를 세트로, 세트를 리스트로 변환할 수 있습니다. 목록을 세트로 변환하면 중복 항목이 제거되고 고유한 항목만 예약됩니다. + +```py +# syntax +lst = ['item1', 'item2', 'item3', 'item4', 'item1'] +st = set(lst) # {'item2', 'item4', 'item1', 'item3'} - the order is random, because sets in general are unordered +``` + +**예시:** + +```py +fruits = ['banana', 'orange', 'mango', 'lemon','orange', 'banana'] +fruits = set(fruits) # {'mango', 'lemon', 'banana', 'orange'} +``` + +### 집합 결합 + +*union()* 또는 *update()* 메서드를 사용하여 두 집합을 결합할 수 있습니다. + +- Union 이 메서드는 새 집합을 반환합니다. + +```py +# syntax +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item5', 'item6', 'item7', 'item8'} +st3 = st1.union(st2) +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +vegetables = {'tomato', 'potato', 'cabbage','onion', 'carrot'} +print(fruits.union(vegetables)) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabbage', 'potato', 'onion'} +``` + +- 업데이트 이 메서드는 주어진 집합에 집합을 삽입합니다. + +```py +# syntax +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item5', 'item6', 'item7', 'item8'} +st1.update(st2) # st2 contents are added to st1 +``` + +**예시:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +vegetables = {'tomato', 'potato', 'cabbage','onion', 'carrot'} +fruits.update(vegetables) +print(fruits) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabbage', 'potato', 'onion'} +``` + +### 교차 항목 찾기 + +Intersection은 두 집합 모두에 있는 항목 집합을 반환합니다. 예를 참조하십시오 + +```py +# syntax +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item3', 'item2'} +st1.intersection(st2) # {'item3', 'item2'} +``` + +**예시:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +even_numbers = {0, 2, 4, 6, 8, 10} +whole_numbers.intersection(even_numbers) # {0, 2, 4, 6, 8, 10} + +python = {'p', 'y', 't', 'h', 'o','n'} +dragon = {'d', 'r', 'a', 'g', 'o','n'} +python.intersection(dragon) # {'o', 'n'} +``` + +### 하위 집합 및 수퍼 집합 확인 + +집합은 다른 집합의 하위 집합 또는 상위 집합일 수 있습니다. + +- Subset: *issubset()* +- Super set: *issuperset* + +```py +# syntax +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +st2.issubset(st1) # True +st1.issuperset(st2) # True +``` + +**예시:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +even_numbers = {0, 2, 4, 6, 8, 10} +whole_numbers.issubset(even_numbers) # False, because it is a super set +whole_numbers.issuperset(even_numbers) # True + +python = {'p', 'y', 't', 'h', 'o','n'} +dragon = {'d', 'r', 'a', 'g', 'o','n'} +python.issubset(dragon) # False +``` + +### 두 세트 간의 차이 확인 + +두 집합 간의 차이를 반환합니다. + +```py +# syntax +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +st2.difference(st1) # set() +st1.difference(st2) # {'item1', 'item4'} => st1\st2 +``` + +**예시:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +even_numbers = {0, 2, 4, 6, 8, 10} +whole_numbers.difference(even_numbers) # {1, 3, 5, 7, 9} + +python = {'p', 'y', 't', 'o','n'} +dragon = {'d', 'r', 'a', 'g', 'o','n'} +python.difference(dragon) # {'p', 'y', 't'} - the result is unordered (characteristic of sets) +dragon.difference(python) # {'d', 'r', 'a', 'g'} +``` + +### 두 집합 간의 대칭적 차이 찾기 + +두 집합 간의 대칭 차이를 반환합니다. 수학적으로 두 세트에 있는 항목을 제외하고 두 세트의 모든 항목을 포함하는 세트를 리턴한다는 의미입니다. (A\B) ∪ (B\A) + +```py +# syntax +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +# it means (A\B)∪(B\A) +st2.symmetric_difference(st1) # {'item1', 'item4'} +``` + +**예시:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +some_numbers = {1, 2, 3, 4, 5} +whole_numbers.symmetric_difference(some_numbers) # {0, 6, 7, 8, 9, 10} + +python = {'p', 'y', 't', 'h', 'o','n'} +dragon = {'d', 'r', 'a', 'g', 'o','n'} +python.symmetric_difference(dragon) # {'r', 't', 'p', 'y', 'g', 'a', 'd', 'h'} +``` + +### 집합 결합 + +두 세트에 공통 항목이 없으면 분리 세트라고 합니다. *isdisjoint()* 메서드를 사용하여 두 집합이 결합인지 분리인지 확인할 수 있습니다. + +```py +# syntax +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +st2.isdisjoint(st1) # False +``` + +**예시:** + +```py +even_numbers = {0, 2, 4 ,6, 8} +even_numbers = {1, 3, 5, 7, 9} +even_numbers.isdisjoint(odd_numbers) # True, because no common item + +python = {'p', 'y', 't', 'h', 'o','n'} +dragon = {'d', 'r', 'a', 'g', 'o','n'} +python.isdisjoint(dragon) # False, there are common items {'o', 'n'} +``` + +🌕 당신은 떠오르는 별입니다. 당신은 방금 7일차 챌린지를 완료했으며 위대함을 향한 당신의 길에 7걸음 앞서 있습니다. 이제 뇌와 근육을 위한 몇 가지 훈련을 하십시오. + +## 💻 Exercises: Day 7 + +```py +# sets +it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'} +A = {19, 22, 24, 20, 25, 26} +B = {19, 22, 20, 25, 26, 24, 28, 27} +age = [22, 19, 24, 25, 26, 24, 25, 24] +``` + +### Exercises: Level 1 + +1. 집합 it_companies의 길이 찾기 +2. it_companies에 'Twitter' 추가 +3. it_companies 집합에 여러 IT 회사를 한 번에 삽입 +4. it_companies 집합에서 회사 중 하나를 제거합니다. +5. 제거하다와 버리다의 차이점은 무엇인가요? + +### Exercises: Level 2 + +1. A와 B를 결합 +2. 교차 항목 찾기 +3. A는 B의 부분집합 +4. A와 B는 서로소 집합입니다. +5. A는 B와, B는 A와 조인 +6. A와 B의 대칭 차이는 무엇입니까 +7. 세트를 완전히 삭제 + +### Exercises: Level 3 + +1. 연령을 세트로 변환하고 목록의 길이와 세트의 길이를 비교합니다. 어느 것이 더 큽니까? +2. 문자열, 목록, 튜플 및 집합과 같은 데이터 유형의 차이점을 설명하십시오. +3. *저는 교사이고 사람들에게 영감을 주고 가르치는 것을 좋아합니다.* 문장에 사용된 독특한 단어는 몇 개입니까? 분할 방법을 사용하고 고유한 단어를 가져오도록 설정합니다. + +🎉 축하합니다! 🎉 + +[<< 6일차](../06_Day_Tuples/06_tuples.md) | [8일차 >>](../08_Day_Dictionaries/08_dictionaries.md) diff --git a/Korean/10_loops_ko.md b/Korean/10_loops_ko.md new file mode 100644 index 000000000..8b88fd87f --- /dev/null +++ b/Korean/10_loops_ko.md @@ -0,0 +1,448 @@ +
30 Days Of Python: Day 10 - Loops Twitter Follow +
+

Author: Asabeneh Yetayeh
Second Edition: July, 2021

+
+ +[<< Day 9](../09_Day_Conditionals/09_conditionals.md) | [Day 11 >>](../11_Day_Functions/11_functions.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 Day 10](#-day-10) + - [Loops](#loops) + - [While 루프](#while-루프) + - [Break 과 Continue - Part 1](#break-and-continue---part-1) + - [For 루프](#for-루프) + - [Break 과 Continue - Part 2](#break-and-continue---part-2) + - [범위 기능](#범위-기능) + - [중첩 For 루프](#중첩-for-루프) + - [For Else](#for-else) + - [Pass](#pass) + - [💻 Exercises: Day 10](#-exercises-day-10) + - [Exercises: Level 1](#exercises-level-1) + - [Exercises: Level 2](#exercises-level-2) + - [Exercises: Level 3](#exercises-level-3) + +# 📘 Day 10 + +## Loops + +인생은 일상으로 가득 차 있습니다. 프로그래밍에서 우리는 또한 많은 반복 작업을 수행합니다. 반복 작업을 처리하기 위해 프로그래밍 언어는 루프를 사용합니다. Python 프로그래밍 언어는 또한 다음 유형의 두 루프를 제공합니다. + +1. while loop +2. for loop + +### While 루프 + +우리는 while 루프를 만들기 위해 예약어 *while* 을 사용합니다. 주어진 조건이 만족될 때까지 문 블록을 반복적으로 실행하는 데 사용됩니다. 조건이 거짓이 되면 루프 뒤의 코드 행이 계속 실행됩니다. + +```py + # syntax +while condition: + code goes here +``` + +**예시:** + +```py +count = 0 +while count < 5: + print(count) + count = count + 1 +#prints from 0 to 4 +``` + +위의 while 루프에서 count가 5일 때 조건이 false가 됩니다. 이때 루프가 중지됩니다. 조건이 더 이상 참이 아닐 때 코드 블록을 실행하고 싶다면 *else* 를 사용할 수 있습니다. + +```py + # syntax +while condition: + code goes here +else: + code goes here +``` + +**예시:** + +```py +count = 0 +while count < 5: + print(count) + count = count + 1 +#prints from 0 to 4 +``` + +위의 루프 조건은 count가 5이고 루프가 중지되고 실행이 else 문을 시작하면 거짓이 됩니다. 결과적으로 5가 인쇄됩니다. + +### Break 과 Continue - Part 1 + +- 중단: 루프에서 벗어나거나 중단하고 싶을 때 중단을 사용합니다. + +```py +# syntax +while condition: + code goes here + if another_condition: + break +``` + +**예시:** + +```py +count = 0 +while count < 5: + print(count) + count = count + 1 + if count == 3: + break +``` + +위의 while 루프는 0, 1, 2만 인쇄하지만 3에 도달하면 중지합니다. + +- 계속: continue 문을 사용하면 현재 반복을 건너뛰고 다음을 계속할 수 있습니다. + +```py + # syntax +while condition: + code goes here + if another_condition: + continue +``` + +**예시:** + +```py +count = 0 +while count < 5: + if count == 3: + continue + print(count) + count = count + 1 +``` + +위의 while 루프는 0, 1, 2 및 4만 인쇄합니다(3을 건너뜁니다). + +### For 루프 + +*for* 키워드는 다른 프로그래밍 언어와 유사하지만 구문이 약간 다른 for 루프를 만드는 데 사용됩니다. 루프는 시퀀스(즉, 목록, 튜플, 사전, 집합 또는 문자열)를 반복하는 데 사용됩니다. + +- For loop with list + +```py +# syntax +for iterator in lst: + code goes here +``` + +**예시:** + +```py +numbers = [0, 1, 2, 3, 4, 5] +for number in numbers: # number is temporary name to refer to the list's items, valid only inside this loop + print(number) # the numbers will be printed line by line, from 0 to 5 +``` + +- For loop with string + +```py +# syntax +for iterator in string: + code goes here +``` + +**예시:** + +```py +language = 'Python' +for letter in language: + print(letter) + + +for i in range(len(language)): + print(language[i]) +``` + +- For loop with tuple + +```py +# syntax +for iterator in tpl: + code goes here +``` + +**예시:** + +```py +numbers = (0, 1, 2, 3, 4, 5) +for number in numbers: + print(number) +``` + +- 사전을 사용한 For 루프 사전을 통한 루프는 사전의 키를 제공합니다. + +```py + # syntax +for iterator in dct: + code goes here +``` + +**예시:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } +} +for key in person: + print(key) + +for key, value in person.items(): + print(key, value) # this way we get both keys and values printed out +``` + +- Loops in set + +```py +# syntax +for iterator in st: + code goes here +``` + +**예시:** + +```py +it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'} +for company in it_companies: + print(company) +``` + +### Break 과 Continue - Part 2 + +짧은 알림: *중단* : 루프가 완료되기 전에 중단하고 싶을 때 중단을 사용합니다. + +```py +# syntax +for iterator in sequence: + code goes here + if condition: + break +``` + +**예시:** + +```py +numbers = (0,1,2,3,4,5) +for number in numbers: + print(number) + if number == 3: + break +``` + +위의 예에서 루프는 3에 도달하면 중지됩니다. + +계속: 루프 반복에서 일부 단계를 건너뛰고 싶을 때 계속을 사용합니다. + +```py + # syntax +for iterator in sequence: + code goes here + if condition: + continue +``` + +**예시:** + +```py +numbers = (0,1,2,3,4,5) +for number in numbers: + print(number) + if number == 3: + continue + print('Next number should be ', number + 1) if number != 5 else print("loop's end") # for short hand conditions need both if and else statements +print('outside the loop') +``` + +위의 예에서 숫자가 3이면 조건 *다음* 단계(루프 내부)를 건너뛰고 반복이 남아 있으면 루프 실행이 계속됩니다. + +### 범위 기능 + +*range()* 함수는 숫자 목록에 사용됩니다. *범위(시작, 끝, 단계)* 는 시작, 종료 및 증분의 세 가지 매개변수를 사용합니다. 기본적으로 0부터 시작하고 증분은 1입니다. 범위 시퀀스에는 최소 1개의 인수(종료)가 필요합니다. 범위를 사용하여 시퀀스 만들기 + +```py +lst = list(range(11)) +print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +st = set(range(1, 11)) # 2 arguments indicate start and end of the sequence, step set to default 1 +print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + +lst = list(range(0,11,2)) +print(lst) # [0, 2, 4, 6, 8, 10] +st = set(range(0,11,2)) +print(st) # {0, 2, 4, 6, 8, 10} +``` + +```py +# syntax +for iterator in range(start, end, step): +``` + +**예시:** + +```py +for number in range(11): + print(number) # prints 0 to 10, not including 11 +``` + +### 중첩 For 루프 + +루프 안에 루프를 작성할 수 있습니다. + +```py +# syntax +for x in y: + for t in x: + print(t) +``` + +**예시:** + +```py +person = { + 'first_name': 'Asabeneh', + 'last_name': 'Yetayeh', + 'age': 250, + 'country': 'Finland', + 'is_marred': True, + 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address': { + 'street': 'Space street', + 'zipcode': '02210' + } +} +for key in person: + if key == 'skills': + for skill in person['skills']: + print(skill) +``` + +### For Else + +루프가 끝날 때 메시지를 실행하려면 else를 사용합니다. + +```py +# syntax +for iterator in range(start, end, step): + do something +else: + print('The loop ended') +``` + +**예시:** + +```py +for number in range(11): + print(number) # prints 0 to 10, not including 11 +else: + print('The loop stops at', number) +``` + +### Pass + +Python에서 when 문이 필요하지만(세미콜론 뒤에) 코드를 실행하는 것을 좋아하지 않으므로 오류를 피하기 위해 *pass* 라는 단어를 쓸 수 있습니다. 또한 향후 진술을 위해 자리 표시자로 사용할 수 있습니다. + +**예시:** + +```py +for number in range(6): + pass +``` + +🌕 당신은 큰 이정표를 세웠고, 당신은 멈출 수 없습니다. 계속하세요! 10일차 챌린지를 방금 완료했으며 위대함을 향한 10단계를 앞두고 있습니다. 이제 뇌와 근육을 위한 몇 가지 운동을 하십시오. + +## 💻 Exercises: Day 10 + +### Exercises: Level 1 + +1. for 루프를 사용하여 0에서 10까지 반복하고 while 루프를 사용하여 동일한 작업을 수행합니다. + +2. for 루프를 사용하여 10에서 0까지 반복하고 while 루프를 사용하여 동일한 작업을 수행합니다. + +3. print()를 7번 호출하는 루프를 작성하여 다음 삼각형을 출력합니다. + + ```py + # + ## + ### + #### + ##### + ###### + ####### + ``` + +4. 중첩 루프를 사용하여 다음을 만듭니다. + + ```sh + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + ``` + +5. 다음 패턴을 인쇄합니다. + + ```sh + 0 x 0 = 0 + 1 x 1 = 1 + 2 x 2 = 4 + 3 x 3 = 9 + 4 x 4 = 16 + 5 x 5 = 25 + 6 x 6 = 36 + 7 x 7 = 49 + 8 x 8 = 64 + 9 x 9 = 81 + 10 x 10 = 100 + ``` + +6. for 루프를 사용하여 ['Python', 'Numpy','Pandas','Django', 'Flask'] 목록을 반복하고 항목을 출력합니다. + +7. for 루프를 사용하여 0에서 100까지 반복하고 짝수만 출력 + +8. for 루프를 사용하여 0에서 100까지 반복하고 홀수만 출력 + +### Exercises: Level 2 + +1. for 루프를 사용하여 0에서 100까지 반복하고 모든 숫자의 합계를 인쇄합니다. + +```sh +The sum of all numbers is 5050. +``` + +1. for 루프를 사용하여 0에서 100까지 반복하고 모든 짝수의 합과 모든 승산의 합을 인쇄합니다. + + ```sh + The sum of all evens is 2550. And the sum of all odds is 2500. + ``` + +### Exercises: Level 3 + +1. 데이터 폴더로 이동하여 [countries.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py) 파일을 사용합니다. 국가를 순환하고 단어 *land* 를 포함하는 모든 국가를 추출합니다. +2. 이것은 과일 목록입니다. ['banana', 'orange', 'mango', 'lemon'] 루프를 사용하여 순서를 뒤집습니다. +3. 데이터 폴더로 이동하여 [countries_data.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) 파일을 사용합니다. + 1. 데이터의 총 언어 수는 얼마입니까? + 2. 데이터에서 가장 많이 사용되는 10개 언어 찾기 + 3. 세계에서 인구가 가장 많은 10개 국가 찾기 + +🎉 축하합니다! 🎉 + +[<< Day 9](../09_Day_Conditionals/09_conditionals.md) | [Day 11 >>](../11_Day_Functions/11_functions.md) From 1f2f42bf527f36a4cb6691334ebb0f095e80bc4a Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Fri, 9 Dec 2022 11:27:47 +0900 Subject: [PATCH 19/63] Day 07 10 md --- Korean/04_strings_ko.md | 2 +- Korean/07_sets_ko.md | 2 +- Korean/10_loops_ko.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Korean/04_strings_ko.md b/Korean/04_strings_ko.md index b2d92dee8..dc74f7c31 100644 --- a/Korean/04_strings_ko.md +++ b/Korean/04_strings_ko.md @@ -1,5 +1,5 @@
- 30 Days Of Python: Day 4 - Strings Twitter Follow +

30 Days Of Python: Day 4 - Strings

Twitter Follow

Author: Asabeneh Yetayeh
Second Edition: July, 2021

diff --git a/Korean/07_sets_ko.md b/Korean/07_sets_ko.md index 46092fb72..815f51e27 100644 --- a/Korean/07_sets_ko.md +++ b/Korean/07_sets_ko.md @@ -1,4 +1,4 @@ -
30 Days Of Python: Day 7 - Sets Twitter Follow +

30 Days Of Python: Day 7 - Sets

Twitter Follow

Author: Asabeneh Yetayeh
Second Edition: July, 2021

diff --git a/Korean/10_loops_ko.md b/Korean/10_loops_ko.md index 8b88fd87f..408d943cf 100644 --- a/Korean/10_loops_ko.md +++ b/Korean/10_loops_ko.md @@ -1,4 +1,4 @@ -
30 Days Of Python: Day 10 - Loops Twitter Follow +

30 Days Of Python: Day 10 - Loops

Twitter Follow

Author: Asabeneh Yetayeh
Second Edition: July, 2021

From 3670b7000e417437d909efd8e2882235eb599a30 Mon Sep 17 00:00:00 2001 From: jshyun1 Date: Fri, 9 Dec 2022 11:32:23 +0900 Subject: [PATCH 20/63] kor ver --- Korean/04_strings_ko.md | 26 +++++++++++++------------- Korean/10_loops_ko.md | 4 ++-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Korean/04_strings_ko.md b/Korean/04_strings_ko.md index dc74f7c31..a5e1d774f 100644 --- a/Korean/04_strings_ko.md +++ b/Korean/04_strings_ko.md @@ -10,20 +10,20 @@ - [Day 4](#day-4) - [문자열](#strings) - - [문자열 만들기](#creating-a-string) - - [문자열 연결](#string-concatenation) - - [문자열의 이스케이프 시퀀스](#escape-sequences-in-strings) - - [문자열 포매팅](#string-formatting) - - [올드 스타일 문자열 포매팅(% 연산자)](#old-style-string-formatting--operator) - - [새로운 스타일 문자열 포매팅(str.format)](#new-style-string-formatting-strformat) + - [문자열 만들기](#문자열-만들기) + - [문자열 연결](#문자열-연결) + - [문자열의 이스케이프 시퀀스](#문자열의-이스케이프-시퀀스) + - [문자열 포매팅](#문자열-포매팅) + - [올드 스타일 문자열 포매팅(% 연산자)](#올드-스타일-문자열-포매팅%-연산자) + - [새로운 스타일 문자열 포매팅(str.format)](#새로운-스타일-문자열-포매팅str.format) - [문자열 Interpolation / f-Strings (Python 3.6+)](#string-interpolation--f-strings-python-36) - - [문자 시퀀스로서의 Python 문자열](#python-strings-as-sequences-of-characters) - - [언패킹 문자](#unpacking-characters) - - [인덱스로 문자열의 문자에 액세스](#accessing-characters-in-strings-by-index) - - [파이썬 문자열 슬라이싱](#slicing-python-strings) - - [문자열 리버스](#reversing-a-string) - - [슬라이싱하는 동안 문자 건너뛰기](#skipping-characters-while-slicing) - - [문자열 메서드](#string-methods) + - [문자 시퀀스로서의 Python 문자열](#문자-시퀀스로서의-Python-문자열) + - [언패킹 문자](#언패킹-문자) + - [인덱스로 문자열의 문자에 액세스](#인덱스로-문자열의-문자에-액세스) + - [파이썬 문자열 슬라이싱](#파이썬-문자열-슬라이싱) + - [문자열 리버스](#문자열-리버스) + - [슬라이싱하는 동안 문자 건너뛰기](#슬라이싱하는-동안-문자-건너뛰기) + - [문자열 메서드](#문자열-메서드) - [💻 Exercises - Day 4](#-exercises---day-4) # Day 4 diff --git a/Korean/10_loops_ko.md b/Korean/10_loops_ko.md index 408d943cf..0b6f58d92 100644 --- a/Korean/10_loops_ko.md +++ b/Korean/10_loops_ko.md @@ -10,9 +10,9 @@ - [📘 Day 10](#-day-10) - [Loops](#loops) - [While 루프](#while-루프) - - [Break 과 Continue - Part 1](#break-and-continue---part-1) + - [Break 과 Continue - Part 1](#break-과-continue---part-1) - [For 루프](#for-루프) - - [Break 과 Continue - Part 2](#break-and-continue---part-2) + - [Break 과 Continue - Part 2](#break-과-continue---part-2) - [범위 기능](#범위-기능) - [중첩 For 루프](#중첩-for-루프) - [For Else](#for-else) From 0b19ebad50136280bab91d261a062bdeac926a4c Mon Sep 17 00:00:00 2001 From: ShinYooJung Date: Fri, 9 Dec 2022 14:39:31 +0900 Subject: [PATCH 21/63] Add Day 5 Korean Translation --- Korean/05_Day_Lists/05_lists.md | 588 ++++++++++++++++++++++++++++++++ 1 file changed, 588 insertions(+) create mode 100644 Korean/05_Day_Lists/05_lists.md diff --git a/Korean/05_Day_Lists/05_lists.md b/Korean/05_Day_Lists/05_lists.md new file mode 100644 index 000000000..4b4e89a11 --- /dev/null +++ b/Korean/05_Day_Lists/05_lists.md @@ -0,0 +1,588 @@ +
+

30 Days Of Python: Day 5 - Lists

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ Second Edition: July - 2021 +
+ +
+ +[<< Day 4](../04_Day_Strings/04_strings.md) | [Day 6 >>](../06_Day_Tuples/06_tuples.md) + +![30DaysOfPython](../../images/30DaysOfPython_banner3@2x.png) + +- [Day 5](#day-5) + - [Lists](#lists) + - [How to Create a List](#how-to-create-a-list) + - [Accessing List Items Using Positive Indexing](#accessing-list-items-using-positive-indexing) + - [Accessing List Items Using Negative Indexing](#accessing-list-items-using-negative-indexing) + - [Unpacking List Items](#unpacking-list-items) + - [Slicing Items from a List](#slicing-items-from-a-list) + - [Modifying Lists](#modifying-lists) + - [Checking Items in a List](#checking-items-in-a-list) + - [Adding Items to a List](#adding-items-to-a-list) + - [Inserting Items into a List](#inserting-items-into-a-list) + - [Removing Items from a List](#removing-items-from-a-list) + - [Removing Items Using Pop](#removing-items-using-pop) + - [Removing Items Using Del](#removing-items-using-del) + - [Clearing List Items](#clearing-list-items) + - [Copying a List](#copying-a-list) + - [Joining Lists](#joining-lists) + - [Counting Items in a List](#counting-items-in-a-list) + - [Finding Index of an Item](#finding-index-of-an-item) + - [Reversing a List](#reversing-a-list) + - [Sorting List Items](#sorting-list-items) + - [💻 Exercises: Day 5](#-exercises-day-5) + - [Exercises: Level 1](#exercises-level-1) + - [Exercises: Level 2](#exercises-level-2) + +# Day 5 + +## Lists + +파이썬에는 네 가지 컬렉션 자료형이 있습니다. + +- List: 정렬되고 변경 가능(수정 가능)한 컬렉션입니다. 중복 값을 허용합니다. +- Tuple: 정렬되고 변경 불가능하거나 수정 불가능한(불변) 컬렉션입니다. 중복 값을 허용합니다. +- Set: 순서가 지정되지 않고 인덱스가 없고 수정할 수 없는 컬렉션이지만 새 아이템을 추가할 수 있습니다. 중복 값은 허용되지 않습니다. +- Dictionary: 정렬되지 않고 변경 가능(수정 가능)하며 인덱스가 있는 컬렉션입니다. 중복 값이 없습니다. + +리스트는 정렬되고 수정(변경) 가능한 다양한 자료형의 컬렉션입니다. 목록은 비어 있거나 다른 자료형 아이템을 가질 수 있습니다. + +### How to Create a List + +파이썬에서 리스트는 두가지 방법으로 생성할 수 있습니다: + +- list 내장 함수를 사용 + +```py +# syntax +lst = list() +``` + +```py +empty_list = list() # 이건 빈 리스트 입니다, 리스트 안에 아무 값도 없습니다 +print(len(empty_list)) # 0 +``` + +- 대괄호 사용, [] + +```py +# syntax +lst = [] +``` + +```py +empty_list = [] # 이건 빈 리스트 입니다, 리스트 안에 아무 값도 없습니다 +print(len(empty_list)) # 0 +``` + +초기 값이 있는 리스트입니다. _len()_ 을 사용하여 리스트의 길이를 찾습니다. + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] # list of fruits +vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # list of vegetables +animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products +web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # list of web technologies +countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] + +# Print the lists and its length +print('Fruits:', fruits) +print('Number of fruits:', len(fruits)) +print('Vegetables:', vegetables) +print('Number of vegetables:', len(vegetables)) +print('Animal products:',animal_products) +print('Number of animal products:', len(animal_products)) +print('Web technologies:', web_techs) +print('Number of web technologies:', len(web_techs)) +print('Countries:', countries) +print('Number of countries:', len(countries)) +``` + +```sh +output +Fruits: ['banana', 'orange', 'mango', 'lemon'] +Number of fruits: 4 +Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +Number of vegetables: 5 +Animal products: ['milk', 'meat', 'butter', 'yoghurt'] +Number of animal products: 4 +Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] +Number of web technologies: 7 +Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] +Number of countries: 5 +``` + +- 리스트는 서로 다른 자료형의 아이템을 가질 수 있습니다. + +```py + lst = ['Asabeneh', 250, True, {'country':'Finland', 'city':'Helsinki'}] # 다른 자료형을 가진 리스트 +``` + +### Accessing List Items Using Positive Indexing + +인덱스를 사용하여 리스트의 각 아이템에 액세스합니다. 리스트 인덱스는 0부터 시작합니다. 아래 그림은 인덱스가 시작되는 위치를 명확하게 보여줍니다. +![List index](../../images/list_index.png) + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +first_fruit = fruits[0] # 인덱스를 사용해 첫번째 아이템에 접근합니다 +print(first_fruit) # banana +second_fruit = fruits[1] +print(second_fruit) # orange +last_fruit = fruits[3] +print(last_fruit) # lemon +# Last index +last_index = len(fruits) - 1 +last_fruit = fruits[last_index] +``` + +### Accessing List Items Using Negative Indexing + +음수 인덱스는 끝에서 시작하는 것을 의미하며 -1은 마지막 아이템을, -2는 마지막에서 두번쨰 아이템을 의미합니다. + +![List negative indexing](../../images/list_negative_indexing.png) + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +first_fruit = fruits[-4] +last_fruit = fruits[-1] +second_last = fruits[-2] +print(first_fruit) # banana +print(last_fruit) # lemon +print(second_last) # mango +``` + +### Unpacking List Items + +```py +lst = ['item','item2','item3', 'item4', 'item5'] +first_item, second_item, third_item, *rest = lst +print(first_item) # item1 +print(second_item) # item2 +print(third_item) # item3 +print(rest) # ['item4', 'item5'] + +``` + +```py +# First Example +fruits = ['banana', 'orange', 'mango', 'lemon','lime','apple'] +first_fruit, second_fruit, third_fruit, *rest = lst +print(first_fruit) # banana +print(second_fruit) # orange +print(third_fruit) # mango +print(rest) # ['lemon','lime','apple'] +# Second Example about unpacking list +first, second, third,*rest, tenth = [1,2,3,4,5,6,7,8,9,10] +print(first) # 1 +print(second) # 2 +print(third) # 3 +print(rest) # [4,5,6,7,8,9] +print(tenth) # 10 +# Third Example about unpacking list +countries = ['Germany', 'France','Belgium','Sweden','Denmark','Finland','Norway','Iceland','Estonia'] +gr, fr, bg, sw, *scandic, es = countries +print(gr) +print(fr) +print(bg) +print(sw) +print(scandic) +print(es) +``` + +### Slicing Items from a List + +- 양수 인덱싱: start, end 및 step을 지정하여 양수 인덱스 범위를 지정할 수 있습니다. 반환 값은 새 리스트가 됩니다. (start의 디폴트값 = 0, end = len(lst) - 1 (마지막 아이템), step = 1) + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +all_fruits = fruits[0:4] # 모든 fruits를 반환합니다 +# 이것또한 위와 같은 값을 반환합니다 +all_fruits = fruits[0:] # 우리가 어디서 멈출 지 설정하지 않으면, 모든 것을 포함합니다 +orange_and_mango = fruits[1:3] # 첫번째 인덱스를 포함하지 않습니다 +orange_mango_lemon = fruits[1:] +orange_and_lemon = fruits[::2] # 여기서 세번째 인자인 step을 사용했습니다. 모든 두번째 아이템을 포함합니다 - ['banana', 'mango'] +``` + +- 음수 인덱싱: start, end 및 step을 지정하여 음수 인덱스의 범위를 지정할 수 있습니다. 반환 값은 새 리스트가 됩니다. + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +all_fruits = fruits[-4:] # 모든 fruits를 반환합니다 +orange_and_mango = fruits[-3:-1] # 마지막 인덱스를 포함하지 않습니다,['orange', 'mango'] +orange_mango_lemon = fruits[-3:] # 이것은 -3 부터 시작하여 끝까지의 값을 줍니다,['orange', 'mango', 'lemon'] +reverse_fruits = fruits[::-1] # 음수의 step은 리스트를 역순으로 가집니다,['lemon', 'mango', 'orange', 'banana'] +``` + +### Modifying Lists + +리스트는 변경 가능하거나 수정 가능한 순서가 있는 아이템들의 컬렉션입니다. 과일 리스트를 수정해봅시다. + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits[0] = 'avocado' +print(fruits) # ['avocado', 'orange', 'mango', 'lemon'] +fruits[1] = 'apple' +print(fruits) # ['avocado', 'apple', 'mango', 'lemon'] +last_index = len(fruits) - 1 +fruits[last_index] = 'lime' +print(fruits) # ['avocado', 'apple', 'mango', 'lime'] +``` + +### Checking Items in a List + +*in* 연산자를 사용하여 아이템이 리스트의 구성원인지 확인합니다. 아래 예시를 봅시다. + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +does_exist = 'banana' in fruits +print(does_exist) # True +does_exist = 'lime' in fruits +print(does_exist) # False +``` + +### Adding Items to a List + +기존 리스트의 끝에 아이템을 추가하려면 *append()* 메서드를 사용합니다. + +```py +# syntax +lst = list() +lst.append(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.append('apple') +print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple'] +fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime'] +print(fruits) +``` + +### Inserting Items into a List + +*insert()* 메서드를 사용하여 목록의 지정된 인덱스에 하나의 아이템을 삽입할 수 있습니다. 다른 아이템들은 오른쪽으로 이동한다는 것에 주의합시다. *insert()* 메서드는 인덱스와 삽입할 아이템이라는 두 가지 인자를 가집니다. + +```py +# syntax +lst = ['item1', 'item2'] +lst.insert(index, item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.insert(2, 'apple') # orange와 mango 사이에 apple을 삽입 +print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon'] +fruits.insert(3, 'lime') # ['banana', 'orange', 'apple', 'lime', 'mango', 'lemon'] +print(fruits) +``` + +### Removing Items from a List + +remove 메서드는 리스트에서 지정된 아이템을 삭제합니다. + +```py +# syntax +lst = ['item1', 'item2'] +lst.remove(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon', 'banana'] +fruits.remove('banana') +print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - 이 메서드는 리스트에서 첫번째로 존재하는 아이템을 삭제합니다 +fruits.remove('lemon') +print(fruits) # ['orange', 'mango', 'banana'] +``` + +### Removing Items Using Pop + +*pop()* 메서드는 지정된 인덱스를 제거합니다(또는 인덱스가 지정되지 않은 경우 마지막 아이템): + +```py +# syntax +lst = ['item1', 'item2'] +lst.pop() # 마지막 아이템 +lst.pop(index) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.pop() +print(fruits) # ['banana', 'orange', 'mango'] + +fruits.pop(0) +print(fruits) # ['orange', 'mango'] +``` + +### Removing Items Using Del + +*del* 키워드는 지정된 인덱스를 삭제하며 인덱스 범위 내의 아이템을 삭제하는 데도 사용할 수 있습니다. 또한 리스트를 완전히 삭제할 수도 있습니다. + +```py +# syntax +lst = ['item1', 'item2'] +del lst[index] # 하니의 아이템 +del lst # 리스트를 완전히 삭제 +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon', 'kiwi', 'lime'] +del fruits[0] +print(fruits) # ['orange', 'mango', 'lemon', 'kiwi', 'lime'] +del fruits[1] +print(fruits) # ['orange', 'lemon', 'kiwi', 'lime'] +del fruits[1:3] # 이것은 주어진 인덱스 사이의 아이템을 삭제합니다, 그러므로 인덱스가 3인 아이템은 삭제되지 않습니다! +print(fruits) # ['orange', 'lime'] +del fruits +print(fruits) # NameError: name 'fruits' is not defined 가 발생해야합니다 +``` + +### Clearing List Items + +*clear()* 메서드를 사용해 리스트 비우기: + +```py +# syntax +lst = ['item1', 'item2'] +lst.clear() +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.clear() +print(fruits) # [] +``` + +### Copying a List + +다음의 방법으로 새 변수에 재할당하여 리스트를 복사할 수 있습니다:list2 = list1. 이제 list2는 list1의 참조이며, list2에서 변경한 내용은 원본 list1도 수정합니다. 하지만 원본을 수정하고 싶지 않고 다른 사본을 갖고 싶어하는 경우가 많습니다. 위의 문제를 피하는 한 가지 방법은 _copy()_ 를 사용하는 것입니다. + +```py +# syntax +lst = ['item1', 'item2'] +lst_copy = lst.copy() +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits_copy = fruits.copy() +print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon'] +``` + +### Joining Lists + +파이썬에서 두 개 이상의 목록을 결합하거나 연결하는 방법은 여러 가지가 있습니다. + +- 플러스 연산자 (+) + +```py +# syntax +list3 = list1 + list2 +``` + +```py +positive_numbers = [1, 2, 3, 4, 5] +zero = [0] +negative_numbers = [-5,-4,-3,-2,-1] +integers = negative_numbers + zero + positive_numbers +print(integers) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] +fruits = ['banana', 'orange', 'mango', 'lemon'] +vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +fruits_and_vegetables = fruits + vegetables +print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +``` + +- extend() 메서드를 사용하여 연결 + *extend()* 메서드를 사용하면 리스트에 리스트를 추가할 수 있습니다. 아래 예를 참조합시다. + +```py +# syntax +list1 = ['item1', 'item2'] +list2 = ['item3', 'item4', 'item5'] +list1.extend(list2) +``` + +```py +num1 = [0, 1, 2, 3] +num2= [4, 5, 6] +num1.extend(num2) +print('Numbers:', num1) # Numbers: [0, 1, 2, 3, 4, 5, 6] +negative_numbers = [-5,-4,-3,-2,-1] +positive_numbers = [1, 2, 3,4,5] +zero = [0] + +negative_numbers.extend(zero) +negative_numbers.extend(positive_numbers) +print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] +fruits = ['banana', 'orange', 'mango', 'lemon'] +vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +fruits.extend(vegetables) +print('Fruits and vegetables:', fruits ) # Fruits and vegetables: ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +``` + +### Counting Items in a List + +*count()* 메서드는 리스트에 아이템이 나타나는 횟수를 반환합니다: + +```py +# syntax +lst = ['item1', 'item2'] +lst.count(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +print(fruits.count('orange')) # 1 +ages = [22, 19, 24, 25, 26, 24, 25, 24] +print(ages.count(24)) # 3 +``` + +### Finding Index of an Item + +*index()* 메서드는 리스트에 있는 아이템의 인덱스를 반환합니다: + +```py +# syntax +lst = ['item1', 'item2'] +lst.index(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +print(fruits.index('orange')) # 1 +ages = [22, 19, 24, 25, 26, 24, 25, 24] +print(ages.index(24)) # 2, 처음 만난 것 +``` + +### Reversing a List + +*reverse()* 메서드는 리스트의 순서를 거꾸로 합니다. + +```py +# syntax +lst = ['item1', 'item2'] +lst.reverse() + +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.reverse() +print(fruits) # ['lemon', 'mango', 'orange', 'banana'] +ages = [22, 19, 24, 25, 26, 24, 25, 24] +ages.reverse() +print(ages) # [24, 25, 24, 26, 25, 24, 19, 22] +``` + +### Sorting List Items + +리스트를 정렬하려면 _sort()_ 메서드 또는 _sorted()_ 내장 함수를 사용할 수 있습니다. _sort()_ 메서드는 리스트 아이템을 오름차순으로 정렬하고 원래 리스트를 수정합니다. 만약 _sort()_ 메서드의 reverse의 인자가 true라면, 그것은 목록을 내림차순으로 배열할 것입니다. + +- sort(): 이 메서드는 원래 리스트를 수정합니다 + + ```py + # syntax + lst = ['item1', 'item2'] + lst.sort() # 오름차순 + lst.sort(reverse=True) # 내림차순 + ``` + + **Example:** + + ```py + fruits = ['banana', 'orange', 'mango', 'lemon'] + fruits.sort() + print(fruits) # 알파벳순으로 정렬, ['banana', 'lemon', 'mango', 'orange'] + fruits.sort(reverse=True) + print(fruits) # ['orange', 'mango', 'lemon', 'banana'] + ages = [22, 19, 24, 25, 26, 24, 25, 24] + ages.sort() + print(ages) # [19, 22, 24, 24, 24, 25, 25, 26] + + ages.sort(reverse=True) + print(ages) # [26, 25, 25, 24, 24, 24, 22, 19] + ``` + + sorted(): 원래 리스트를 수정하지 않고 정렬된 리스트를 반환합니다 + **Example:** + + ```py + fruits = ['banana', 'orange', 'mango', 'lemon'] + print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange'] + # 역순 + fruits = ['banana', 'orange', 'mango', 'lemon'] + fruits = sorted(fruits,reverse=True) + print(fruits) # ['orange', 'mango', 'lemon', 'banana'] + ``` + +🌕 당신은 성실하고 이미 많은 것을 성취했습니다. 여러분은 이제 막 5일차 도전을 마쳤고 위대함을 향한 5걸음 앞에 있습니다. 이제 여러분의 뇌와 근육을 위한 운동을 하세요. + +## 💻 Exercises: Day 5 + +### Exercises: Level 1 + +1. 빈 리스트를 선언합니다 +2. 5개 이상의 아이템을 갖는 리스트를 선언합니다 +3. 당신의 리스트의 길이를 알아봅니다 +4. 리스트의 첫번째, 중간의, 마지막 아이템을 얻어봅니다 +5. mixed_data_types 라는 리스트를 선언하고, 당신의 이름, 나이, 키, 결혼 여부, 주소를 넣어봅시다 +6. it_companies 라는 이름의 목록 변수를 선언하고 초기 값에 Facebook, Google, Microsoft, Apple, IBM, Oracle 및 Amazon을 할당합니다 +7. _print()_ 를 사용하여 리스트를 프린트 합니다 +8. 리스트에 있는 기업 수를 프린트 합니다 +9. 첫번째, 중간, 마지막 기업을 프린트 합니다 +10. 기업 중 하나를 수정하고 리스트를 프린트 합니다 +11. it_companies 에 하나의 IT 기업을 추가합니다 +12. 회사 리스트 중간에 IT 기업을 추가합니다 +13. it_companies 이름 중 하나를 대문자로 변경합니다 (IBM 제외!) +14. '#;  ' 라는 문자열로 it_companies 에 연결합니다 +15. it_companies 리스트에 특정 기업이 존재하는 지 확인합니다 +16. sort() 메서드를 사용해 리스트를 정렬합니다 +17. reverse() 메서드를 사용하여 리스트를 내림차순으로 반전합니다 +18. 리스트에서 처음 3개의 기업을 잘라냅니다 +19. 리스트에서 마지막 3개의 기업을 잘라냅니다 +20. 리스트에서 중간의 IT 기업 또는 기업들을 잘라냅니다 +21. 리스트에서 첫번째 IT 기업을 삭제합니다 +22. 리스트에서 중간의 IT 기업 또는 기업들을 삭제합니다 +23. 리스트에서 마지막 IT 기업을 삭제합니다 +24. 리스트에서 모든 IT 기업을 삭제합니다 +25. IT 기업 리스트를 완전히 제거합니다 +26. 다음 리스트를 연결합니다: + + ```py + front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux'] + back_end = ['Node','Express', 'MongoDB'] + ``` + +27. 26번 문제의 리스트를 연결한 후, 연결된 리스트를 복사해 full_stack 변수에 할당합니다. 그리고 Python, SQL, Redux를 삽입합니다. + +### Exercises: Level 2 + +1. 다음은 10명의 학생의 나이 리스트입니다: + +```sh +ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] +``` + +- 리스트를 정렬하고 최소값 및 최대값 찾습니다 +- 리스트에 최소값 및 최대값을 다시 추가합니다 +- 나이의 중위값을 찾습니다(중간 아이템 하나 또는 중간 아이템 두 개를 2로 나눈 값) +- 평균 나이를 구합니다(모든 아이템의 합을 개수로 나눈 값) +- 나이의 범위를 구합니다(최대값 빼기 최소값) +- (최소값 - 평균)과 (최대값 - 평균)의 값을 비교하고 _abs()_ 메서드를 사용합니다. + +1. [국가 목록](https://github.com/Asabeneh/30-Days-Of-Python/tree/master/data/countries.py) 에서 중간 국가를 찾습니다. +1. 국가 리스트를 두개의 리스트로 나눕니다. 짝수라면 두개의 리스트의 크기가 갖게, 아니라면 앞의 리스트가 하나의 국가를 더 갖도록 합니다. +1. ['China', 'Russia', 'USA', 'Finland', 'Sweden', 'Norway', 'Denmark']. 앞의 세개 국가와 나머지를 scandic countries로 unpack합니다. + +🎉 CONGRATULATIONS ! 🎉 + +[<< Day 4](../04_Day_Strings/04_strings.md) | [Day 6 >>](../06_Day_Tuples/06_tuples.md) From ec87e0da4204856c042fa6c0397b49563556f5e6 Mon Sep 17 00:00:00 2001 From: ShinYooJung Date: Fri, 9 Dec 2022 14:44:05 +0900 Subject: [PATCH 22/63] Typo error --- 05_Day_Lists/05_lists.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/05_Day_Lists/05_lists.md b/05_Day_Lists/05_lists.md index ac18fce3a..b3fb49f6a 100644 --- a/05_Day_Lists/05_lists.md +++ b/05_Day_Lists/05_lists.md @@ -364,7 +364,7 @@ print(fruits) # [] ### Copying a List -It is possible to copy a list by reassigning it to a new variable in the following way: list2 = list1. Now, list2 is a reference of list1, any changes we make in list2 will also modify the original, list2. But there are lots of case in which we do not like to modify the original instead we like to have a different copy. One of way of avoiding the problem above is using _copy()_. +It is possible to copy a list by reassigning it to a new variable in the following way: list2 = list1. Now, list2 is a reference of list1, any changes we make in list2 will also modify the original, list1. But there are lots of case in which we do not like to modify the original instead we like to have a different copy. One of way of avoiding the problem above is using _copy()_. ```py # syntax From ab25567784961fc4ca7c80c20f6c287385173ffa Mon Sep 17 00:00:00 2001 From: ShinYooJung Date: Fri, 9 Dec 2022 15:08:05 +0900 Subject: [PATCH 23/63] Add Day 8 Korean Translation --- Korean/08_Day_Dictionaries/08_dictionaries.md | 342 ++++++++++++++++++ 1 file changed, 342 insertions(+) create mode 100644 Korean/08_Day_Dictionaries/08_dictionaries.md diff --git a/Korean/08_Day_Dictionaries/08_dictionaries.md b/Korean/08_Day_Dictionaries/08_dictionaries.md new file mode 100644 index 000000000..a418cac2e --- /dev/null +++ b/Korean/08_Day_Dictionaries/08_dictionaries.md @@ -0,0 +1,342 @@ +
+

30 Days Of Python: Day 8 - Dictionaries

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ Second Edition: July, 2021 +
+ +
+ +[<< Day 7 ](../07_Day_Sets/07_sets.md) | [Day 9 >>](../09_Day_Conditionals/09_conditionals.md) + +![30DaysOfPython](../../images/30DaysOfPython_banner3@2x.png) + +- [📘 Day 8](#-day-8) + - [Dictionaries](#dictionaries) + - [Creating a Dictionary](#creating-a-dictionary) + - [Dictionary Length](#dictionary-length) + - [Accessing Dictionary Items](#accessing-dictionary-items) + - [Adding Items to a Dictionary](#adding-items-to-a-dictionary) + - [Modifying Items in a Dictionary](#modifying-items-in-a-dictionary) + - [Checking Keys in a Dictionary](#checking-keys-in-a-dictionary) + - [Removing Key and Value Pairs from a Dictionary](#removing-key-and-value-pairs-from-a-dictionary) + - [Changing Dictionary to a List of Items](#changing-dictionary-to-a-list-of-items) + - [Clearing a Dictionary](#clearing-a-dictionary) + - [Deleting a Dictionary](#deleting-a-dictionary) + - [Copy a Dictionary](#copy-a-dictionary) + - [Getting Dictionary Keys as a List](#getting-dictionary-keys-as-a-list) + - [Getting Dictionary Values as a List](#getting-dictionary-values-as-a-list) + - [💻 Exercises: Day 8](#-exercises-day-8) + +# 📘 Day 8 + +## Dictionaries + +Dictionary는 순서가 없는 수정(변형) 가능한 쌍(키: 값)의 자료형의 컬렉션입니다. + +### Creating a Dictionary + +Dictionary를 만들려면 중괄호 {} 또는 *dict()* 내장 함수를 사용합니다. + +```py +# syntax +empty_dict = {} +# Dictionary with data values +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +``` + +**Example:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +``` + +상단의 Dictionary는 값이 어떤 자료형일 수도 있다는 것을 보여줍니다:string, boolean, list, tuple, set 또는 dictionary. + +### Dictionary Length + +dictionary 내 'key: value' 쌍의 개수를 확인합니다. + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(len(dct)) # 4 +``` + +**Example:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +print(len(person)) # 7 + +``` + +### Accessing Dictionary Items + +키의 이름을 통해 딕셔너리 아이템에 접근할 수 있습니다. + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(dct['key1']) # value1 +print(dct['key4']) # value4 +``` + +**Example:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +print(person['first_name']) # Asabeneh +print(person['country']) # Finland +print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'] +print(person['skills'][0]) # JavaScript +print(person['address']['street']) # Space street +print(person['city']) # Error +``` + +존재하지 않는 키의 이름으로 아이템에 접근할 경우 에러가 발생할 수 있습니다. 이 에러를 피하기위해 우리는 우선 키가 존재하는지 확인해야합니다. 또는 _get_ 메서드를 사용할수 있습니다. get 메서드는 키가 존재하지 않을 경우, NoneType object 자료형인 None을 반환합니다. +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +print(person.get('first_name')) # Asabeneh +print(person.get('country')) # Finland +print(person.get('skills')) #['HTML','CSS','JavaScript', 'React', 'Node', 'MongoDB', 'Python'] +print(person.get('city')) # None +``` + +### Adding Items to a Dictionary + +딕셔너리에 새로운 키와 값의 쌍을 추가할 수 있습니다. + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct['key5'] = 'value5' +``` + +**Example:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } +} +person['job_title'] = 'Instructor' +person['skills'].append('HTML') +print(person) +``` + +### Modifying Items in a Dictionary + +딕셔너리의 아이템을 수정할 수 있습니다 + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct['key1'] = 'value-one' +``` + +**Example:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +person['first_name'] = 'Eyob' +person['age'] = 252 +``` + +### Checking Keys in a Dictionary + +딕셔너리에 키가 존재하는 지 확인하기 위해 _in_ 연산자를 사용합니다 + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print('key2' in dct) # True +print('key5' in dct) # False +``` + +### Removing Key and Value Pairs from a Dictionary + +- _pop(key)_: 특정 키 이름을 가진 아이템을 삭제합니다 +- _popitem()_: 마지막 아이템을 삭제합니다 +- _del_: 특정 키 이름을 가진 아이템을 삭제합니다 + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct.pop('key1') # removes key1 item +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct.popitem() # removes the last item +del dct['key2'] # removes key2 item +``` + +**Example:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +person.pop('first_name') # Removes the firstname item +person.popitem() # Removes the address item +del person['is_married'] # Removes the is_married item +``` + +### Changing Dictionary to a List of Items + +_items()_ 메서드는 딕셔너리를 튜플의 리스트로 변환합니다. + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(dct.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')]) +``` + +### Clearing a Dictionary + +딕셔너리 내의 아이템을 원하지 않는다면 _clear()_ 메서드를 사용해 비울 수 있습니다 + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(dct.clear()) # None +``` + +### Deleting a Dictionary + +딕셔너리를 사용하지않는다면 완전히 지울 수 있습니다 + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +del dct +``` + +### Copy a Dictionary + +_copy()_ 메서드를 통해 딕셔너리를 복사할 수 있습니다. copy를 사용해 원래 딕셔너리의 변화를 막을 수 있습니다. + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +``` + +### Getting Dictionary Keys as a List + +_keys()_ 메서드는 하나의 딕셔너리의 모든 키를 리스트로 줍니다. + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +keys = dct.keys() +print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4']) +``` + +### Getting Dictionary Values as a List + +_values_ 메서드는 하나의 딕셔너리의 모든 값을 리스트로 줍니다. + +```py +# syntax +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +values = dct.values() +print(values) # dict_values(['value1', 'value2', 'value3', 'value4']) +``` + +🌕 당신은 정말 놀라워요. 이제, 여러분은 사전의 힘으로 완전히 충전되어 있습니다. 여러분은 이제 막 8일째의 도전을 마쳤고 위대함을 향해 8보 전진했습니다. 이제 여러분의 뇌와 근육을 위한 운동을 하세요. + +## 💻 Exercises: Day 8 + +1. dog라는 이름의 빈 딕셔너리를 생성합니다 +2. dog 딕셔너리에 name, color, breed, legs, age 를 추가합니다 +3. student 딕셔너리를 생성하고 first_name, last_name, gender, age, marital status, skills, country, city 와 address 를 키로 추가합니다 +4. student 딕셔너리의 길이를 얻습니다 +5. skills 의 값을 얻고 자료형을 확인합니다, list 여야 합니다 +6. 한개나 두개를 추가해 skills의 값을 수정합니다 +7. 딕셔너리의 키를 리스트로 얻습니다 +8. 딕셔너리의 값을 리스트로 얻습니다 +9. _items()_ 메서드를 이용해 튜플의 리스트로 딕셔너리를 바꿉니다 +10. 딕셔너리의 아이템중 하나를 삭제합니다 +11. 딕셔너리 중 하나를 삭제합니다 + +🎉 CONGRATULATIONS ! 🎉 + +[<< Day 7 ](../07_Day_Sets/07_sets.md) | [Day 9 >>](../09_Day_Conditionals/09_conditionals.md) From 4b3471988d0e9795e5a2576d4947ec4c1c4b71d3 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Sun, 2 Apr 2023 17:11:00 +0300 Subject: [PATCH 24/63] link has been added --- 30_Day_Conclusions/30_conclusions.md | 2 +- readme.md | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/30_Day_Conclusions/30_conclusions.md b/30_Day_Conclusions/30_conclusions.md index d514eec2f..e8865fc6a 100644 --- a/30_Day_Conclusions/30_conclusions.md +++ b/30_Day_Conclusions/30_conclusions.md @@ -30,7 +30,7 @@ In the process of preparing this material I have learned quite a lot and you have inspired me to do more. Congratulations for making it to this level. If you have done all the exercise and the projects, now you are capable to go to a data analysis, data science, machine learning or web development paths. [Support the author for more educational materials](https://www.paypal.com/paypalme/asabeneh). ## Testimony -Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) +Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://testimonial-vdzd.onrender.com/) GIVE FEEDBACK: http://thirtydayofpython-api.herokuapp.com/feedback diff --git a/readme.md b/readme.md index 76a8f85b6..8af2c85ee 100644 --- a/readme.md +++ b/readme.md @@ -102,7 +102,10 @@ If you would like to actively engage in the challenge, you may join the [30DaysO Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of Python programming language was derived from a British sketch comedy series, *Month Python's Flying Circus*. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, many hands on exercises and projects. This challenge is designed for beginners and professionals who want to learn python programming language. It may take 30 to 100 days to complete the challenge, people who actively participate on the telegram group have a high probability of completing the challenge. -If you are a visual learner or in favor of videos, you may get started with this [Python for Absolute Beginners video](https://www.youtube.com/watch?v=11OYpBrhdyM). + +This challenge is easy to read, written in conversational English, engaging, motivating and at the same time, it is very demanding. You need to allocate much time to finish this challenge. If you are a visual learner, you may get the video lesson on Washera YouTube channel. You may start from [Python for Absolute Beginners video](https://youtu.be/OCCWZheOesI). Subscribe the channel, comment and ask questions on YouTube vidoes and be proactive, the author will eventually notice you. + +The author likes to hear your opinion about the challenge, share the author by expressing your thoughts about the 30DaysOfPython challenge. You can leave your testimonial on this [link](https://testimonial-vdzd.onrender.com/) ## Why Python ? From 623a552dbf277737634f0a6c13bafe730adc013a Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Mon, 3 Jul 2023 02:50:12 +0300 Subject: [PATCH 25/63] data added --- data/cats.json | 2732 +++++ data/countries_data_long.json | 20502 ++++++++++++++++++++++++++++++++ 2 files changed, 23234 insertions(+) create mode 100644 data/cats.json create mode 100644 data/countries_data_long.json diff --git a/data/cats.json b/data/cats.json new file mode 100644 index 000000000..65ac320f6 --- /dev/null +++ b/data/cats.json @@ -0,0 +1,2732 @@ +[ + { + "weight": { + "imperial": "7 - 10", + "metric": "3 - 5" + }, + "id": "abys", + "name": "Abyssinian", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/Abyssinian.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/abyssinian", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/abyssinian", + "temperament": "Active, Energetic, Independent, Intelligent, Gentle", + "origin": "Egypt", + "country_codes": "EG", + "country_code": "EG", + "description": "The Abyssinian is easy to care for, and a joy to have in your home. They’re affectionate cats and love both people and other animals.", + "life_span": "14 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 3, + "dog_friendly": 4, + "energy_level": 5, + "grooming": 1, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 2, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Abyssinian_(cat)", + "hypoallergenic": 0, + "reference_image_id": "0XYvRd7oD" + }, + { + "weight": { + "imperial": "7 - 10", + "metric": "3 - 5" + }, + "id": "aege", + "name": "Aegean", + "vetstreet_url": "http://www.vetstreet.com/cats/aegean-cat", + "temperament": "Affectionate, Social, Intelligent, Playful, Active", + "origin": "Greece", + "country_codes": "GR", + "country_code": "GR", + "description": "Native to the Greek islands known as the Cyclades in the Aegean Sea, these are natural cats, meaning they developed without humans getting involved in their breeding. As a breed, Aegean Cats are rare, although they are numerous on their home islands. They are generally friendly toward people and can be excellent cats for families with children.", + "life_span": "9 - 12", + "indoor": 0, + "alt_names": "", + "adaptability": 5, + "affection_level": 4, + "child_friendly": 4, + "dog_friendly": 4, + "energy_level": 3, + "grooming": 3, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Aegean_cat", + "hypoallergenic": 0, + "reference_image_id": "ozEvzdVM-" + }, + { + "weight": { + "imperial": "7 - 16", + "metric": "3 - 7" + }, + "id": "abob", + "name": "American Bobtail", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/AmericanBobtail.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/american-bobtail", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/american-bobtail", + "temperament": "Intelligent, Interactive, Lively, Playful, Sensitive", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "American Bobtails are loving and incredibly intelligent cats possessing a distinctive wild appearance. They are extremely interactive cats that bond with their human family with great devotion.", + "life_span": "11 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 1, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/American_Bobtail", + "hypoallergenic": 0, + "reference_image_id": "hBXicehMA" + }, + { + "weight": { + "imperial": "5 - 10", + "metric": "2 - 5" + }, + "id": "acur", + "name": "American Curl", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/AmericanCurl.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/american-curl", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/american-curl", + "temperament": "Affectionate, Curious, Intelligent, Interactive, Lively, Playful, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Distinguished by truly unique ears that curl back in a graceful arc, offering an alert, perky, happily surprised expression, they cause people to break out into a big smile when viewing their first Curl. Curls are very people-oriented, faithful, affectionate soulmates, adjusting remarkably fast to other pets, children, and new situations.", + "life_span": "12 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 2, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/American_Curl", + "hypoallergenic": 0, + "reference_image_id": "xnsqonbjW" + }, + { + "weight": { + "imperial": "8 - 15", + "metric": "4 - 7" + }, + "id": "asho", + "name": "American Shorthair", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/AmericanShorthair.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/american-shorthair", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/american-shorthair", + "temperament": "Active, Curious, Easy Going, Playful, Calm", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The American Shorthair is known for its longevity, robust health, good looks, sweet personality, and amiability with children, dogs, and other pets.", + "life_span": "15 - 17", + "indoor": 0, + "lap": 1, + "alt_names": "Domestic Shorthair", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 1, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/American_Shorthair", + "hypoallergenic": 0, + "reference_image_id": "JFPROfGtQ" + }, + { + "weight": { + "imperial": "8 - 15", + "metric": "4 - 7" + }, + "id": "awir", + "name": "American Wirehair", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/AmericanWirehair.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/american-wirehair", + "temperament": "Affectionate, Curious, Gentle, Intelligent, Interactive, Lively, Loyal, Playful, Sensible, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The American Wirehair tends to be a calm and tolerant cat who takes life as it comes. His favorite hobby is bird-watching from a sunny windowsill, and his hunting ability will stand you in good stead if insects enter the house.", + "life_span": "14 - 18", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 1, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/American_Wirehair", + "hypoallergenic": 0, + "reference_image_id": "8D--jCd21" + }, + { + "weight": { + "imperial": "8 - 16", + "metric": "4 - 7" + }, + "id": "amau", + "name": "Arabian Mau", + "vcahospitals_url": "", + "temperament": "Affectionate, Agile, Curious, Independent, Playful, Loyal", + "origin": "United Arab Emirates", + "country_codes": "AE", + "country_code": "AE", + "description": "Arabian Mau cats are social and energetic. Due to their energy levels, these cats do best in homes where their owners will be able to provide them with plenty of playtime, attention and interaction from their owners. These kitties are friendly, intelligent, and adaptable, and will even get along well with other pets and children.", + "life_span": "12 - 14", + "indoor": 0, + "alt_names": "Alley cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 1, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Arabian_Mau", + "hypoallergenic": 0, + "reference_image_id": "k71ULYfRr" + }, + { + "weight": { + "imperial": "7 - 15", + "metric": "3 - 7" + }, + "id": "amis", + "name": "Australian Mist", + "temperament": "Lively, Social, Fun-loving, Relaxed, Affectionate", + "origin": "Australia", + "country_codes": "AU", + "country_code": "AU", + "description": "The Australian Mist thrives on human companionship. Tolerant of even the youngest of children, these friendly felines enjoy playing games and being part of the hustle and bustle of a busy household. They make entertaining companions for people of all ages, and are happy to remain indoors between dusk and dawn or to be wholly indoor pets.", + "life_span": "12 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "Spotted Mist", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 3, + "health_issues": 1, + "intelligence": 4, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Australian_Mist", + "hypoallergenic": 0, + "reference_image_id": "_6x-3TiCA" + }, + { + "weight": { + "imperial": "4 - 10", + "metric": "2 - 5" + }, + "id": "bali", + "name": "Balinese", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/Balinese.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/balinese", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/balinese", + "temperament": "Affectionate, Intelligent, Playful", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Balinese are curious, outgoing, intelligent cats with excellent communication skills. They are known for their chatty personalities and are always eager to tell you their views on life, love, and what you’ve served them for dinner. ", + "life_span": "10 - 15", + "indoor": 0, + "alt_names": "Long-haired Siamese", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 3, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Balinese_(cat)", + "hypoallergenic": 1, + "reference_image_id": "13MkvUreZ" + }, + { + "weight": { + "imperial": "4 - 9", + "metric": "2 - 4" + }, + "id": "bamb", + "name": "Bambino", + "temperament": "Affectionate, Lively, Friendly, Intelligent", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Bambino is a breed of cat that was created as a cross between the Sphynx and the Munchkin breeds. The Bambino cat has short legs, large upright ears, and is usually hairless. They love to be handled and cuddled up on the laps of their family members.", + "life_span": "12 - 14", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 1, + "hairless": 1, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 1, + "wikipedia_url": "https://en.wikipedia.org/wiki/Bambino_cat", + "hypoallergenic": 0, + "reference_image_id": "5AdhMjeEu" + }, + { + "weight": { + "imperial": "6 - 12", + "metric": "3 - 7" + }, + "id": "beng", + "name": "Bengal", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/Bengal.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/bengal", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/bengal", + "temperament": "Alert, Agile, Energetic, Demanding, Intelligent", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Bengals are a lot of fun to live with, but they're definitely not the cat for everyone, or for first-time cat owners. Extremely intelligent, curious and active, they demand a lot of interaction and woe betide the owner who doesn't provide it.", + "life_span": "12 - 15", + "indoor": 0, + "lap": 0, + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "cat_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 5, + "bidability": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Bengal_(cat)", + "hypoallergenic": 1, + "reference_image_id": "O3btzLlsO" + }, + { + "weight": { + "imperial": "6 - 15", + "metric": "3 - 7" + }, + "id": "birm", + "name": "Birman", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/Birman.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/birman", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/birman", + "temperament": "Affectionate, Active, Gentle, Social", + "origin": "France", + "country_codes": "FR", + "country_code": "FR", + "description": "The Birman is a docile, quiet cat who loves people and will follow them from room to room. Expect the Birman to want to be involved in what you’re doing. He communicates in a soft voice, mainly to remind you that perhaps it’s time for dinner or maybe for a nice cuddle on the sofa. He enjoys being held and will relax in your arms like a furry baby.", + "life_span": "14 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Sacred Birman, Sacred Cat Of Burma", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 2, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Birman", + "hypoallergenic": 0, + "reference_image_id": "HOrX5gwLS" + }, + { + "weight": { + "imperial": "6 - 11", + "metric": "3 - 5" + }, + "id": "bomb", + "name": "Bombay", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/Bombay.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/bombay", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/bombay", + "temperament": "Affectionate, Dependent, Gentle, Intelligent, Playful", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The the golden eyes and the shiny black coa of the Bopmbay is absolutely striking. Likely to bond most with one family member, the Bombay will follow you from room to room and will almost always have something to say about what you are doing, loving attention and to be carried around, often on his caregiver's shoulder.", + "life_span": "12 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "Small black Panther", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Bombay_(cat)", + "hypoallergenic": 0, + "reference_image_id": "5iYq9NmT1" + }, + { + "weight": { + "imperial": "8 - 18", + "metric": "4 - 8" + }, + "id": "bslo", + "name": "British Longhair", + "temperament": "Affectionate, Easy Going, Independent, Intelligent, Loyal, Social", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "The British Longhair is a very laid-back relaxed cat, often perceived to be very independent although they will enjoy the company of an equally relaxed and likeminded cat. They are an affectionate breed, but very much on their own terms and tend to prefer to choose to come and sit with their owners rather than being picked up.", + "life_span": "12 - 14", + "indoor": 0, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 5, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 4, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/British_Longhair", + "hypoallergenic": 0, + "reference_image_id": "7isAO4Cav" + }, + { + "weight": { + "imperial": "12 - 20", + "metric": "5 - 9" + }, + "id": "bsho", + "name": "British Shorthair", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/BritishShorthair.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/british-shorthair", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/british-shorthair", + "temperament": "Affectionate, Easy Going, Gentle, Loyal, Patient, calm", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "The British Shorthair is a very pleasant cat to have as a companion, ans is easy going and placid. The British is a fiercely loyal, loving cat and will attach herself to every one of her family members. While loving to play, she doesn't need hourly attention. If she is in the mood to play, she will find someone and bring a toy to that person. The British also plays well by herself, and thus is a good companion for single people.", + "life_span": "12 - 17", + "indoor": 0, + "lap": 1, + "alt_names": "Highlander, Highland Straight, Britannica", + "adaptability": 5, + "affection_level": 4, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 2, + "grooming": 2, + "health_issues": 2, + "intelligence": 3, + "shedding_level": 4, + "social_needs": 3, + "stranger_friendly": 2, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/British_Shorthair", + "hypoallergenic": 0, + "reference_image_id": "s4wQfYoEk" + }, + { + "weight": { + "imperial": "6 - 12", + "metric": "3 - 5" + }, + "id": "bure", + "name": "Burmese", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/Burmese.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/burmese", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/burmese", + "temperament": "Curious, Intelligent, Gentle, Social, Interactive, Playful, Lively", + "origin": "Burma", + "country_codes": "MM", + "country_code": "MM", + "description": "Burmese love being with people, playing with them, and keeping them entertained. They crave close physical contact and abhor an empty lap. They will follow their humans from room to room, and sleep in bed with them, preferably under the covers, cuddled as close as possible. At play, they will turn around to see if their human is watching and being entertained by their crazy antics.", + "life_span": "15 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Burmese_(cat)", + "hypoallergenic": 1, + "reference_image_id": "4lXnnfxac" + }, + { + "weight": { + "imperial": "6 - 13", + "metric": "3 - 6" + }, + "id": "buri", + "name": "Burmilla", + "cfa_url": "http://cfa.org/Breeds/BreedsAB/Burmilla.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/burmilla", + "temperament": "Easy Going, Friendly, Intelligent, Lively, Playful, Social", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "The Burmilla is a fairly placid cat. She tends to be an easy cat to get along with, requiring minimal care. The Burmilla is affectionate and sweet and makes a good companion, the Burmilla is an ideal companion to while away a lonely evening. Loyal, devoted, and affectionate, this cat will stay by its owner, always keeping them company.", + "life_span": "10 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 4, + "energy_level": 3, + "grooming": 3, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 3, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Burmilla", + "hypoallergenic": 0, + "reference_image_id": "jvg3XfEdC" + }, + { + "weight": { + "imperial": "10 - 15", + "metric": "5 - 7" + }, + "id": "cspa", + "name": "California Spangled", + "temperament": "Affectionate, Curious, Intelligent, Loyal, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Perhaps the only thing about the California spangled cat that isn’t wild-like is its personality. Known to be affectionate, gentle and sociable, this breed enjoys spending a great deal of time with its owners. They are very playful, often choosing to perch in high locations and show off their acrobatic skills.", + "life_span": "10 - 14", + "indoor": 0, + "alt_names": "Spangle", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 4, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/California_Spangled", + "hypoallergenic": 0, + "reference_image_id": "B1ERTmgph" + }, + { + "weight": { + "imperial": "7 - 12", + "metric": "3 - 5" + }, + "id": "ctif", + "name": "Chantilly-Tiffany", + "temperament": "Affectionate, Demanding, Interactive, Loyal", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Chantilly is a devoted companion and prefers company to being left alone. While the Chantilly is not demanding, she will \"chirp\" and \"talk\" as if having a conversation. This breed is affectionate, with a sweet temperament. It can stay still for extended periods, happily lounging in the lap of its loved one. This quality makes the Tiffany an ideal traveling companion, and an ideal house companion for senior citizens and the physically handicapped.", + "life_span": "14 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "Chantilly, Foreign Longhair", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 5, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 5, + "social_needs": 3, + "stranger_friendly": 4, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Chantilly-Tiffany", + "hypoallergenic": 0, + "reference_image_id": "TR-5nAd_S" + }, + { + "weight": { + "imperial": "6 - 15", + "metric": "3 - 7" + }, + "id": "char", + "name": "Chartreux", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/Chartreux.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/chartreux", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/chartreux", + "temperament": "Affectionate, Loyal, Intelligent, Social, Lively, Playful", + "origin": "France", + "country_codes": "FR", + "country_code": "FR", + "description": "The Chartreux is generally silent but communicative. Short play sessions, mixed with naps and meals are their perfect day. Whilst appreciating any attention you give them, they are not demanding, content instead to follow you around devotedly, sleep on your bed and snuggle with you if you’re not feeling well.", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 2, + "grooming": 1, + "health_issues": 2, + "intelligence": 4, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 1, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Chartreux", + "hypoallergenic": 1, + "reference_image_id": "j6oFGLpRG" + }, + { + "weight": { + "imperial": "7 - 15", + "metric": "3 - 7" + }, + "id": "chau", + "name": "Chausie", + "temperament": "Affectionate, Intelligent, Playful, Social", + "origin": "Egypt", + "country_codes": "EG", + "country_code": "EG", + "description": "For those owners who desire a feline capable of evoking the great outdoors, the strikingly beautiful Chausie retains a bit of the wild in its appearance but has the house manners of our friendly, familiar moggies. Very playful, this cat needs a large amount of space to be able to fully embrace its hunting instincts.", + "life_span": "12 - 14", + "indoor": 0, + "alt_names": "Nile Cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 3, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 4, + "vocalisation": 1, + "experimental": 1, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Chausie", + "hypoallergenic": 0, + "reference_image_id": "vJ3lEYgXr" + }, + { + "weight": { + "imperial": "8 - 15", + "metric": "4 - 7" + }, + "id": "chee", + "name": "Cheetoh", + "temperament": "Affectionate, Gentle, Intelligent, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Cheetoh has a super affectionate nature and real love for their human companions; they are intelligent with the ability to learn quickly. You can expect that a Cheetoh will be a fun-loving kitty who enjoys playing, running, and jumping through every room in your house.", + "life_span": "12 - 14", + "indoor": 0, + "alt_names": " ", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 4, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Bengal_cat#Cheetoh", + "hypoallergenic": 0, + "reference_image_id": "IFXsxmXLm" + }, + { + "weight": { + "imperial": "4 - 10", + "metric": "2 - 5" + }, + "id": "csho", + "name": "Colorpoint Shorthair", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/ColorpointShorthair.aspx", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/colorpoint-shorthair", + "temperament": "Affectionate, Intelligent, Playful, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Colorpoint Shorthairs are an affectionate breed, devoted and loyal to their people. Sensitive to their owner’s moods, Colorpoints are more than happy to sit at your side or on your lap and purr words of encouragement on a bad day. They will constantly seek out your lap whenever it is open and in the moments when your lap is preoccupied they will stretch out in sunny spots on the ground.", + "life_span": "12 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 3, + "affection_level": 4, + "child_friendly": 4, + "cat_friendly": 3, + "dog_friendly": 4, + "energy_level": 4, + "grooming": 2, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 2, + "vocalisation": 5, + "bidability": 4, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Colorpoint_Shorthair", + "hypoallergenic": 0, + "reference_image_id": "oSpqGyUDS" + }, + { + "weight": { + "imperial": "5 - 9", + "metric": "2 - 4" + }, + "id": "crex", + "name": "Cornish Rex", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/CornishRex.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/cornish-rex", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/cornish-rex", + "temperament": "Affectionate, Intelligent, Active, Curious, Playful", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "This is a confident cat who loves people and will follow them around, waiting for any opportunity to sit in a lap or give a kiss. He enjoys being handled, making it easy to take him to the veterinarian or train him for therapy work. The Cornish Rex stay in kitten mode most of their lives and well into their senior years. ", + "life_span": "11 - 14", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "cat_friendly": 2, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 1, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 1, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Cornish_Rex", + "hypoallergenic": 1, + "reference_image_id": "unX21IBVB" + }, + { + "weight": { + "imperial": "8 - 13", + "metric": "4 - 6" + }, + "id": "cymr", + "name": "Cymric", + "vetstreet_url": "http://www.vetstreet.com/cats/cymric", + "temperament": "Gentle, Loyal, Intelligent, Playful", + "origin": "Canada", + "country_codes": "CA", + "country_code": "CA", + "description": "The Cymric is a placid, sweet cat. They do not get too upset about anything that happens in their world. They are loving companions and adore people. They are smart and dexterous, capable of using his paws to get into cabinets or to open doors.", + "life_span": "8 - 14", + "indoor": 0, + "lap": 1, + "alt_names": "Spangle", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 3, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 5, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 1, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Cymric_(cat)", + "hypoallergenic": 0, + "reference_image_id": "3dbtapCWM" + }, + { + "weight": { + "imperial": "8 - 16", + "metric": "4 - 7" + }, + "id": "cypr", + "name": "Cyprus", + "temperament": "Affectionate, Social", + "origin": "Cyprus", + "country_codes": "CY", + "country_code": "CY", + "description": "Loving, loyal, social and inquisitive, the Cyprus cat forms strong ties with their families and love nothing more than to be involved in everything that goes on in their surroundings. They are not overly active by nature which makes them the perfect companion for people who would like to share their homes with a laid-back relaxed feline companion. ", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Cypriot cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 3, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 4, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Cyprus_cat", + "hypoallergenic": 0, + "reference_image_id": "tJbzb7FKo" + }, + { + "weight": { + "imperial": "5 - 10", + "metric": "2 - 5" + }, + "id": "drex", + "name": "Devon Rex", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/DevonRex.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/devon-rex", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/devon-rex", + "temperament": "Highly interactive, Mischievous, Loyal, Social, Playful", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "The favourite perch of the Devon Rex is right at head level, on the shoulder of her favorite person. She takes a lively interest in everything that is going on and refuses to be left out of any activity. Count on her to stay as close to you as possible, occasionally communicating his opinions in a quiet voice. She loves people and welcomes the attentions of friends and family alike.", + "life_span": "10 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Pixie cat, Alien cat, Poodle cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 1, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 1, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Devon_Rex", + "hypoallergenic": 1, + "reference_image_id": "4RzEwvyzz" + }, + { + "weight": { + "imperial": "10 - 12", + "metric": "5 - 6" + }, + "id": "dons", + "name": "Donskoy", + "temperament": "Playful, affectionate, loyal, social", + "origin": "Russia", + "country_codes": "RU", + "country_code": "RU", + "description": "Donskoy are affectionate, intelligent, and easy-going. They demand lots of attention and interaction. The Donskoy also gets along well with other pets. It is now thought the same gene that causes degrees of hairlessness in the Donskoy also causes alterations in cat personality, making them calmer the less hair they have.", + "life_span": "12 - 15", + "indoor": 0, + "adaptability": 4, + "affection_level": 4, + "child_friendly": 3, + "cat_friendly": 3, + "dog_friendly": 3, + "energy_level": 4, + "grooming": 2, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 1, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 2, + "experimental": 0, + "hairless": 1, + "natural": 0, + "rare": 1, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Donskoy_(cat)", + "hypoallergenic": 0, + "reference_image_id": "3KG57GfMW" + }, + { + "weight": { + "imperial": "9 - 12", + "metric": "4 - 6" + }, + "id": "lihu", + "name": "Dragon Li", + "vetstreet_url": "http://www.vetstreet.com/cats/li-hua", + "temperament": "Intelligent, Friendly, Gentle, Loving, Loyal", + "origin": "China", + "country_codes": "CN", + "country_code": "CN", + "description": "The Dragon Li is loyal, but not particularly affectionate. They are known to be very intelligent, and their natural breed status means that they're very active. She is is gentle with people, and has a reputation as a talented hunter of rats and other vermin.", + "life_span": "12 - 15", + "indoor": 1, + "alt_names": "Chinese Lia Hua, Lí hua māo (貍花貓), Li Hua", + "adaptability": 3, + "affection_level": 3, + "child_friendly": 3, + "cat_friendly": 3, + "dog_friendly": 3, + "energy_level": 3, + "grooming": 1, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Dragon_Li", + "hypoallergenic": 0, + "reference_image_id": "BQMSld0A0" + }, + { + "weight": { + "imperial": "6 - 14", + "metric": "3 - 6" + }, + "id": "emau", + "name": "Egyptian Mau", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/EgyptianMau.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/egyptian-mau", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/egyptian-mau", + "temperament": "Agile, Dependent, Gentle, Intelligent, Lively, Loyal, Playful", + "origin": "Egypt", + "country_codes": "EG", + "country_code": "EG", + "description": "The Egyptian Mau is gentle and reserved. She loves her people and desires attention and affection from them but is wary of others. Early, continuing socialization is essential with this sensitive and sometimes shy cat, especially if you plan to show or travel with her. Otherwise, she can be easily startled by unexpected noises or events.", + "life_span": "18 - 20", + "indoor": 0, + "lap": 1, + "alt_names": "Pharaoh Cat", + "adaptability": 2, + "affection_level": 5, + "child_friendly": 3, + "dog_friendly": 3, + "energy_level": 5, + "grooming": 1, + "health_issues": 3, + "intelligence": 4, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 2, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Egyptian_Mau", + "hypoallergenic": 0, + "reference_image_id": "TuSyTkt2n" + }, + { + "weight": { + "imperial": "7 - 14", + "metric": "3 - 6" + }, + "id": "ebur", + "name": "European Burmese", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/EuropeanBurmese.aspx", + "temperament": "Sweet, Affectionate, Loyal", + "origin": "Burma", + "country_codes": "MM", + "country_code": "MM", + "description": "The European Burmese is a very affectionate, intelligent, and loyal cat. They thrive on companionship and will want to be with you, participating in everything you do. While they might pick a favorite family member, chances are that they will interact with everyone in the home, as well as any visitors that come to call. They are inquisitive and playful, even as adults. ", + "life_span": "10 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "cat_friendly": 4, + "dog_friendly": 4, + "energy_level": 4, + "grooming": 1, + "health_issues": 4, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 4, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "hypoallergenic": 0 + }, + { + "weight": { + "imperial": "7 - 14", + "metric": "3 - 6" + }, + "id": "esho", + "name": "Exotic Shorthair", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/Exotic.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/exotic-shorthair", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/exotic-shorthair", + "temperament": "Affectionate, Sweet, Loyal, Quiet, Peaceful", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Exotic Shorthair is a gentle friendly cat that has the same personality as the Persian. They love having fun, don’t mind the company of other cats and dogs, also love to curl up for a sleep in a safe place. Exotics love their own people, but around strangers they are cautious at first. Given time, they usually warm up to visitors.", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Exotic", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 3, + "dog_friendly": 3, + "energy_level": 3, + "grooming": 2, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 2, + "social_needs": 4, + "stranger_friendly": 2, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Exotic_Shorthair", + "hypoallergenic": 0, + "reference_image_id": "YnPrYEmfe" + }, + { + "weight": { + "imperial": "6 - 10", + "metric": "3 - 5" + }, + "id": "hbro", + "name": "Havana Brown", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/HavanaBrown.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/havana-brown", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/havana-brown", + "temperament": "Affectionate, Curious, Demanding, Friendly, Intelligent, Playful", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "The Havana Brown is human oriented, playful, and curious. She has a strong desire to spend time with her people and involve herself in everything they do. Being naturally inquisitive, the Havana Brown reaches out with a paw to touch and feel when investigating curiosities in its environment. They are truly sensitive by nature and frequently gently touch their human companions as if they are extending a paw of friendship.", + "life_span": "10 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Havana, HB", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Havana_Brown", + "hypoallergenic": 0, + "reference_image_id": "njK25knLH" + }, + { + "weight": { + "imperial": "7 - 14", + "metric": "3 - 6" + }, + "id": "hima", + "name": "Himalayan", + "vetstreet_url": "http://www.vetstreet.com/cats/himalayan", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/himalayan", + "temperament": "Dependent, Gentle, Intelligent, Quiet, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Calm and devoted, Himalayans make excellent companions, though they prefer a quieter home. They are playful in a sedate kind of way and enjoy having an assortment of toys. The Himalayan will stretch out next to you, sleep in your bed and even sit on your lap when she is in the mood.", + "life_span": "9 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Himalayan Persian, Colourpoint Persian, Longhaired Colourpoint, Himmy", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 2, + "dog_friendly": 2, + "energy_level": 1, + "grooming": 5, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 4, + "social_needs": 4, + "stranger_friendly": 2, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Himalayan_(cat)", + "hypoallergenic": 0, + "reference_image_id": "CDhOtM-Ig" + }, + { + "weight": { + "imperial": "5 - 10", + "metric": "2 - 5" + }, + "id": "jbob", + "name": "Japanese Bobtail", + "cfa_url": "http://cfa.org/Breeds/BreedsCJ/JapaneseBobtail.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/japanese-bobtail", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/japanese-bobtail", + "temperament": "Active, Agile, Clever, Easy Going, Intelligent, Lively, Loyal, Playful, Social", + "origin": "Japan", + "country_codes": "JP", + "country_code": "JP", + "description": "The Japanese Bobtail is an active, sweet, loving and highly intelligent breed. They love to be with people and play seemingly endlessly. They learn their name and respond to it. They bring toys to people and play fetch with a favorite toy for hours. Bobtails are social and are at their best when in the company of people. They take over the house and are not intimidated. If a dog is in the house, Bobtails assume Bobtails are in charge.", + "life_span": "14 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "Japanese Truncated Cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 1, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Japanese_Bobtail", + "hypoallergenic": 0, + "reference_image_id": "-tm9-znzl" + }, + { + "weight": { + "imperial": "5 - 10", + "metric": "2 - 5" + }, + "id": "java", + "name": "Javanese", + "vetstreet_url": "http://www.vetstreet.com/cats/javanese", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/javanese", + "temperament": "Active, Devoted, Intelligent, Playful", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Javanese are endlessly interested, intelligent and active. They tend to enjoy jumping to great heights, playing with fishing pole-type or other interactive toys and just generally investigating their surroundings. He will attempt to copy things you do, such as opening doors or drawers.", + "life_span": "10 - 12", + "indoor": 0, + "alt_names": " ", + "adaptability": 4, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 4, + "energy_level": 5, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 2, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Javanese_cat", + "hypoallergenic": 1, + "reference_image_id": "xoI_EpOKe" + }, + { + "weight": { + "imperial": "8 - 12", + "metric": "4 - 6" + }, + "id": "khao", + "name": "Khao Manee", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/KhaoManee.aspx", + "temperament": "Calm, Relaxed, Talkative, Playful, Warm", + "origin": "Thailand", + "country_codes": "TH", + "country_code": "TH", + "description": "The Khao Manee is highly intelligent, with an extrovert and inquisitive nature, however they are also very calm and relaxed, making them an idea lap cat.", + "life_span": "10 - 12", + "indoor": 0, + "lap": 1, + "alt_names": "Diamond Eye cat", + "adaptability": 4, + "affection_level": 4, + "child_friendly": 3, + "cat_friendly": 3, + "dog_friendly": 3, + "energy_level": 3, + "grooming": 3, + "health_issues": 1, + "intelligence": 4, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Khao_Manee", + "hypoallergenic": 0, + "reference_image_id": "165ok6ESN" + }, + { + "weight": { + "imperial": "7 - 11", + "metric": "3 - 5" + }, + "id": "kora", + "name": "Korat", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/Korat.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/korat", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/korat", + "temperament": "Active, Loyal, highly intelligent, Expressive, Trainable", + "origin": "Thailand", + "country_codes": "TH", + "country_code": "TH", + "description": "The Korat is a natural breed, and one of the oldest stable cat breeds. They are highly intelligent and confident cats that can be fearless, although they are startled by loud sounds and sudden movements. Korats form strong bonds with their people and like to cuddle and stay nearby.", + "life_span": "10 - 15", + "indoor": 0, + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 2, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 1, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Korat", + "hypoallergenic": 0, + "reference_image_id": "DbwiefiaY" + }, + { + "weight": { + "imperial": "8 - 15", + "metric": "4 - 7" + }, + "id": "kuri", + "name": "Kurilian", + "vetstreet_url": "http://www.vetstreet.com/cats/kurilian-bobtail", + "temperament": "Independent, highly intelligent, clever, inquisitive, sociable, playful, trainable", + "origin": "Russia", + "country_codes": "RU", + "country_code": "RU", + "description": "The character of the Kurilian Bobtail is independent, highly intelligent, clever, inquisitive, sociable, playful, trainable, absent of aggression and very gentle. They are devoted to their humans and when allowed are either on the lap of or sleeping in bed with their owners.", + "life_span": "15 - 20", + "indoor": 0, + "adaptability": 5, + "affection_level": 5, + "child_friendly": 5, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 2, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 1, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Kurilian_Bobtail", + "hypoallergenic": 0, + "reference_image_id": "NZpO4pU56M" + }, + { + "weight": { + "imperial": "6 - 10", + "metric": "3 - 5" + }, + "id": "lape", + "name": "LaPerm", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/LaPerm.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/laperm", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/laperm", + "temperament": "Affectionate, Friendly, Gentle, Intelligent, Playful, Quiet", + "origin": "Thailand", + "country_codes": "TH", + "country_code": "TH", + "description": "LaPerms are gentle and affectionate but also very active. Unlike many active breeds, the LaPerm is also quite content to be a lap cat. The LaPerm will often follow your lead; that is, if they are busy playing and you decide to sit and relax, simply pick up your LaPerm and sit down with it, and it will stay in your lap, devouring the attention you give it.", + "life_span": "10 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Si-Sawat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 1, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/LaPerm", + "hypoallergenic": 1, + "reference_image_id": "aKbsEYjSl" + }, + { + "weight": { + "imperial": "12 - 18", + "metric": "5 - 8" + }, + "id": "mcoo", + "name": "Maine Coon", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/MaineCoon.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/maine-coon", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/maine-coon", + "temperament": "Adaptable, Intelligent, Loving, Gentle, Independent", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "They are known for their size and luxurious long coat Maine Coons are considered a gentle giant. The good-natured and affable Maine Coon adapts well to many lifestyles and personalities. She likes being with people and has the habit of following them around, but isn’t needy. Most Maine Coons love water and they can be quite good swimmers.", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Coon Cat, Maine Cat, Maine Shag, Snowshoe Cat, American Longhair, The Gentle Giants", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 3, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Maine_Coon", + "hypoallergenic": 0, + "reference_image_id": "OOD3VXAQn" + }, + { + "weight": { + "imperial": "6 - 13", + "metric": "3 - 6" + }, + "id": "mala", + "name": "Malayan", + "temperament": "Affectionate, Interactive, Playful, Social", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "Malayans love to explore and even enjoy traveling by way of a cat carrier. They are quite a talkative and rather loud cat with an apparent strong will. These cats will make sure that you give it the attention it seeks and always seem to want to be held and hugged. They will constantly interact with people, even strangers. They love to play and cuddle.", + "life_span": "12 - 18", + "indoor": 0, + "alt_names": "Asian", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Asian_cat", + "hypoallergenic": 0 + }, + { + "weight": { + "imperial": "7 - 13", + "metric": "3 - 6" + }, + "id": "manx", + "name": "Manx", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/Manx.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/manx", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/manx", + "temperament": "Easy Going, Intelligent, Loyal, Playful, Social", + "origin": "Isle of Man", + "country_codes": "IM", + "country_code": "IM", + "description": "The Manx is a placid, sweet cat that is gentle and playful. She never seems to get too upset about anything. She is a loving companion and adores being with people.", + "life_span": "12 - 14", + "indoor": 0, + "lap": 1, + "alt_names": "Manks, Stubbin, Rumpy", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 5, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 1, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Manx_(cat)", + "hypoallergenic": 0, + "reference_image_id": "fhYh2PDcC" + }, + { + "weight": { + "imperial": "5 - 9", + "metric": "2 - 4" + }, + "id": "munc", + "name": "Munchkin", + "vetstreet_url": "http://www.vetstreet.com/cats/munchkin", + "temperament": "Agile, Easy Going, Intelligent, Playful", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Munchkin is an outgoing cat who enjoys being handled. She has lots of energy and is faster and more agile than she looks. The shortness of their legs does not seem to interfere with their running and leaping abilities.", + "life_span": "10 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 2, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 1, + "wikipedia_url": "https://en.wikipedia.org/wiki/Munchkin_(cat)", + "hypoallergenic": 0, + "reference_image_id": "j5cVSqLer" + }, + { + "weight": { + "imperial": "7 - 11", + "metric": "3 - 5" + }, + "id": "nebe", + "name": "Nebelung", + "temperament": "Gentle, Quiet, Shy, Playful", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Nebelung may have a reserved nature, but she loves to play (being especially fond of retrieving) and enjoys jumping or climbing to high places where she can study people and situations at her leisure before making up her mind about whether she wants to get involved.", + "life_span": "11 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "Longhaired Russian Blue", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 4, + "energy_level": 3, + "grooming": 3, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 1, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Nebelung", + "hypoallergenic": 0, + "reference_image_id": "OGTWqNNOt" + }, + { + "weight": { + "imperial": "8 - 16", + "metric": "4 - 7" + }, + "id": "norw", + "name": "Norwegian Forest Cat", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/NorwegianForestCat.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/norwegian-forest-cat", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/norwegian-forest-cat", + "temperament": "Sweet, Active, Intelligent, Social, Playful, Lively, Curious", + "origin": "Norway", + "country_codes": "NO", + "country_code": "NO", + "description": "The Norwegian Forest Cat is a sweet, loving cat. She appreciates praise and loves to interact with her parent. She makes a loving companion and bonds with her parents once she accepts them for her own. She is still a hunter at heart. She loves to chase toys as if they are real. She is territorial and patrols several times each day to make certain that all is fine.", + "life_span": "12 - 16", + "indoor": 0, + "alt_names": "Skogkatt / Skaukatt, Norsk Skogkatt / Norsk Skaukatt, Weegie", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 2, + "health_issues": 3, + "intelligence": 4, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Norwegian_Forest_Cat", + "hypoallergenic": 0, + "reference_image_id": "06dgGmEOV" + }, + { + "weight": { + "imperial": "7 - 15", + "metric": "3 - 7" + }, + "id": "ocic", + "name": "Ocicat", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/Ocicat.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/ocicat", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/ocicat", + "temperament": "Active, Agile, Curious, Demanding, Friendly, Gentle, Lively, Playful, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Loyal and devoted to their owners, the Ocicat is intelligent, confident, outgoing, and seems to have many dog traits. They can be trained to fetch toys, walk on a lead, taught to 'speak', come when called, and follow other commands. ", + "life_span": "12 - 14", + "indoor": 0, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Ocicat", + "hypoallergenic": 1, + "reference_image_id": "JAx-08Y0n" + }, + { + "weight": { + "imperial": "5 - 10", + "metric": "2 - 5" + }, + "id": "orie", + "name": "Oriental", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/Oriental.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/oriental", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/oriental", + "temperament": "Energetic, Affectionate, Intelligent, Social, Playful, Curious", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Orientals are passionate about the people in their lives. They become extremely attached to their humans, so be prepared for a lifetime commitment. When you are not available to entertain her, an Oriental will divert herself by jumping on top of the refrigerator, opening drawers, seeking out new hideaways.", + "life_span": "12 - 14", + "indoor": 0, + "lap": 1, + "alt_names": "Foreign Type", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Oriental_Shorthair", + "hypoallergenic": 1, + "reference_image_id": "LutjkZJpH" + }, + { + "weight": { + "imperial": "9 - 14", + "metric": "4 - 6" + }, + "id": "pers", + "name": "Persian", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/Persian.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/persian", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/persian", + "temperament": "Affectionate, loyal, Sedate, Quiet", + "origin": "Iran (Persia)", + "country_codes": "IR", + "country_code": "IR", + "description": "Persians are sweet, gentle cats that can be playful or quiet and laid-back. Great with families and children, they absolutely love to lounge around the house. While they don’t mind a full house or active kids, they’ll usually hide when they need some alone time.", + "life_span": "14 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Longhair, Persian Longhair, Shiraz, Shirazi", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 2, + "dog_friendly": 2, + "energy_level": 1, + "grooming": 5, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 4, + "social_needs": 4, + "stranger_friendly": 2, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Persian_(cat)", + "hypoallergenic": 0, + "reference_image_id": "-Zfz5z2jK" + }, + { + "weight": { + "imperial": "8 - 17", + "metric": "4 - 8" + }, + "id": "pixi", + "name": "Pixie-bob", + "vetstreet_url": "http://www.vetstreet.com/cats/pixiebob", + "temperament": "Affectionate, Social, Intelligent, Loyal", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Companionable and affectionate, the Pixie-bob wants to be an integral part of the family. The Pixie-Bob’s ability to bond with their humans along with their patient personas make them excellent companions for children.", + "life_span": "13 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 1, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 1, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Pixiebob", + "hypoallergenic": 0, + "reference_image_id": "z7fJRNeN6" + }, + { + "weight": { + "imperial": "8 - 20", + "metric": "4 - 9" + }, + "id": "raga", + "name": "Ragamuffin", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/Ragamuffin.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/ragamuffin", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/ragamuffin", + "temperament": "Affectionate, Friendly, Gentle, Calm", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Ragamuffin is calm, even tempered and gets along well with all family members. Changes in routine generally do not upset her. She is an ideal companion for those in apartments, and with children due to her patient nature.", + "life_span": "12 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 3, + "health_issues": 3, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Ragamuffin_cat", + "hypoallergenic": 0, + "reference_image_id": "SMuZx-bFM" + }, + { + "weight": { + "imperial": "12 - 20", + "metric": "5 - 9" + }, + "id": "ragd", + "name": "Ragdoll", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/Ragdoll.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/ragdoll", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/ragdoll", + "temperament": "Affectionate, Friendly, Gentle, Quiet, Easygoing", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Ragdolls love their people, greeting them at the door, following them around the house, and leaping into a lap or snuggling in bed whenever given the chance. They are the epitome of a lap cat, enjoy being carried and collapsing into the arms of anyone who holds them.", + "life_span": "12 - 17", + "indoor": 0, + "lap": 1, + "alt_names": "Rag doll", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 2, + "health_issues": 3, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Ragdoll", + "hypoallergenic": 0, + "reference_image_id": "oGefY4YoG" + }, + { + "weight": { + "imperial": "5 - 11", + "metric": "2 - 5" + }, + "id": "rblu", + "name": "Russian Blue", + "cfa_url": "http://cfa.org/Breeds/BreedsKthruR/RussianBlue.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/russian-blue-nebelung", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/russian-blue", + "temperament": "Active, Dependent, Easy Going, Gentle, Intelligent, Loyal, Playful, Quiet", + "origin": "Russia", + "country_codes": "RU", + "country_code": "RU", + "description": "Russian Blues are very loving and reserved. They do not like noisy households but they do like to play and can be quite active when outdoors. They bond very closely with their owner and are known to be compatible with other pets.", + "life_span": "10 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "Archangel Blue, Archangel Cat", + "adaptability": 3, + "affection_level": 3, + "child_friendly": 3, + "dog_friendly": 3, + "energy_level": 3, + "grooming": 3, + "health_issues": 1, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 1, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Russian_Blue", + "hypoallergenic": 1, + "reference_image_id": "Rhj-JsTLP" + }, + { + "weight": { + "imperial": "8 - 25", + "metric": "4 - 11" + }, + "id": "sava", + "name": "Savannah", + "vetstreet_url": "http://www.vetstreet.com/cats/savannah", + "temperament": "Curious, Social, Intelligent, Loyal, Outgoing, Adventurous, Affectionate", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "Savannah is the feline version of a dog. Actively seeking social interaction, they are given to pouting if left out. Remaining kitten-like through life. Profoundly loyal to immediate family members whilst questioning the presence of strangers. Making excellent companions that are loyal, intelligent and eager to be involved.", + "life_span": "17 - 20", + "indoor": 0, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 1, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Savannah_cat", + "hypoallergenic": 0, + "reference_image_id": "a8nIYvs6S" + }, + { + "weight": { + "imperial": "5 - 11", + "metric": "2 - 5" + }, + "id": "sfol", + "name": "Scottish Fold", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/ScottishFold.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/scottish-fold-highland-fold", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/scottish-fold", + "temperament": "Affectionate, Intelligent, Loyal, Playful, Social, Sweet, Loving", + "origin": "United Kingdom", + "country_codes": "GB", + "country_code": "GB", + "description": "The Scottish Fold is a sweet, charming breed. She is an easy cat to live with and to care for. She is affectionate and is comfortable with all members of her family. Her tail should be handled gently. Folds are known for sleeping on their backs, and for sitting with their legs stretched out and their paws on their belly. This is called the \"Buddha Position\".", + "life_span": "11 - 14", + "indoor": 0, + "alt_names": "Scot Fold", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 1, + "health_issues": 4, + "intelligence": 3, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Scottish_Fold", + "hypoallergenic": 0, + "reference_image_id": "o9t0LDcsa" + }, + { + "weight": { + "imperial": "6 - 16", + "metric": "3 - 7" + }, + "id": "srex", + "name": "Selkirk Rex", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/SelkirkRex.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/selkirk-rex", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/selkirk-rex", + "temperament": "Active, Affectionate, Dependent, Gentle, Patient, Playful, Quiet, Social", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Selkirk Rex is an incredibly patient, loving, and tolerant breed. The Selkirk also has a silly side and is sometimes described as clownish. She loves being a lap cat and will be happy to chat with you in a quiet voice if you talk to her. ", + "life_span": "14 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Shepherd Cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 2, + "health_issues": 4, + "intelligence": 3, + "shedding_level": 1, + "social_needs": 3, + "stranger_friendly": 3, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 1, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Selkirk_Rex", + "hypoallergenic": 1, + "reference_image_id": "II9dOZmrw" + }, + { + "weight": { + "imperial": "8 - 15", + "metric": "4 - 7" + }, + "id": "siam", + "name": "Siamese", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/Siamese.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/siamese", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/siamese", + "temperament": "Active, Agile, Clever, Sociable, Loving, Energetic", + "origin": "Thailand", + "country_codes": "TH", + "country_code": "TH", + "description": "While Siamese cats are extremely fond of their people, they will follow you around and supervise your every move, being talkative and opinionated. They are a demanding and social cat, that do not like being left alone for long periods.", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Siam, Thai Cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 2, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Siamese_(cat)", + "hypoallergenic": 1, + "reference_image_id": "ai6Jps4sx" + }, + { + "weight": { + "imperial": "8 - 16", + "metric": "4 - 7" + }, + "id": "sibe", + "name": "Siberian", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/Siberian.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/siberian", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/siberian", + "temperament": "Curious, Intelligent, Loyal, Sweet, Agile, Playful, Affectionate", + "origin": "Russia", + "country_codes": "RU", + "country_code": "RU", + "description": "The Siberians dog like temperament and affection makes the ideal lap cat and will live quite happily indoors. Very agile and powerful, the Siberian cat can easily leap and reach high places, including the tops of refrigerators and even doors. ", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Moscow Semi-longhair, HairSiberian Forest Cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 2, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 3, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Siberian_(cat)", + "hypoallergenic": 1, + "reference_image_id": "3bkZAjRh1" + }, + { + "weight": { + "imperial": "5 - 8", + "metric": "2 - 4" + }, + "id": "sing", + "name": "Singapura", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/Singapura.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/singapura", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/singapura", + "temperament": "Affectionate, Curious, Easy Going, Intelligent, Interactive, Lively, Loyal", + "origin": "Singapore", + "country_codes": "SP", + "country_code": "SP", + "description": "The Singapura is usually cautious when it comes to meeting new people, but loves attention from his family so much that she sometimes has the reputation of being a pest. This is a highly active, curious and affectionate cat. She may be small, but she knows she’s in charge", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "Drain Cat, Kucinta, Pura", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Singapura_(cat)", + "hypoallergenic": 0, + "reference_image_id": "Qtncp2nRe" + }, + { + "weight": { + "imperial": "7 - 12", + "metric": "3 - 5" + }, + "id": "snow", + "name": "Snowshoe", + "temperament": "Affectionate, Social, Intelligent, Sweet-tempered", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Snowshoe is a vibrant, energetic, affectionate and intelligent cat. They love being around people which makes them ideal for families, and becomes unhappy when left alone for long periods of time. Usually attaching themselves to one person, they do whatever they can to get your attention.", + "life_span": "14 - 19", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 4, + "grooming": 3, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Snowshoe_(cat)", + "hypoallergenic": 0, + "reference_image_id": "MK-sYESvO" + }, + { + "weight": { + "imperial": "6 - 12", + "metric": "3 - 5" + }, + "id": "soma", + "name": "Somali", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/Somali.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/somali", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/somali", + "temperament": "Mischievous, Tenacious, Intelligent, Affectionate, Gentle, Interactive, Loyal", + "origin": "Somalia", + "country_codes": "SO", + "country_code": "SO", + "description": "The Somali lives life to the fullest. He climbs higher, jumps farther, plays harder. Nothing escapes the notice of this highly intelligent and inquisitive cat. Somalis love the company of humans and other animals.", + "life_span": "12 - 16", + "indoor": 0, + "alt_names": "Fox Cat, Long-Haired Abyssinian", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 3, + "dog_friendly": 4, + "energy_level": 5, + "grooming": 3, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 4, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 1, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Somali_(cat)", + "hypoallergenic": 0, + "reference_image_id": "EPF2ejNS0" + }, + { + "weight": { + "imperial": "6 - 12", + "metric": "3 - 5" + }, + "id": "sphy", + "name": "Sphynx", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/Sphynx.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/sphynx", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/sphynx", + "temperament": "Loyal, Inquisitive, Friendly, Quiet, Gentle", + "origin": "Canada", + "country_codes": "CA", + "country_code": "CA", + "description": "The Sphynx is an intelligent, inquisitive, extremely friendly people-oriented breed. Sphynx commonly greet their owners at the front door, with obvious excitement and happiness. She has an unexpected sense of humor that is often at odds with her dour expression.", + "life_span": "12 - 14", + "indoor": 0, + "lap": 1, + "alt_names": "Canadian Hairless, Canadian Sphynx", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 3, + "grooming": 2, + "health_issues": 4, + "intelligence": 5, + "shedding_level": 1, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 5, + "experimental": 0, + "hairless": 1, + "natural": 0, + "rare": 1, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Sphynx_(cat)", + "hypoallergenic": 1, + "reference_image_id": "BDb8ZXb1v" + }, + { + "weight": { + "imperial": "6 - 12", + "metric": "3 - 5" + }, + "id": "tonk", + "name": "Tonkinese", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/Tonkinese.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/tonkinese", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/tonkinese", + "temperament": "Curious, Intelligent, Social, Lively, Outgoing, Playful, Affectionate", + "origin": "Canada", + "country_codes": "CA", + "country_code": "CA", + "description": "Intelligent and generous with their affection, a Tonkinese will supervise all activities with curiosity. Loving, social, active, playful, yet content to be a lap cat", + "life_span": "14 - 16", + "indoor": 0, + "lap": 1, + "alt_names": "Tonk", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Tonkinese_(cat)", + "hypoallergenic": 0, + "reference_image_id": "KBroiVNCM" + }, + { + "weight": { + "imperial": "7 - 15", + "metric": "3 - 7" + }, + "id": "toyg", + "name": "Toyger", + "vetstreet_url": "http://www.vetstreet.com/cats/toyger", + "temperament": "Playful, Social, Intelligent", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "The Toyger has a sweet, calm personality and is generally friendly. He's outgoing enough to walk on a leash, energetic enough to play fetch and other interactive games, and confident enough to get along with other cats and friendly dogs.", + "life_span": "12 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 1, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 3, + "stranger_friendly": 5, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Toyger", + "hypoallergenic": 0, + "reference_image_id": "O3F3_S1XN" + }, + { + "weight": { + "imperial": "5 - 10", + "metric": "2 - 5" + }, + "id": "tang", + "name": "Turkish Angora", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/TurkishAngora.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/turkish-angora", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/turkish-angora", + "temperament": "Affectionate, Agile, Clever, Gentle, Intelligent, Playful, Social", + "origin": "Turkey", + "country_codes": "TR", + "country_code": "TR", + "description": "This is a smart and intelligent cat which bonds well with humans. With its affectionate and playful personality the Angora is a top choice for families. The Angora gets along great with other pets in the home, but it will make clear who is in charge, and who the house belongs to", + "life_span": "15 - 18", + "indoor": 0, + "alt_names": "Ankara", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 2, + "health_issues": 2, + "intelligence": 5, + "shedding_level": 2, + "social_needs": 5, + "stranger_friendly": 5, + "vocalisation": 3, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Turkish_Angora", + "hypoallergenic": 0, + "reference_image_id": "7CGV6WVXq" + }, + { + "weight": { + "imperial": "7 - 20", + "metric": "3 - 9" + }, + "id": "tvan", + "name": "Turkish Van", + "cfa_url": "http://cfa.org/Breeds/BreedsSthruT/TurkishVan.aspx", + "vetstreet_url": "http://www.vetstreet.com/cats/turkish-van", + "vcahospitals_url": "https://vcahospitals.com/know-your-pet/cat-breeds/turkish-van", + "temperament": "Agile, Intelligent, Loyal, Playful, Energetic", + "origin": "Turkey", + "country_codes": "TR", + "country_code": "TR", + "description": "While the Turkish Van loves to jump and climb, play with toys, retrieve and play chase, she is is big and ungainly; this is one cat who doesn’t always land on his feet. While not much of a lap cat, the Van will be happy to cuddle next to you and sleep in your bed. ", + "life_span": "12 - 17", + "indoor": 0, + "alt_names": "Turkish Cat, Swimming cat", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 2, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 1, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/Turkish_Van", + "hypoallergenic": 0, + "reference_image_id": "sxIXJax6h" + }, + { + "weight": { + "imperial": "12 - 18", + "metric": "5 - 8" + }, + "id": "ycho", + "name": "York Chocolate", + "temperament": "Playful, Social, Intelligent, Curious, Friendly", + "origin": "United States", + "country_codes": "US", + "country_code": "US", + "description": "York Chocolate cats are known to be true lap cats with a sweet temperament. They love to be cuddled and petted. Their curious nature makes them follow you all the time and participate in almost everything you do, even if it's related to water: unlike many other cats, York Chocolates love it.", + "life_span": "13 - 15", + "indoor": 0, + "lap": 1, + "alt_names": "York", + "adaptability": 5, + "affection_level": 5, + "child_friendly": 4, + "dog_friendly": 5, + "energy_level": 5, + "grooming": 3, + "health_issues": 1, + "intelligence": 5, + "shedding_level": 3, + "social_needs": 4, + "stranger_friendly": 4, + "vocalisation": 5, + "experimental": 0, + "hairless": 0, + "natural": 0, + "rare": 0, + "rex": 0, + "suppressed_tail": 0, + "short_legs": 0, + "wikipedia_url": "https://en.wikipedia.org/wiki/York_Chocolate", + "hypoallergenic": 0, + "reference_image_id": "0SxW2SQ_S" + } +] \ No newline at end of file diff --git a/data/countries_data_long.json b/data/countries_data_long.json new file mode 100644 index 000000000..17d8b15c0 --- /dev/null +++ b/data/countries_data_long.json @@ -0,0 +1,20502 @@ +[ + { + "name": "Afghanistan", + "topLevelDomain": [ + ".af" + ], + "alpha2Code": "AF", + "alpha3Code": "AFG", + "callingCodes": [ + "93" + ], + "capital": "Kabul", + "altSpellings": [ + "AF", + "Afġānistān" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 40218234, + "latlng": [ + 33.0, + 65.0 + ], + "demonym": "Afghan", + "area": 652230.0, + "timezones": [ + "UTC+04:30" + ], + "borders": [ + "IRN", + "PAK", + "TKM", + "UZB", + "TJK", + "CHN" + ], + "nativeName": "افغانستان", + "numericCode": "004", + "flags": { + "svg": "https://upload.wikimedia.org/wikipedia/commons/5/5c/Flag_of_the_Taliban.svg", + "png": "https://upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Flag_of_the_Taliban.svg/320px-Flag_of_the_Taliban.svg.png" + }, + "currencies": [ + { + "code": "AFN", + "name": "Afghan afghani", + "symbol": "؋" + } + ], + "languages": [ + { + "iso639_1": "ps", + "iso639_2": "pus", + "name": "Pashto", + "nativeName": "پښتو" + }, + { + "iso639_1": "uz", + "iso639_2": "uzb", + "name": "Uzbek", + "nativeName": "Oʻzbek" + }, + { + "iso639_1": "tk", + "iso639_2": "tuk", + "name": "Turkmen", + "nativeName": "Türkmen" + } + ], + "translations": { + "br": "Afghanistan", + "pt": "Afeganistão", + "nl": "Afghanistan", + "hr": "Afganistan", + "fa": "افغانستان", + "de": "Afghanistan", + "es": "Afganistán", + "fr": "Afghanistan", + "ja": "アフガニスタン", + "it": "Afghanistan", + "hu": "Afganisztán" + }, + "flag": "https://upload.wikimedia.org/wikipedia/commons/5/5c/Flag_of_the_Taliban.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "AFG", + "independent": true + }, + { + "name": "Åland Islands", + "topLevelDomain": [ + ".ax" + ], + "alpha2Code": "AX", + "alpha3Code": "ALA", + "callingCodes": [ + "358" + ], + "capital": "Mariehamn", + "altSpellings": [ + "AX", + "Aaland", + "Aland", + "Ahvenanmaa" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 28875, + "latlng": [ + 60.116667, + 19.9 + ], + "demonym": "Ålandish", + "area": 1580.0, + "timezones": [ + "UTC+02:00" + ], + "nativeName": "Åland", + "numericCode": "248", + "flags": { + "svg": "https://flagcdn.com/ax.svg", + "png": "https://flagcdn.com/w320/ax.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "sv", + "iso639_2": "swe", + "name": "Swedish", + "nativeName": "svenska" + } + ], + "translations": { + "br": "Åland", + "pt": "Ilhas de Aland", + "nl": "Ålandeilanden", + "hr": "Ålandski otoci", + "fa": "جزایر الند", + "de": "Åland", + "es": "Alandia", + "fr": "Åland", + "ja": "オーランド諸島", + "it": "Isole Aland", + "hu": "Åland-szigetek" + }, + "flag": "https://flagcdn.com/ax.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "independent": false + }, + { + "name": "Albania", + "topLevelDomain": [ + ".al" + ], + "alpha2Code": "AL", + "alpha3Code": "ALB", + "callingCodes": [ + "355" + ], + "capital": "Tirana", + "altSpellings": [ + "AL", + "Shqipëri", + "Shqipëria", + "Shqipnia" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 2837743, + "latlng": [ + 41.0, + 20.0 + ], + "demonym": "Albanian", + "area": 28748.0, + "gini": 33.2, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "MNE", + "GRC", + "MKD", + "UNK" + ], + "nativeName": "Shqipëria", + "numericCode": "008", + "flags": { + "svg": "https://flagcdn.com/al.svg", + "png": "https://flagcdn.com/w320/al.png" + }, + "currencies": [ + { + "code": "ALL", + "name": "Albanian lek", + "symbol": "L" + } + ], + "languages": [ + { + "iso639_1": "sq", + "iso639_2": "sqi", + "name": "Albanian", + "nativeName": "Shqip" + } + ], + "translations": { + "br": "Albania", + "pt": "Albânia", + "nl": "Albanië", + "hr": "Albanija", + "fa": "آلبانی", + "de": "Albanien", + "es": "Albania", + "fr": "Albanie", + "ja": "アルバニア", + "it": "Albania", + "hu": "Albánia" + }, + "flag": "https://flagcdn.com/al.svg", + "regionalBlocs": [ + { + "acronym": "CEFTA", + "name": "Central European Free Trade Agreement" + } + ], + "cioc": "ALB", + "independent": true + }, + { + "name": "Algeria", + "topLevelDomain": [ + ".dz" + ], + "alpha2Code": "DZ", + "alpha3Code": "DZA", + "callingCodes": [ + "213" + ], + "capital": "Algiers", + "altSpellings": [ + "DZ", + "Dzayer", + "Algérie" + ], + "subregion": "Northern Africa", + "region": "Africa", + "population": 44700000, + "latlng": [ + 28.0, + 3.0 + ], + "demonym": "Algerian", + "area": 2381741.0, + "gini": 27.6, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "TUN", + "LBY", + "NER", + "ESH", + "MRT", + "MLI", + "MAR" + ], + "nativeName": "الجزائر", + "numericCode": "012", + "flags": { + "svg": "https://flagcdn.com/dz.svg", + "png": "https://flagcdn.com/w320/dz.png" + }, + "currencies": [ + { + "code": "DZD", + "name": "Algerian dinar", + "symbol": "د.ج" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Aljeria", + "pt": "Argélia", + "nl": "Algerije", + "hr": "Alžir", + "fa": "الجزایر", + "de": "Algerien", + "es": "Argelia", + "fr": "Algérie", + "ja": "アルジェリア", + "it": "Algeria", + "hu": "Algéria" + }, + "flag": "https://flagcdn.com/dz.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "ALG", + "independent": true + }, + { + "name": "American Samoa", + "topLevelDomain": [ + ".as" + ], + "alpha2Code": "AS", + "alpha3Code": "ASM", + "callingCodes": [ + "1" + ], + "capital": "Pago Pago", + "altSpellings": [ + "AS", + "Amerika Sāmoa", + "Amelika Sāmoa", + "Sāmoa Amelika" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 55197, + "latlng": [ + -14.33333333, + -170.0 + ], + "demonym": "American Samoan", + "area": 199.0, + "timezones": [ + "UTC-11:00" + ], + "nativeName": "American Samoa", + "numericCode": "016", + "flags": { + "svg": "https://flagcdn.com/as.svg", + "png": "https://flagcdn.com/w320/as.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States Dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "sm", + "iso639_2": "smo", + "name": "Samoan", + "nativeName": "gagana fa'a Samoa" + } + ], + "translations": { + "br": "Samoa Amerikan", + "pt": "Samoa Americana", + "nl": "Amerikaans Samoa", + "hr": "Američka Samoa", + "fa": "ساموآی آمریکا", + "de": "Amerikanisch-Samoa", + "es": "Samoa Americana", + "fr": "Samoa américaines", + "ja": "アメリカ領サモア", + "it": "Samoa Americane", + "hu": "Amerikai Szamoa" + }, + "flag": "https://flagcdn.com/as.svg", + "cioc": "ASA", + "independent": false + }, + { + "name": "Andorra", + "topLevelDomain": [ + ".ad" + ], + "alpha2Code": "AD", + "alpha3Code": "AND", + "callingCodes": [ + "376" + ], + "capital": "Andorra la Vella", + "altSpellings": [ + "AD", + "Principality of Andorra", + "Principat d'Andorra" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 77265, + "latlng": [ + 42.5, + 1.5 + ], + "demonym": "Andorran", + "area": 468.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "FRA", + "ESP" + ], + "nativeName": "Andorra", + "numericCode": "020", + "flags": { + "svg": "https://flagcdn.com/ad.svg", + "png": "https://flagcdn.com/w320/ad.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "ca", + "iso639_2": "cat", + "name": "Catalan", + "nativeName": "català" + } + ], + "translations": { + "br": "Andorra", + "pt": "Andorra", + "nl": "Andorra", + "hr": "Andora", + "fa": "آندورا", + "de": "Andorra", + "es": "Andorra", + "fr": "Andorre", + "ja": "アンドラ", + "it": "Andorra", + "hu": "Andorra" + }, + "flag": "https://flagcdn.com/ad.svg", + "cioc": "AND", + "independent": true + }, + { + "name": "Angola", + "topLevelDomain": [ + ".ao" + ], + "alpha2Code": "AO", + "alpha3Code": "AGO", + "callingCodes": [ + "244" + ], + "capital": "Luanda", + "altSpellings": [ + "AO", + "República de Angola", + "ʁɛpublika de an'ɡɔla" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 32866268, + "latlng": [ + -12.5, + 18.5 + ], + "demonym": "Angolan", + "area": 1246700.0, + "gini": 51.3, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "COG", + "COD", + "ZMB", + "NAM" + ], + "nativeName": "Angola", + "numericCode": "024", + "flags": { + "svg": "https://flagcdn.com/ao.svg", + "png": "https://flagcdn.com/w320/ao.png" + }, + "currencies": [ + { + "code": "AOA", + "name": "Angolan kwanza", + "symbol": "Kz" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Angola", + "pt": "Angola", + "nl": "Angola", + "hr": "Angola", + "fa": "آنگولا", + "de": "Angola", + "es": "Angola", + "fr": "Angola", + "ja": "アンゴラ", + "it": "Angola", + "hu": "Angola" + }, + "flag": "https://flagcdn.com/ao.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "ANG", + "independent": true + }, + { + "name": "Anguilla", + "topLevelDomain": [ + ".ai" + ], + "alpha2Code": "AI", + "alpha3Code": "AIA", + "callingCodes": [ + "1" + ], + "capital": "The Valley", + "altSpellings": [ + "AI" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 13452, + "latlng": [ + 18.25, + -63.16666666 + ], + "demonym": "Anguillian", + "area": 91.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Anguilla", + "numericCode": "660", + "flags": { + "svg": "https://flagcdn.com/ai.svg", + "png": "https://flagcdn.com/w320/ai.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Anguilla", + "pt": "Anguila", + "nl": "Anguilla", + "hr": "Angvila", + "fa": "آنگویلا", + "de": "Anguilla", + "es": "Anguilla", + "fr": "Anguilla", + "ja": "アンギラ", + "it": "Anguilla", + "hu": "Anguilla" + }, + "flag": "https://flagcdn.com/ai.svg", + "independent": false + }, + { + "name": "Antarctica", + "topLevelDomain": [ + ".aq" + ], + "alpha2Code": "AQ", + "alpha3Code": "ATA", + "callingCodes": [ + "672" + ], + "subregion": "Antarctica", + "region": "Polar", + "population": 1000, + "latlng": [ + -74.65, + 4.48 + ], + "demonym": "Antarctic", + "area": 14000000.0, + "timezones": [ + "UTC-03:00", + "UTC+03:00", + "UTC+05:00", + "UTC+06:00", + "UTC+07:00", + "UTC+08:00", + "UTC+10:00", + "UTC+12:00" + ], + "nativeName": "Antarctica", + "numericCode": "010", + "flags": { + "svg": "https://flagcdn.com/aq.svg", + "png": "https://flagcdn.com/w320/aq.png" + }, + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Antarktika", + "pt": "Antárctida", + "nl": "Antarctica", + "hr": "Antarktika", + "fa": "جنوبگان", + "de": "Antarktika", + "es": "Antártida", + "fr": "Antarctique", + "ja": "南極大陸", + "it": "Antartide", + "hu": "Antarktisz" + }, + "flag": "https://flagcdn.com/aq.svg", + "independent": false + }, + { + "name": "Antigua and Barbuda", + "topLevelDomain": [ + ".ag" + ], + "alpha2Code": "AG", + "alpha3Code": "ATG", + "callingCodes": [ + "1" + ], + "capital": "Saint John's", + "altSpellings": [ + "AG" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 97928, + "latlng": [ + 17.05, + -61.8 + ], + "demonym": "Antiguan, Barbudan", + "area": 442.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Antigua and Barbuda", + "numericCode": "028", + "flags": { + "svg": "https://flagcdn.com/ag.svg", + "png": "https://flagcdn.com/w320/ag.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Antigua ha Barbuda", + "pt": "Antígua e Barbuda", + "nl": "Antigua en Barbuda", + "hr": "Antigva i Barbuda", + "fa": "آنتیگوا و باربودا", + "de": "Antigua und Barbuda", + "es": "Antigua y Barbuda", + "fr": "Antigua-et-Barbuda", + "ja": "アンティグア・バーブーダ", + "it": "Antigua e Barbuda", + "hu": "Antigua és Barbuda" + }, + "flag": "https://flagcdn.com/ag.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "ANT", + "independent": true + }, + { + "name": "Argentina", + "topLevelDomain": [ + ".ar" + ], + "alpha2Code": "AR", + "alpha3Code": "ARG", + "callingCodes": [ + "54" + ], + "capital": "Buenos Aires", + "altSpellings": [ + "AR", + "Argentine Republic", + "República Argentina" + ], + "subregion": "South America", + "region": "Americas", + "population": 45376763, + "latlng": [ + -34.0, + -64.0 + ], + "demonym": "Argentinean", + "area": 2780400.0, + "gini": 42.9, + "timezones": [ + "UTC-03:00" + ], + "borders": [ + "BOL", + "BRA", + "CHL", + "PRY", + "URY" + ], + "nativeName": "Argentina", + "numericCode": "032", + "flags": { + "svg": "https://flagcdn.com/ar.svg", + "png": "https://flagcdn.com/w320/ar.png" + }, + "currencies": [ + { + "code": "ARS", + "name": "Argentine peso", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + }, + { + "iso639_1": "gn", + "iso639_2": "grn", + "name": "Guaraní", + "nativeName": "Avañe'ẽ" + } + ], + "translations": { + "br": "Arc'hantina", + "pt": "Argentina", + "nl": "Argentinië", + "hr": "Argentina", + "fa": "آرژانتین", + "de": "Argentinien", + "es": "Argentina", + "fr": "Argentine", + "ja": "アルゼンチン", + "it": "Argentina", + "hu": "Argentína" + }, + "flag": "https://flagcdn.com/ar.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "ARG", + "independent": true + }, + { + "name": "Armenia", + "topLevelDomain": [ + ".am" + ], + "alpha2Code": "AM", + "alpha3Code": "ARM", + "callingCodes": [ + "374" + ], + "capital": "Yerevan", + "altSpellings": [ + "AM", + "Hayastan", + "Republic of Armenia", + "Հայաստանի Հանրապետություն" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 2963234, + "latlng": [ + 40.0, + 45.0 + ], + "demonym": "Armenian", + "area": 29743.0, + "gini": 29.9, + "timezones": [ + "UTC+04:00" + ], + "borders": [ + "AZE", + "GEO", + "IRN", + "TUR" + ], + "nativeName": "Հայաստան", + "numericCode": "051", + "flags": { + "svg": "https://flagcdn.com/am.svg", + "png": "https://flagcdn.com/w320/am.png" + }, + "currencies": [ + { + "code": "AMD", + "name": "Armenian dram", + "symbol": "֏" + } + ], + "languages": [ + { + "iso639_1": "hy", + "iso639_2": "hye", + "name": "Armenian", + "nativeName": "Հայերեն" + } + ], + "translations": { + "br": "Armenia", + "pt": "Arménia", + "nl": "Armenië", + "hr": "Armenija", + "fa": "ارمنستان", + "de": "Armenien", + "es": "Armenia", + "fr": "Arménie", + "ja": "アルメニア", + "it": "Armenia", + "hu": "Örményország" + }, + "flag": "https://flagcdn.com/am.svg", + "regionalBlocs": [ + { + "acronym": "EEU", + "name": "Eurasian Economic Union", + "otherAcronyms": [ + "EAEU" + ] + } + ], + "cioc": "ARM", + "independent": true + }, + { + "name": "Aruba", + "topLevelDomain": [ + ".aw" + ], + "alpha2Code": "AW", + "alpha3Code": "ABW", + "callingCodes": [ + "297" + ], + "capital": "Oranjestad", + "altSpellings": [ + "AW" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 106766, + "latlng": [ + 12.5, + -69.96666666 + ], + "demonym": "Aruban", + "area": 180.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Aruba", + "numericCode": "533", + "flags": { + "svg": "https://flagcdn.com/aw.svg", + "png": "https://flagcdn.com/w320/aw.png" + }, + "currencies": [ + { + "code": "AWG", + "name": "Aruban florin", + "symbol": "ƒ" + } + ], + "languages": [ + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + }, + { + "iso639_1": "pa", + "iso639_2": "pan", + "name": "(Eastern) Punjabi", + "nativeName": "ਪੰਜਾਬੀ" + } + ], + "translations": { + "br": "Aruba", + "pt": "Aruba", + "nl": "Aruba", + "hr": "Aruba", + "fa": "آروبا", + "de": "Aruba", + "es": "Aruba", + "fr": "Aruba", + "ja": "アルバ", + "it": "Aruba", + "hu": "Aruba" + }, + "flag": "https://flagcdn.com/aw.svg", + "cioc": "ARU", + "independent": true + }, + { + "name": "Australia", + "topLevelDomain": [ + ".au" + ], + "alpha2Code": "AU", + "alpha3Code": "AUS", + "callingCodes": [ + "61" + ], + "capital": "Canberra", + "altSpellings": [ + "AU" + ], + "subregion": "Australia and New Zealand", + "region": "Oceania", + "population": 25687041, + "latlng": [ + -27.0, + 133.0 + ], + "demonym": "Australian", + "area": 7692024.0, + "gini": 34.4, + "timezones": [ + "UTC+05:00", + "UTC+06:30", + "UTC+07:00", + "UTC+08:00", + "UTC+09:30", + "UTC+10:00", + "UTC+10:30", + "UTC+11:30" + ], + "nativeName": "Australia", + "numericCode": "036", + "flags": { + "svg": "https://flagcdn.com/au.svg", + "png": "https://flagcdn.com/w320/au.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Aostralia", + "pt": "Austrália", + "nl": "Australië", + "hr": "Australija", + "fa": "استرالیا", + "de": "Australien", + "es": "Australia", + "fr": "Australie", + "ja": "オーストラリア", + "it": "Australia", + "hu": "Ausztrália" + }, + "flag": "https://flagcdn.com/au.svg", + "cioc": "AUS", + "independent": true + }, + { + "name": "Austria", + "topLevelDomain": [ + ".at" + ], + "alpha2Code": "AT", + "alpha3Code": "AUT", + "callingCodes": [ + "43" + ], + "capital": "Vienna", + "altSpellings": [ + "AT", + "Österreich", + "Osterreich", + "Oesterreich" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 8917205, + "latlng": [ + 47.33333333, + 13.33333333 + ], + "demonym": "Austrian", + "area": 83871.0, + "gini": 30.8, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "CZE", + "DEU", + "HUN", + "ITA", + "LIE", + "SVK", + "SVN", + "CHE" + ], + "nativeName": "Österreich", + "numericCode": "040", + "flags": { + "svg": "https://flagcdn.com/at.svg", + "png": "https://flagcdn.com/w320/at.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "de", + "iso639_2": "deu", + "name": "German", + "nativeName": "Deutsch" + } + ], + "translations": { + "br": "Aostria", + "pt": "Áustria", + "nl": "Oostenrijk", + "hr": "Austrija", + "fa": "اتریش", + "de": "Österreich", + "es": "Austria", + "fr": "Autriche", + "ja": "オーストリア", + "it": "Austria", + "hu": "Ausztria" + }, + "flag": "https://flagcdn.com/at.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "AUT", + "independent": true + }, + { + "name": "Azerbaijan", + "topLevelDomain": [ + ".az" + ], + "alpha2Code": "AZ", + "alpha3Code": "AZE", + "callingCodes": [ + "994" + ], + "capital": "Baku", + "altSpellings": [ + "AZ", + "Republic of Azerbaijan", + "Azərbaycan Respublikası" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 10110116, + "latlng": [ + 40.5, + 47.5 + ], + "demonym": "Azerbaijani", + "area": 86600.0, + "gini": 26.6, + "timezones": [ + "UTC+04:00" + ], + "borders": [ + "ARM", + "GEO", + "IRN", + "RUS", + "TUR" + ], + "nativeName": "Azərbaycan", + "numericCode": "031", + "flags": { + "svg": "https://flagcdn.com/az.svg", + "png": "https://flagcdn.com/w320/az.png" + }, + "currencies": [ + { + "code": "AZN", + "name": "Azerbaijani manat", + "symbol": "₼" + } + ], + "languages": [ + { + "iso639_1": "az", + "iso639_2": "aze", + "name": "Azerbaijani", + "nativeName": "azərbaycan dili" + } + ], + "translations": { + "br": "Azerbaidjan", + "pt": "Azerbaijão", + "nl": "Azerbeidzjan", + "hr": "Azerbajdžan", + "fa": "آذربایجان", + "de": "Aserbaidschan", + "es": "Azerbaiyán", + "fr": "Azerbaïdjan", + "ja": "アゼルバイジャン", + "it": "Azerbaijan", + "hu": "Azerbajdzsán" + }, + "flag": "https://flagcdn.com/az.svg", + "cioc": "AZE", + "independent": true + }, + { + "name": "Bahamas", + "topLevelDomain": [ + ".bs" + ], + "alpha2Code": "BS", + "alpha3Code": "BHS", + "callingCodes": [ + "1" + ], + "capital": "Nassau", + "altSpellings": [ + "BS", + "Commonwealth of the Bahamas" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 393248, + "latlng": [ + 24.25, + -76.0 + ], + "demonym": "Bahamian", + "area": 13943.0, + "timezones": [ + "UTC-05:00" + ], + "nativeName": "Bahamas", + "numericCode": "044", + "flags": { + "svg": "https://flagcdn.com/bs.svg", + "png": "https://flagcdn.com/w320/bs.png" + }, + "currencies": [ + { + "code": "BSD", + "name": "Bahamian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Bahamas", + "pt": "Baamas", + "nl": "Bahama’s", + "hr": "Bahami", + "fa": "باهاما", + "de": "Bahamas", + "es": "Bahamas", + "fr": "Bahamas", + "ja": "バハマ", + "it": "Bahamas", + "hu": "Bahama-szigetek" + }, + "flag": "https://flagcdn.com/bs.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "BAH", + "independent": true + }, + { + "name": "Bahrain", + "topLevelDomain": [ + ".bh" + ], + "alpha2Code": "BH", + "alpha3Code": "BHR", + "callingCodes": [ + "973" + ], + "capital": "Manama", + "altSpellings": [ + "BH", + "Kingdom of Bahrain", + "Mamlakat al-Baḥrayn" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 1701583, + "latlng": [ + 26.0, + 50.55 + ], + "demonym": "Bahraini", + "area": 765.0, + "timezones": [ + "UTC+03:00" + ], + "nativeName": "‏البحرين", + "numericCode": "048", + "flags": { + "svg": "https://flagcdn.com/bh.svg", + "png": "https://flagcdn.com/w320/bh.png" + }, + "currencies": [ + { + "code": "BHD", + "name": "Bahraini dinar", + "symbol": ".د.ب" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Bahrein", + "pt": "Barém", + "nl": "Bahrein", + "hr": "Bahrein", + "fa": "بحرین", + "de": "Bahrain", + "es": "Bahrein", + "fr": "Bahreïn", + "ja": "バーレーン", + "it": "Bahrein", + "hu": "Bahrein" + }, + "flag": "https://flagcdn.com/bh.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "BRN", + "independent": true + }, + { + "name": "Bangladesh", + "topLevelDomain": [ + ".bd" + ], + "alpha2Code": "BD", + "alpha3Code": "BGD", + "callingCodes": [ + "880" + ], + "capital": "Dhaka", + "altSpellings": [ + "BD", + "People's Republic of Bangladesh", + "Gônôprôjatôntri Bangladesh" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 164689383, + "latlng": [ + 24.0, + 90.0 + ], + "demonym": "Bangladeshi", + "area": 147570.0, + "gini": 32.4, + "timezones": [ + "UTC+06:00" + ], + "borders": [ + "MMR", + "IND" + ], + "nativeName": "Bangladesh", + "numericCode": "050", + "flags": { + "svg": "https://flagcdn.com/bd.svg", + "png": "https://flagcdn.com/w320/bd.png" + }, + "currencies": [ + { + "code": "BDT", + "name": "Bangladeshi taka", + "symbol": "৳" + } + ], + "languages": [ + { + "iso639_1": "bn", + "iso639_2": "ben", + "name": "Bengali", + "nativeName": "বাংলা" + } + ], + "translations": { + "br": "Bangladesh", + "pt": "Bangladeche", + "nl": "Bangladesh", + "hr": "Bangladeš", + "fa": "بنگلادش", + "de": "Bangladesch", + "es": "Bangladesh", + "fr": "Bangladesh", + "ja": "バングラデシュ", + "it": "Bangladesh", + "hu": "Banglades" + }, + "flag": "https://flagcdn.com/bd.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "BAN", + "independent": true + }, + { + "name": "Barbados", + "topLevelDomain": [ + ".bb" + ], + "alpha2Code": "BB", + "alpha3Code": "BRB", + "callingCodes": [ + "1" + ], + "capital": "Bridgetown", + "altSpellings": [ + "BB" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 287371, + "latlng": [ + 13.16666666, + -59.53333333 + ], + "demonym": "Barbadian", + "area": 430.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Barbados", + "numericCode": "052", + "flags": { + "svg": "https://flagcdn.com/bb.svg", + "png": "https://flagcdn.com/w320/bb.png" + }, + "currencies": [ + { + "code": "BBD", + "name": "Barbadian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Barbados", + "pt": "Barbados", + "nl": "Barbados", + "hr": "Barbados", + "fa": "باربادوس", + "de": "Barbados", + "es": "Barbados", + "fr": "Barbade", + "ja": "バルバドス", + "it": "Barbados", + "hu": "Barbados" + }, + "flag": "https://flagcdn.com/bb.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "BAR", + "independent": true + }, + { + "name": "Belarus", + "topLevelDomain": [ + ".by" + ], + "alpha2Code": "BY", + "alpha3Code": "BLR", + "callingCodes": [ + "375" + ], + "capital": "Minsk", + "altSpellings": [ + "BY", + "Bielaruś", + "Republic of Belarus", + "Белоруссия", + "Республика Беларусь", + "Belorussiya", + "Respublika Belarus’" + ], + "subregion": "Eastern Europe", + "region": "Europe", + "population": 9398861, + "latlng": [ + 53.0, + 28.0 + ], + "demonym": "Belarusian", + "area": 207600.0, + "gini": 25.3, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "LVA", + "LTU", + "POL", + "RUS", + "UKR" + ], + "nativeName": "Белару́сь", + "numericCode": "112", + "flags": { + "svg": "https://flagcdn.com/by.svg", + "png": "https://flagcdn.com/w320/by.png" + }, + "currencies": [ + { + "code": "BYN", + "name": "New Belarusian ruble", + "symbol": "Br" + }, + { + "code": "BYR", + "name": "Old Belarusian ruble", + "symbol": "Br" + } + ], + "languages": [ + { + "iso639_1": "be", + "iso639_2": "bel", + "name": "Belarusian", + "nativeName": "беларуская мова" + }, + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Belarus", + "pt": "Bielorrússia", + "nl": "Wit-Rusland", + "hr": "Bjelorusija", + "fa": "بلاروس", + "de": "Weißrussland", + "es": "Bielorrusia", + "fr": "Biélorussie", + "ja": "ベラルーシ", + "it": "Bielorussia", + "hu": "Fehéroroszország" + }, + "flag": "https://flagcdn.com/by.svg", + "regionalBlocs": [ + { + "acronym": "EEU", + "name": "Eurasian Economic Union", + "otherAcronyms": [ + "EAEU" + ] + } + ], + "cioc": "BLR", + "independent": true + }, + { + "name": "Belgium", + "topLevelDomain": [ + ".be" + ], + "alpha2Code": "BE", + "alpha3Code": "BEL", + "callingCodes": [ + "32" + ], + "capital": "Brussels", + "altSpellings": [ + "BE", + "België", + "Belgie", + "Belgien", + "Belgique", + "Kingdom of Belgium", + "Koninkrijk België", + "Royaume de Belgique", + "Königreich Belgien" + ], + "subregion": "Western Europe", + "region": "Europe", + "population": 11555997, + "latlng": [ + 50.83333333, + 4.0 + ], + "demonym": "Belgian", + "area": 30528.0, + "gini": 27.2, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "FRA", + "DEU", + "LUX", + "NLD" + ], + "nativeName": "België", + "numericCode": "056", + "flags": { + "svg": "https://flagcdn.com/be.svg", + "png": "https://flagcdn.com/w320/be.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "de", + "iso639_2": "deu", + "name": "German", + "nativeName": "Deutsch" + } + ], + "translations": { + "br": "Belgia", + "pt": "Bélgica", + "nl": "België", + "hr": "Belgija", + "fa": "بلژیک", + "de": "Belgien", + "es": "Bélgica", + "fr": "Belgique", + "ja": "ベルギー", + "it": "Belgio", + "hu": "Belgium" + }, + "flag": "https://flagcdn.com/be.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "BEL", + "independent": true + }, + { + "name": "Belize", + "topLevelDomain": [ + ".bz" + ], + "alpha2Code": "BZ", + "alpha3Code": "BLZ", + "callingCodes": [ + "501" + ], + "capital": "Belmopan", + "altSpellings": [ + "BZ" + ], + "subregion": "Central America", + "region": "Americas", + "population": 397621, + "latlng": [ + 17.25, + -88.75 + ], + "demonym": "Belizean", + "area": 22966.0, + "gini": 53.3, + "timezones": [ + "UTC-06:00" + ], + "borders": [ + "GTM", + "MEX" + ], + "nativeName": "Belize", + "numericCode": "084", + "flags": { + "svg": "https://flagcdn.com/bz.svg", + "png": "https://flagcdn.com/w320/bz.png" + }, + "currencies": [ + { + "code": "BZD", + "name": "Belize dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Belize", + "pt": "Belize", + "nl": "Belize", + "hr": "Belize", + "fa": "بلیز", + "de": "Belize", + "es": "Belice", + "fr": "Belize", + "ja": "ベリーズ", + "it": "Belize", + "hu": "Belize" + }, + "flag": "https://flagcdn.com/bz.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + }, + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "BIZ", + "independent": true + }, + { + "name": "Benin", + "topLevelDomain": [ + ".bj" + ], + "alpha2Code": "BJ", + "alpha3Code": "BEN", + "callingCodes": [ + "229" + ], + "capital": "Porto-Novo", + "altSpellings": [ + "BJ", + "Republic of Benin", + "République du Bénin" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 12123198, + "latlng": [ + 9.5, + 2.25 + ], + "demonym": "Beninese", + "area": 112622.0, + "gini": 47.8, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "BFA", + "NER", + "NGA", + "TGO" + ], + "nativeName": "Bénin", + "numericCode": "204", + "flags": { + "svg": "https://flagcdn.com/bj.svg", + "png": "https://flagcdn.com/w320/bj.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Benin", + "pt": "Benim", + "nl": "Benin", + "hr": "Benin", + "fa": "بنین", + "de": "Benin", + "es": "Benín", + "fr": "Bénin", + "ja": "ベナン", + "it": "Benin", + "hu": "Benin" + }, + "flag": "https://flagcdn.com/bj.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "BEN", + "independent": true + }, + { + "name": "Bermuda", + "topLevelDomain": [ + ".bm" + ], + "alpha2Code": "BM", + "alpha3Code": "BMU", + "callingCodes": [ + "1" + ], + "capital": "Hamilton", + "altSpellings": [ + "BM", + "The Islands of Bermuda", + "The Bermudas", + "Somers Isles" + ], + "subregion": "Northern America", + "region": "Americas", + "population": 63903, + "latlng": [ + 32.33333333, + -64.75 + ], + "demonym": "Bermudian", + "area": 54.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Bermuda", + "numericCode": "060", + "flags": { + "svg": "https://flagcdn.com/bm.svg", + "png": "https://flagcdn.com/w320/bm.png" + }, + "currencies": [ + { + "code": "BMD", + "name": "Bermudian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Bermuda", + "pt": "Bermudas", + "nl": "Bermuda", + "hr": "Bermudi", + "fa": "برمودا", + "de": "Bermuda", + "es": "Bermudas", + "fr": "Bermudes", + "ja": "バミューダ", + "it": "Bermuda", + "hu": "Bermuda" + }, + "flag": "https://flagcdn.com/bm.svg", + "cioc": "BER", + "independent": false + }, + { + "name": "Bhutan", + "topLevelDomain": [ + ".bt" + ], + "alpha2Code": "BT", + "alpha3Code": "BTN", + "callingCodes": [ + "975" + ], + "capital": "Thimphu", + "altSpellings": [ + "BT", + "Kingdom of Bhutan" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 771612, + "latlng": [ + 27.5, + 90.5 + ], + "demonym": "Bhutanese", + "area": 38394.0, + "gini": 37.4, + "timezones": [ + "UTC+06:00" + ], + "borders": [ + "CHN", + "IND" + ], + "nativeName": "ʼbrug-yul", + "numericCode": "064", + "flags": { + "svg": "https://flagcdn.com/bt.svg", + "png": "https://flagcdn.com/w320/bt.png" + }, + "currencies": [ + { + "code": "BTN", + "name": "Bhutanese ngultrum", + "symbol": "Nu." + }, + { + "code": "INR", + "name": "Indian rupee", + "symbol": "₹" + } + ], + "languages": [ + { + "iso639_1": "dz", + "iso639_2": "dzo", + "name": "Dzongkha", + "nativeName": "རྫོང་ཁ" + } + ], + "translations": { + "br": "Bhoutan", + "pt": "Butão", + "nl": "Bhutan", + "hr": "Butan", + "fa": "بوتان", + "de": "Bhutan", + "es": "Bután", + "fr": "Bhoutan", + "ja": "ブータン", + "it": "Bhutan", + "hu": "Bhután" + }, + "flag": "https://flagcdn.com/bt.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "BHU", + "independent": true + }, + { + "name": "Bolivia (Plurinational State of)", + "topLevelDomain": [ + ".bo" + ], + "alpha2Code": "BO", + "alpha3Code": "BOL", + "callingCodes": [ + "591" + ], + "capital": "Sucre", + "altSpellings": [ + "BO", + "Buliwya", + "Wuliwya", + "Plurinational State of Bolivia", + "Estado Plurinacional de Bolivia", + "Buliwya Mamallaqta", + "Wuliwya Suyu", + "Tetã Volívia" + ], + "subregion": "South America", + "region": "Americas", + "population": 11673029, + "latlng": [ + -17.0, + -65.0 + ], + "demonym": "Bolivian", + "area": 1098581.0, + "gini": 41.6, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "ARG", + "BRA", + "CHL", + "PRY", + "PER" + ], + "nativeName": "Bolivia", + "numericCode": "068", + "flags": { + "svg": "https://flagcdn.com/bo.svg", + "png": "https://flagcdn.com/w320/bo.png" + }, + "currencies": [ + { + "code": "BOB", + "name": "Bolivian boliviano", + "symbol": "Bs." + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + }, + { + "iso639_1": "ay", + "iso639_2": "aym", + "name": "Aymara", + "nativeName": "aymar aru" + }, + { + "iso639_1": "qu", + "iso639_2": "que", + "name": "Quechua", + "nativeName": "Runa Simi" + } + ], + "translations": { + "br": "Bolivia", + "pt": "Bolívia", + "nl": "Bolivia", + "hr": "Bolivija", + "fa": "بولیوی", + "de": "Bolivien", + "es": "Bolivia", + "fr": "Bolivie", + "ja": "ボリビア多民族国", + "it": "Bolivia", + "hu": "Bolívia" + }, + "flag": "https://flagcdn.com/bo.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "BOL", + "independent": true + }, + { + "name": "Bonaire, Sint Eustatius and Saba", + "topLevelDomain": [ + ".an", + ".nl" + ], + "alpha2Code": "BQ", + "alpha3Code": "BES", + "callingCodes": [ + "599" + ], + "capital": "Kralendijk", + "altSpellings": [ + "BQ", + "Boneiru" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 17408, + "latlng": [ + 12.15, + -68.266667 + ], + "demonym": "Dutch", + "area": 294.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Bonaire", + "numericCode": "535", + "flags": { + "svg": "https://flagcdn.com/bq.svg", + "png": "https://flagcdn.com/w320/bq.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + } + ], + "translations": { + "br": "Bonaire, Sint Eustatius ha Saba", + "pt": "Bonaire", + "nl": "Caribisch Nederland", + "hr": "Bonaire, Sint Eustatius and Saba", + "fa": "بونیر", + "de": "Bonaire, Sint Eustatius und Saba", + "es": "Bonaire, Sint Eustatius and Saba", + "fr": "Bonaire, Saint-Eustache et Saba", + "ja": "Bonaire, Sint Eustatius and Saba", + "it": "Bonaire, Saint-Eustache e Saba", + "hu": "Bonaire" + }, + "flag": "https://flagcdn.com/bq.svg", + "independent": true + }, + { + "name": "Bosnia and Herzegovina", + "topLevelDomain": [ + ".ba" + ], + "alpha2Code": "BA", + "alpha3Code": "BIH", + "callingCodes": [ + "387" + ], + "capital": "Sarajevo", + "altSpellings": [ + "BA", + "Bosnia-Herzegovina", + "Босна и Херцеговина" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 3280815, + "latlng": [ + 44.0, + 18.0 + ], + "demonym": "Bosnian, Herzegovinian", + "area": 51209.0, + "gini": 33.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "HRV", + "MNE", + "SRB" + ], + "nativeName": "Bosna i Hercegovina", + "numericCode": "070", + "flags": { + "svg": "https://flagcdn.com/ba.svg", + "png": "https://flagcdn.com/w320/ba.png" + }, + "currencies": [ + { + "code": "BAM", + "name": "Bosnia and Herzegovina convertible mark", + "symbol": "KM" + } + ], + "languages": [ + { + "iso639_1": "bs", + "iso639_2": "bos", + "name": "Bosnian", + "nativeName": "bosanski jezik" + }, + { + "iso639_1": "hr", + "iso639_2": "hrv", + "name": "Croatian", + "nativeName": "hrvatski jezik" + }, + { + "iso639_1": "sr", + "iso639_2": "srp", + "name": "Serbian", + "nativeName": "српски језик" + } + ], + "translations": { + "br": "Bosnia-ha-Herzegovina", + "pt": "Bósnia e Herzegovina", + "nl": "Bosnië en Herzegovina", + "hr": "Bosna i Hercegovina", + "fa": "بوسنی و هرزگوین", + "de": "Bosnien und Herzegowina", + "es": "Bosnia y Herzegovina", + "fr": "Bosnie-Herzégovine", + "ja": "ボスニア・ヘルツェゴビナ", + "it": "Bosnia ed Erzegovina", + "hu": "Bosznia-Hercegovina" + }, + "flag": "https://flagcdn.com/ba.svg", + "regionalBlocs": [ + { + "acronym": "CEFTA", + "name": "Central European Free Trade Agreement" + } + ], + "cioc": "BIH", + "independent": true + }, + { + "name": "Botswana", + "topLevelDomain": [ + ".bw" + ], + "alpha2Code": "BW", + "alpha3Code": "BWA", + "callingCodes": [ + "267" + ], + "capital": "Gaborone", + "altSpellings": [ + "BW", + "Republic of Botswana", + "Lefatshe la Botswana" + ], + "subregion": "Southern Africa", + "region": "Africa", + "population": 2351625, + "latlng": [ + -22.0, + 24.0 + ], + "demonym": "Motswana", + "area": 582000.0, + "gini": 53.3, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "NAM", + "ZAF", + "ZMB", + "ZWE" + ], + "nativeName": "Botswana", + "numericCode": "072", + "flags": { + "svg": "https://flagcdn.com/bw.svg", + "png": "https://flagcdn.com/w320/bw.png" + }, + "currencies": [ + { + "code": "BWP", + "name": "Botswana pula", + "symbol": "P" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "tn", + "iso639_2": "tsn", + "name": "Tswana", + "nativeName": "Setswana" + } + ], + "translations": { + "br": "Botswana", + "pt": "Botsuana", + "nl": "Botswana", + "hr": "Bocvana", + "fa": "بوتسوانا", + "de": "Botswana", + "es": "Botswana", + "fr": "Botswana", + "ja": "ボツワナ", + "it": "Botswana", + "hu": "Botswana" + }, + "flag": "https://flagcdn.com/bw.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "BOT", + "independent": true + }, + { + "name": "Bouvet Island", + "topLevelDomain": [ + ".bv" + ], + "alpha2Code": "BV", + "alpha3Code": "BVT", + "callingCodes": [ + "47" + ], + "altSpellings": [ + "BV", + "Bouvetøya", + "Bouvet-øya" + ], + "subregion": "South Antarctic Ocean", + "region": "Antarctic Ocean", + "population": 0, + "latlng": [ + -54.43333333, + 3.4 + ], + "demonym": "Norwegian", + "area": 49.0, + "timezones": [ + "UTC+01:00" + ], + "nativeName": "Bouvetøya", + "numericCode": "074", + "flags": { + "svg": "https://flagcdn.com/bv.svg", + "png": "https://flagcdn.com/w320/bv.png" + }, + "currencies": [ + { + "code": "NOK", + "name": "Norwegian krone", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "no", + "iso639_2": "nor", + "name": "Norwegian", + "nativeName": "Norsk" + }, + { + "iso639_1": "nb", + "iso639_2": "nob", + "name": "Norwegian Bokmål", + "nativeName": "Norsk bokmål" + }, + { + "iso639_1": "nn", + "iso639_2": "nno", + "name": "Norwegian Nynorsk", + "nativeName": "Norsk nynorsk" + } + ], + "translations": { + "br": "Enez Bouvet", + "pt": "Ilha Bouvet", + "nl": "Bouveteiland", + "hr": "Otok Bouvet", + "fa": "جزیره بووه", + "de": "Bouvetinsel", + "es": "Isla Bouvet", + "fr": "Île Bouvet", + "ja": "ブーベ島", + "it": "Isola Bouvet", + "hu": "Bouvet-sziget" + }, + "flag": "https://flagcdn.com/bv.svg", + "independent": false + }, + { + "name": "Brazil", + "topLevelDomain": [ + ".br" + ], + "alpha2Code": "BR", + "alpha3Code": "BRA", + "callingCodes": [ + "55" + ], + "capital": "Brasília", + "altSpellings": [ + "BR", + "Brasil", + "Federative Republic of Brazil", + "República Federativa do Brasil" + ], + "subregion": "South America", + "region": "Americas", + "population": 212559409, + "latlng": [ + -10.0, + -55.0 + ], + "demonym": "Brazilian", + "area": 8515767.0, + "gini": 53.4, + "timezones": [ + "UTC-05:00", + "UTC-04:00", + "UTC-03:00", + "UTC-02:00" + ], + "borders": [ + "ARG", + "BOL", + "COL", + "FRA", + "GUF", + "GUY", + "PRY", + "PER", + "SUR", + "URY", + "VEN" + ], + "nativeName": "Brasil", + "numericCode": "076", + "flags": { + "svg": "https://flagcdn.com/br.svg", + "png": "https://flagcdn.com/w320/br.png" + }, + "currencies": [ + { + "code": "BRL", + "name": "Brazilian real", + "symbol": "R$" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Brazil", + "pt": "Brasil", + "nl": "Brazilië", + "hr": "Brazil", + "fa": "برزیل", + "de": "Brasilien", + "es": "Brasil", + "fr": "Brésil", + "ja": "ブラジル", + "it": "Brasile", + "hu": "Brazília" + }, + "flag": "https://flagcdn.com/br.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "BRA", + "independent": true + }, + { + "name": "British Indian Ocean Territory", + "topLevelDomain": [ + ".io" + ], + "alpha2Code": "IO", + "alpha3Code": "IOT", + "callingCodes": [ + "246" + ], + "capital": "Diego Garcia", + "altSpellings": [ + "IO" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 3000, + "latlng": [ + -6.0, + 71.5 + ], + "demonym": "Indian", + "area": 60.0, + "timezones": [ + "UTC+06:00" + ], + "nativeName": "British Indian Ocean Territory", + "numericCode": "086", + "flags": { + "svg": "https://flagcdn.com/io.svg", + "png": "https://flagcdn.com/w320/io.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Tiriad breizhveurat Meurvor Indez", + "pt": "Território Britânico do Oceano Índico", + "nl": "Britse Gebieden in de Indische Oceaan", + "hr": "Britanski Indijskooceanski teritorij", + "fa": "قلمرو بریتانیا در اقیانوس هند", + "de": "Britisches Territorium im Indischen Ozean", + "es": "Territorio Británico del Océano Índico", + "fr": "Territoire britannique de l'océan Indien", + "ja": "イギリス領インド洋地域", + "it": "Territorio britannico dell'oceano indiano", + "hu": "Brit Indiai-óceáni Terület" + }, + "flag": "https://flagcdn.com/io.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "independent": true + }, + { + "name": "United States Minor Outlying Islands", + "topLevelDomain": [ + ".us" + ], + "alpha2Code": "UM", + "alpha3Code": "UMI", + "callingCodes": [ + "246" + ], + "altSpellings": [ + "UM" + ], + "subregion": "Northern America", + "region": "Americas", + "population": 300, + "demonym": "American", + "timezones": [ + "UTC-11:00", + "UTC-10:00", + "UTC+12:00" + ], + "nativeName": "United States Minor Outlying Islands", + "numericCode": "581", + "flags": { + "svg": "https://flagcdn.com/um.svg", + "png": "https://flagcdn.com/w320/um.png" + }, + "currencies": [ + { + "code": "GBP", + "name": "British pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Minor A-bell Stadoù-Unanet", + "pt": "Ilhas Menores Distantes dos Estados Unidos", + "nl": "Kleine afgelegen eilanden van de Verenigde Staten", + "hr": "Mali udaljeni otoci SAD-a", + "fa": "جزایر کوچک حاشیه‌ای ایالات متحده آمریکا", + "de": "Kleinere Inselbesitzungen der Vereinigten Staaten", + "es": "Islas Ultramarinas Menores de Estados Unidos", + "fr": "Îles mineures éloignées des États-Unis", + "ja": "合衆国領有小離島", + "it": "Isole minori esterne degli Stati Uniti d'America", + "hu": "Amerikai Egyesült Államok lakatlan külbirtokai" + }, + "flag": "https://flagcdn.com/um.svg", + "independent": false + }, + { + "name": "Virgin Islands (British)", + "topLevelDomain": [ + ".vg" + ], + "alpha2Code": "VG", + "alpha3Code": "VGB", + "callingCodes": [ + "1" + ], + "capital": "Road Town", + "altSpellings": [ + "VG" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 30237, + "latlng": [ + 18.431383, + -64.62305 + ], + "demonym": "Virgin Islander", + "area": 151.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "British Virgin Islands", + "numericCode": "092", + "flags": { + "svg": "https://flagcdn.com/vg.svg", + "png": "https://flagcdn.com/w320/vg.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Gwerc'h Breizhveurat", + "pt": "Ilhas Virgens Britânicas", + "nl": "Britse Maagdeneilanden", + "hr": "Britanski Djevičanski Otoci", + "fa": "جزایر ویرجین بریتانیا", + "de": "Britische Jungferninseln", + "es": "Islas Vírgenes del Reino Unido", + "fr": "Îles Vierges britanniques", + "ja": "イギリス領ヴァージン諸島", + "it": "Isole Vergini Britanniche", + "hu": "Brit Virgin-szigetek" + }, + "flag": "https://flagcdn.com/vg.svg", + "cioc": "IVB", + "independent": false + }, + { + "name": "Virgin Islands (U.S.)", + "topLevelDomain": [ + ".vi" + ], + "alpha2Code": "VI", + "alpha3Code": "VIR", + "callingCodes": [ + "1 340" + ], + "capital": "Charlotte Amalie", + "altSpellings": [ + "VI", + "USVI", + "American Virgin Islands", + "U.S. Virgin Islands" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 106290, + "latlng": [ + 18.34, + -64.93 + ], + "demonym": "Virgin Islander", + "area": 346.36, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Virgin Islands of the United States", + "numericCode": "850", + "flags": { + "svg": "https://flagcdn.com/vi.svg", + "png": "https://flagcdn.com/w320/vi.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Gwerc'h ar Stadoù-Unanet", + "pt": "Ilhas Virgens Americanas", + "nl": "Verenigde Staten Maagdeneilanden", + "hr": "Virgin Islands (U.S.)", + "fa": "جزایر ویرجین آمریکا", + "de": "Amerikanische Jungferninseln", + "es": "Islas Vírgenes de los Estados Unidos", + "fr": "Îles Vierges des États-Unis", + "ja": "アメリカ領ヴァージン諸島", + "it": "Isole Vergini americane", + "hu": "Amerikai Virgin-szigetek" + }, + "flag": "https://flagcdn.com/vi.svg", + "cioc": "ISV", + "independent": false + }, + { + "name": "Brunei Darussalam", + "topLevelDomain": [ + ".bn" + ], + "alpha2Code": "BN", + "alpha3Code": "BRN", + "callingCodes": [ + "673" + ], + "capital": "Bandar Seri Begawan", + "altSpellings": [ + "BN", + "Nation of Brunei", + " the Abode of Peace" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 437483, + "latlng": [ + 4.5, + 114.66666666 + ], + "demonym": "Bruneian", + "area": 5765.0, + "timezones": [ + "UTC+08:00" + ], + "borders": [ + "MYS" + ], + "nativeName": "Negara Brunei Darussalam", + "numericCode": "096", + "flags": { + "svg": "https://flagcdn.com/bn.svg", + "png": "https://flagcdn.com/w320/bn.png" + }, + "currencies": [ + { + "code": "BND", + "name": "Brunei dollar", + "symbol": "$" + }, + { + "code": "SGD", + "name": "Singapore dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "ms", + "iso639_2": "msa", + "name": "Malay", + "nativeName": "bahasa Melayu" + } + ], + "translations": { + "br": "Brunei", + "pt": "Brunei", + "nl": "Brunei", + "hr": "Brunej", + "fa": "برونئی", + "de": "Brunei", + "es": "Brunei", + "fr": "Brunei", + "ja": "ブルネイ・ダルサラーム", + "it": "Brunei", + "hu": "Brunei" + }, + "flag": "https://flagcdn.com/bn.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "BRU", + "independent": true + }, + { + "name": "Bulgaria", + "topLevelDomain": [ + ".bg" + ], + "alpha2Code": "BG", + "alpha3Code": "BGR", + "callingCodes": [ + "359" + ], + "capital": "Sofia", + "altSpellings": [ + "BG", + "Republic of Bulgaria", + "Република България" + ], + "subregion": "Eastern Europe", + "region": "Europe", + "population": 6927288, + "latlng": [ + 43.0, + 25.0 + ], + "demonym": "Bulgarian", + "area": 110879.0, + "gini": 41.3, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "GRC", + "MKD", + "ROU", + "SRB", + "TUR" + ], + "nativeName": "България", + "numericCode": "100", + "flags": { + "svg": "https://flagcdn.com/bg.svg", + "png": "https://flagcdn.com/w320/bg.png" + }, + "currencies": [ + { + "code": "BGN", + "name": "Bulgarian lev", + "symbol": "лв" + } + ], + "languages": [ + { + "iso639_1": "bg", + "iso639_2": "bul", + "name": "Bulgarian", + "nativeName": "български език" + } + ], + "translations": { + "br": "Bulgaria", + "pt": "Bulgária", + "nl": "Bulgarije", + "hr": "Bugarska", + "fa": "بلغارستان", + "de": "Bulgarien", + "es": "Bulgaria", + "fr": "Bulgarie", + "ja": "ブルガリア", + "it": "Bulgaria", + "hu": "Bulgária" + }, + "flag": "https://flagcdn.com/bg.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "BUL", + "independent": true + }, + { + "name": "Burkina Faso", + "topLevelDomain": [ + ".bf" + ], + "alpha2Code": "BF", + "alpha3Code": "BFA", + "callingCodes": [ + "226" + ], + "capital": "Ouagadougou", + "altSpellings": [ + "BF" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 20903278, + "latlng": [ + 13.0, + -2.0 + ], + "demonym": "Burkinabe", + "area": 272967.0, + "gini": 35.3, + "timezones": [ + "UTC" + ], + "borders": [ + "BEN", + "CIV", + "GHA", + "MLI", + "NER", + "TGO" + ], + "nativeName": "Burkina Faso", + "numericCode": "854", + "flags": { + "svg": "https://flagcdn.com/bf.svg", + "png": "https://flagcdn.com/w320/bf.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "ff", + "iso639_2": "ful", + "name": "Fula", + "nativeName": "Fulfulde" + } + ], + "translations": { + "br": "Burkina Faso", + "pt": "Burquina Faso", + "nl": "Burkina Faso", + "hr": "Burkina Faso", + "fa": "بورکینافاسو", + "de": "Burkina Faso", + "es": "Burkina Faso", + "fr": "Burkina Faso", + "ja": "ブルキナファソ", + "it": "Burkina Faso", + "hu": "Burkina Faso" + }, + "flag": "https://flagcdn.com/bf.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "BUR", + "independent": true + }, + { + "name": "Burundi", + "topLevelDomain": [ + ".bi" + ], + "alpha2Code": "BI", + "alpha3Code": "BDI", + "callingCodes": [ + "257" + ], + "capital": "Gitega", + "altSpellings": [ + "BI", + "Republic of Burundi", + "Republika y'Uburundi", + "République du Burundi" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 11890781, + "latlng": [ + -3.5, + 30.0 + ], + "demonym": "Burundian", + "area": 27834.0, + "gini": 38.6, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "COD", + "RWA", + "TZA" + ], + "nativeName": "Burundi", + "numericCode": "108", + "flags": { + "svg": "https://flagcdn.com/bi.svg", + "png": "https://flagcdn.com/w320/bi.png" + }, + "currencies": [ + { + "code": "BIF", + "name": "Burundian franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "rn", + "iso639_2": "run", + "name": "Kirundi", + "nativeName": "Ikirundi" + } + ], + "translations": { + "br": "Burundi", + "pt": "Burúndi", + "nl": "Burundi", + "hr": "Burundi", + "fa": "بوروندی", + "de": "Burundi", + "es": "Burundi", + "fr": "Burundi", + "ja": "ブルンジ", + "it": "Burundi", + "hu": "Burundi" + }, + "flag": "https://flagcdn.com/bi.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "BDI", + "independent": true + }, + { + "name": "Cambodia", + "topLevelDomain": [ + ".kh" + ], + "alpha2Code": "KH", + "alpha3Code": "KHM", + "callingCodes": [ + "855" + ], + "capital": "Phnom Penh", + "altSpellings": [ + "KH", + "Kingdom of Cambodia" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 16718971, + "latlng": [ + 13.0, + 105.0 + ], + "demonym": "Cambodian", + "area": 181035.0, + "timezones": [ + "UTC+07:00" + ], + "borders": [ + "LAO", + "THA", + "VNM" + ], + "nativeName": "Kâmpŭchéa", + "numericCode": "116", + "flags": { + "svg": "https://flagcdn.com/kh.svg", + "png": "https://flagcdn.com/w320/kh.png" + }, + "currencies": [ + { + "code": "KHR", + "name": "Cambodian riel", + "symbol": "៛" + }, + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "km", + "iso639_2": "khm", + "name": "Khmer", + "nativeName": "ខ្មែរ" + } + ], + "translations": { + "br": "Kambodja", + "pt": "Camboja", + "nl": "Cambodja", + "hr": "Kambodža", + "fa": "کامبوج", + "de": "Kambodscha", + "es": "Camboya", + "fr": "Cambodge", + "ja": "カンボジア", + "it": "Cambogia", + "hu": "Kambodzsa" + }, + "flag": "https://flagcdn.com/kh.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "CAM", + "independent": true + }, + { + "name": "Cameroon", + "topLevelDomain": [ + ".cm" + ], + "alpha2Code": "CM", + "alpha3Code": "CMR", + "callingCodes": [ + "237" + ], + "capital": "Yaoundé", + "altSpellings": [ + "CM", + "Republic of Cameroon", + "République du Cameroun" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 26545864, + "latlng": [ + 6.0, + 12.0 + ], + "demonym": "Cameroonian", + "area": 475442.0, + "gini": 46.6, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "CAF", + "TCD", + "COG", + "GNQ", + "GAB", + "NGA" + ], + "nativeName": "Cameroon", + "numericCode": "120", + "flags": { + "svg": "https://flagcdn.com/cm.svg", + "png": "https://flagcdn.com/w320/cm.png" + }, + "currencies": [ + { + "code": "XAF", + "name": "Central African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Kameroun", + "pt": "Camarões", + "nl": "Kameroen", + "hr": "Kamerun", + "fa": "کامرون", + "de": "Kamerun", + "es": "Camerún", + "fr": "Cameroun", + "ja": "カメルーン", + "it": "Camerun", + "hu": "Kamerun" + }, + "flag": "https://flagcdn.com/cm.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "CMR", + "independent": true + }, + { + "name": "Canada", + "topLevelDomain": [ + ".ca" + ], + "alpha2Code": "CA", + "alpha3Code": "CAN", + "callingCodes": [ + "1" + ], + "capital": "Ottawa", + "altSpellings": [ + "CA" + ], + "subregion": "Northern America", + "region": "Americas", + "population": 38005238, + "latlng": [ + 60.0, + -95.0 + ], + "demonym": "Canadian", + "area": 9984670.0, + "gini": 33.3, + "timezones": [ + "UTC-08:00", + "UTC-07:00", + "UTC-06:00", + "UTC-05:00", + "UTC-04:00", + "UTC-03:30" + ], + "borders": [ + "USA" + ], + "nativeName": "Canada", + "numericCode": "124", + "flags": { + "svg": "https://flagcdn.com/ca.svg", + "png": "https://flagcdn.com/w320/ca.png" + }, + "currencies": [ + { + "code": "CAD", + "name": "Canadian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Kanada", + "pt": "Canadá", + "nl": "Canada", + "hr": "Kanada", + "fa": "کانادا", + "de": "Kanada", + "es": "Canadá", + "fr": "Canada", + "ja": "カナダ", + "it": "Canada", + "hu": "Kanada" + }, + "flag": "https://flagcdn.com/ca.svg", + "regionalBlocs": [ + { + "acronym": "NAFTA", + "name": "North American Free Trade Agreement", + "otherNames": [ + "Tratado de Libre Comercio de América del Norte", + "Accord de Libre-échange Nord-Américain" + ] + } + ], + "cioc": "CAN", + "independent": true + }, + { + "name": "Cabo Verde", + "topLevelDomain": [ + ".cv" + ], + "alpha2Code": "CV", + "alpha3Code": "CPV", + "callingCodes": [ + "238" + ], + "capital": "Praia", + "altSpellings": [ + "CV", + "Republic of Cabo Verde", + "República de Cabo Verde" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 555988, + "latlng": [ + 16.0, + -24.0 + ], + "demonym": "Cape Verdian", + "area": 4033.0, + "gini": 42.4, + "timezones": [ + "UTC-01:00" + ], + "nativeName": "Cabo Verde", + "numericCode": "132", + "flags": { + "svg": "https://flagcdn.com/cv.svg", + "png": "https://flagcdn.com/w320/cv.png" + }, + "currencies": [ + { + "code": "CVE", + "name": "Cape Verdean escudo", + "symbol": "Esc" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Kab Glas", + "pt": "Cabo Verde", + "nl": "Kaapverdië", + "hr": "Zelenortska Republika", + "fa": "کیپ ورد", + "de": "Kap Verde", + "es": "Cabo Verde", + "fr": "Cap Vert", + "ja": "カーボベルデ", + "it": "Capo Verde", + "hu": "Zöld-foki Köztársaság" + }, + "flag": "https://flagcdn.com/cv.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "CPV", + "independent": true + }, + { + "name": "Cayman Islands", + "topLevelDomain": [ + ".ky" + ], + "alpha2Code": "KY", + "alpha3Code": "CYM", + "callingCodes": [ + "1" + ], + "capital": "George Town", + "altSpellings": [ + "KY" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 65720, + "latlng": [ + 19.5, + -80.5 + ], + "demonym": "Caymanian", + "area": 264.0, + "timezones": [ + "UTC-05:00" + ], + "nativeName": "Cayman Islands", + "numericCode": "136", + "flags": { + "svg": "https://flagcdn.com/ky.svg", + "png": "https://flagcdn.com/w320/ky.png" + }, + "currencies": [ + { + "code": "KYD", + "name": "Cayman Islands dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Cayman", + "pt": "Ilhas Caimão", + "nl": "Caymaneilanden", + "hr": "Kajmanski otoci", + "fa": "جزایر کیمن", + "de": "Kaimaninseln", + "es": "Islas Caimán", + "fr": "Îles Caïmans", + "ja": "ケイマン諸島", + "it": "Isole Cayman", + "hu": "Kajmán-szigetek" + }, + "flag": "https://flagcdn.com/ky.svg", + "cioc": "CAY", + "independent": false + }, + { + "name": "Central African Republic", + "topLevelDomain": [ + ".cf" + ], + "alpha2Code": "CF", + "alpha3Code": "CAF", + "callingCodes": [ + "236" + ], + "capital": "Bangui", + "altSpellings": [ + "CF", + "Central African Republic", + "République centrafricaine" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 4829764, + "latlng": [ + 7.0, + 21.0 + ], + "demonym": "Central African", + "area": 622984.0, + "gini": 56.2, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "CMR", + "TCD", + "COD", + "COG", + "SSD", + "SDN" + ], + "nativeName": "Ködörösêse tî Bêafrîka", + "numericCode": "140", + "flags": { + "svg": "https://flagcdn.com/cf.svg", + "png": "https://flagcdn.com/w320/cf.png" + }, + "currencies": [ + { + "code": "XAF", + "name": "Central African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "sg", + "iso639_2": "sag", + "name": "Sango", + "nativeName": "yângâ tî sängö" + } + ], + "translations": { + "br": "Republik Kreizafrikan", + "pt": "República Centro-Africana", + "nl": "Centraal-Afrikaanse Republiek", + "hr": "Srednjoafrička Republika", + "fa": "جمهوری آفریقای مرکزی", + "de": "Zentralafrikanische Republik", + "es": "República Centroafricana", + "fr": "République centrafricaine", + "ja": "中央アフリカ共和国", + "it": "Repubblica Centrafricana", + "hu": "Közép-afrikai Köztársaság" + }, + "flag": "https://flagcdn.com/cf.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "CAF", + "independent": true + }, + { + "name": "Chad", + "topLevelDomain": [ + ".td" + ], + "alpha2Code": "TD", + "alpha3Code": "TCD", + "callingCodes": [ + "235" + ], + "capital": "N'Djamena", + "altSpellings": [ + "TD", + "Tchad", + "Republic of Chad", + "République du Tchad" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 16425859, + "latlng": [ + 15.0, + 19.0 + ], + "demonym": "Chadian", + "area": 1284000.0, + "gini": 43.3, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "CMR", + "CAF", + "LBY", + "NER", + "NGA", + "SDN" + ], + "nativeName": "Tchad", + "numericCode": "148", + "flags": { + "svg": "https://flagcdn.com/td.svg", + "png": "https://flagcdn.com/w320/td.png" + }, + "currencies": [ + { + "code": "XAF", + "name": "Central African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Tchad", + "pt": "Chade", + "nl": "Tsjaad", + "hr": "Čad", + "fa": "چاد", + "de": "Tschad", + "es": "Chad", + "fr": "Tchad", + "ja": "チャド", + "it": "Ciad", + "hu": "Csád" + }, + "flag": "https://flagcdn.com/td.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "CHA", + "independent": true + }, + { + "name": "Chile", + "topLevelDomain": [ + ".cl" + ], + "alpha2Code": "CL", + "alpha3Code": "CHL", + "callingCodes": [ + "56" + ], + "capital": "Santiago", + "altSpellings": [ + "CL", + "Republic of Chile", + "República de Chile" + ], + "subregion": "South America", + "region": "Americas", + "population": 19116209, + "latlng": [ + -30.0, + -71.0 + ], + "demonym": "Chilean", + "area": 756102.0, + "gini": 44.4, + "timezones": [ + "UTC-06:00", + "UTC-04:00" + ], + "borders": [ + "ARG", + "BOL", + "PER" + ], + "nativeName": "Chile", + "numericCode": "152", + "flags": { + "svg": "https://flagcdn.com/cl.svg", + "png": "https://flagcdn.com/w320/cl.png" + }, + "currencies": [ + { + "code": "CLP", + "name": "Chilean peso", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Chile", + "pt": "Chile", + "nl": "Chili", + "hr": "Čile", + "fa": "شیلی", + "de": "Chile", + "es": "Chile", + "fr": "Chili", + "ja": "チリ", + "it": "Cile", + "hu": "Chile" + }, + "flag": "https://flagcdn.com/cl.svg", + "regionalBlocs": [ + { + "acronym": "PA", + "name": "Pacific Alliance", + "otherNames": [ + "Alianza del Pacífico" + ] + }, + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "CHI", + "independent": true + }, + { + "name": "China", + "topLevelDomain": [ + ".cn" + ], + "alpha2Code": "CN", + "alpha3Code": "CHN", + "callingCodes": [ + "86" + ], + "capital": "Beijing", + "altSpellings": [ + "CN", + "Zhōngguó", + "Zhongguo", + "Zhonghua", + "People's Republic of China", + "中华人民共和国", + "Zhōnghuá Rénmín Gònghéguó" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 1402112000, + "latlng": [ + 35.0, + 105.0 + ], + "demonym": "Chinese", + "area": 9640011.0, + "gini": 38.5, + "timezones": [ + "UTC+08:00" + ], + "borders": [ + "AFG", + "BTN", + "MMR", + "HKG", + "IND", + "KAZ", + "PRK", + "KGZ", + "LAO", + "MAC", + "MNG", + "PAK", + "RUS", + "TJK", + "VNM", + "NPL" + ], + "nativeName": "中国", + "numericCode": "156", + "flags": { + "svg": "https://flagcdn.com/cn.svg", + "png": "https://flagcdn.com/w320/cn.png" + }, + "currencies": [ + { + "code": "CNY", + "name": "Chinese yuan", + "symbol": "¥" + } + ], + "languages": [ + { + "iso639_1": "zh", + "iso639_2": "zho", + "name": "Chinese", + "nativeName": "中文 (Zhōngwén)" + } + ], + "translations": { + "br": "Sina", + "pt": "China", + "nl": "China", + "hr": "Kina", + "fa": "چین", + "de": "China", + "es": "China", + "fr": "Chine", + "ja": "中国", + "it": "Cina", + "hu": "Kína" + }, + "flag": "https://flagcdn.com/cn.svg", + "cioc": "CHN", + "independent": true + }, + { + "name": "Christmas Island", + "topLevelDomain": [ + ".cx" + ], + "alpha2Code": "CX", + "alpha3Code": "CXR", + "callingCodes": [ + "61" + ], + "capital": "Flying Fish Cove", + "altSpellings": [ + "CX", + "Territory of Christmas Island" + ], + "subregion": "Australia and New Zealand", + "region": "Oceania", + "population": 2072, + "latlng": [ + -10.5, + 105.66666666 + ], + "demonym": "Christmas Island", + "area": 135.0, + "timezones": [ + "UTC+07:00" + ], + "nativeName": "Christmas Island", + "numericCode": "162", + "flags": { + "svg": "https://flagcdn.com/cx.svg", + "png": "https://flagcdn.com/w320/cx.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Enez Christmas", + "pt": "Ilha do Natal", + "nl": "Christmaseiland", + "hr": "Božićni otok", + "fa": "جزیره کریسمس", + "de": "Weihnachtsinsel", + "es": "Isla de Navidad", + "fr": "Île Christmas", + "ja": "クリスマス島", + "it": "Isola di Natale", + "hu": "Karácsony-sziget" + }, + "flag": "https://flagcdn.com/cx.svg", + "independent": false + }, + { + "name": "Cocos (Keeling) Islands", + "topLevelDomain": [ + ".cc" + ], + "alpha2Code": "CC", + "alpha3Code": "CCK", + "callingCodes": [ + "61" + ], + "capital": "West Island", + "altSpellings": [ + "CC", + "Territory of the Cocos (Keeling) Islands", + "Keeling Islands" + ], + "subregion": "Australia and New Zealand", + "region": "Oceania", + "population": 550, + "latlng": [ + -12.5, + 96.83333333 + ], + "demonym": "Cocos Islander", + "area": 14.0, + "timezones": [ + "UTC+06:30" + ], + "nativeName": "Cocos (Keeling) Islands", + "numericCode": "166", + "flags": { + "svg": "https://flagcdn.com/cc.svg", + "png": "https://flagcdn.com/w320/cc.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Cocos (Keeling)", + "pt": "Ilhas dos Cocos", + "nl": "Cocoseilanden", + "hr": "Kokosovi Otoci", + "fa": "جزایر کوکوس", + "de": "Kokosinseln", + "es": "Islas Cocos o Islas Keeling", + "fr": "Îles Cocos", + "ja": "ココス(キーリング)諸島", + "it": "Isole Cocos e Keeling", + "hu": "Kókusz-szigetek" + }, + "flag": "https://flagcdn.com/cc.svg", + "independent": false + }, + { + "name": "Colombia", + "topLevelDomain": [ + ".co" + ], + "alpha2Code": "CO", + "alpha3Code": "COL", + "callingCodes": [ + "57" + ], + "capital": "Bogotá", + "altSpellings": [ + "CO", + "Republic of Colombia", + "República de Colombia" + ], + "subregion": "South America", + "region": "Americas", + "population": 50882884, + "latlng": [ + 4.0, + -72.0 + ], + "demonym": "Colombian", + "area": 1141748.0, + "gini": 51.3, + "timezones": [ + "UTC-05:00" + ], + "borders": [ + "BRA", + "ECU", + "PAN", + "PER", + "VEN" + ], + "nativeName": "Colombia", + "numericCode": "170", + "flags": { + "svg": "https://flagcdn.com/co.svg", + "png": "https://flagcdn.com/w320/co.png" + }, + "currencies": [ + { + "code": "COP", + "name": "Colombian peso", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Kolombia", + "pt": "Colômbia", + "nl": "Colombia", + "hr": "Kolumbija", + "fa": "کلمبیا", + "de": "Kolumbien", + "es": "Colombia", + "fr": "Colombie", + "ja": "コロンビア", + "it": "Colombia", + "hu": "Kolumbia" + }, + "flag": "https://flagcdn.com/co.svg", + "regionalBlocs": [ + { + "acronym": "PA", + "name": "Pacific Alliance", + "otherNames": [ + "Alianza del Pacífico" + ] + }, + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "COL", + "independent": true + }, + { + "name": "Comoros", + "topLevelDomain": [ + ".km" + ], + "alpha2Code": "KM", + "alpha3Code": "COM", + "callingCodes": [ + "269" + ], + "capital": "Moroni", + "altSpellings": [ + "KM", + "Union of the Comoros", + "Union des Comores", + "Udzima wa Komori", + "al-Ittiḥād al-Qumurī" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 869595, + "latlng": [ + -12.16666666, + 44.25 + ], + "demonym": "Comoran", + "area": 1862.0, + "gini": 45.3, + "timezones": [ + "UTC+03:00" + ], + "nativeName": "Komori", + "numericCode": "174", + "flags": { + "svg": "https://flagcdn.com/km.svg", + "png": "https://flagcdn.com/w320/km.png" + }, + "currencies": [ + { + "code": "KMF", + "name": "Comorian franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Komorez", + "pt": "Comores", + "nl": "Comoren", + "hr": "Komori", + "fa": "کومور", + "de": "Union der Komoren", + "es": "Comoras", + "fr": "Comores", + "ja": "コモロ", + "it": "Comore", + "hu": "Comore-szigetek" + }, + "flag": "https://flagcdn.com/km.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "COM", + "independent": true + }, + { + "name": "Congo", + "topLevelDomain": [ + ".cg" + ], + "alpha2Code": "CG", + "alpha3Code": "COG", + "callingCodes": [ + "242" + ], + "capital": "Brazzaville", + "altSpellings": [ + "CG", + "Congo-Brazzaville" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 5518092, + "latlng": [ + -1.0, + 15.0 + ], + "demonym": "Congolese", + "area": 342000.0, + "gini": 48.9, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AGO", + "CMR", + "CAF", + "COD", + "GAB" + ], + "nativeName": "République du Congo", + "numericCode": "178", + "flags": { + "svg": "https://flagcdn.com/cg.svg", + "png": "https://flagcdn.com/w320/cg.png" + }, + "currencies": [ + { + "code": "XAF", + "name": "Central African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "ln", + "iso639_2": "lin", + "name": "Lingala", + "nativeName": "Lingála" + } + ], + "translations": { + "br": "Kongo-Brazzaville", + "pt": "Congo", + "nl": "Congo [Republiek]", + "hr": "Kongo", + "fa": "کنگو", + "de": "Kongo", + "es": "Congo", + "fr": "Congo", + "ja": "コンゴ共和国", + "it": "Congo", + "hu": "Kongói Köztársaság" + }, + "flag": "https://flagcdn.com/cg.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "CGO", + "independent": true + }, + { + "name": "Congo (Democratic Republic of the)", + "topLevelDomain": [ + ".cd" + ], + "alpha2Code": "CD", + "alpha3Code": "COD", + "callingCodes": [ + "243" + ], + "capital": "Kinshasa", + "altSpellings": [ + "CD", + "DR Congo", + "Congo-Kinshasa", + "DRC" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 89561404, + "latlng": [ + 0.0, + 25.0 + ], + "demonym": "Congolese", + "area": 2344858.0, + "gini": 42.1, + "timezones": [ + "UTC+01:00", + "UTC+02:00" + ], + "borders": [ + "AGO", + "BDI", + "CAF", + "COG", + "RWA", + "SSD", + "TZA", + "UGA", + "ZMB" + ], + "nativeName": "République démocratique du Congo", + "numericCode": "180", + "flags": { + "svg": "https://flagcdn.com/cd.svg", + "png": "https://flagcdn.com/w320/cd.png" + }, + "currencies": [ + { + "code": "CDF", + "name": "Congolese franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "ln", + "iso639_2": "lin", + "name": "Lingala", + "nativeName": "Lingála" + }, + { + "iso639_1": "kg", + "iso639_2": "kon", + "name": "Kongo", + "nativeName": "Kikongo" + }, + { + "iso639_1": "sw", + "iso639_2": "swa", + "name": "Swahili", + "nativeName": "Kiswahili" + }, + { + "iso639_1": "lu", + "iso639_2": "lub", + "name": "Luba-Katanga", + "nativeName": "Tshiluba" + } + ], + "translations": { + "br": "Kongo-Kinshasa", + "pt": "RD Congo", + "nl": "Congo [DRC]", + "hr": "Kongo, Demokratska Republika", + "fa": "جمهوری کنگو", + "de": "Kongo (Dem. Rep.)", + "es": "Congo (Rep. Dem.)", + "fr": "Congo (Rép. dém.)", + "ja": "コンゴ民主共和国", + "it": "Congo (Rep. Dem.)", + "hu": "Kongói Demokratikus Köztársaság" + }, + "flag": "https://flagcdn.com/cd.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "COD", + "independent": true + }, + { + "name": "Cook Islands", + "topLevelDomain": [ + ".ck" + ], + "alpha2Code": "CK", + "alpha3Code": "COK", + "callingCodes": [ + "682" + ], + "capital": "Avarua", + "altSpellings": [ + "CK", + "Kūki 'Āirani" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 18100, + "latlng": [ + -21.23333333, + -159.76666666 + ], + "demonym": "Cook Islander", + "area": 236.0, + "timezones": [ + "UTC-10:00" + ], + "nativeName": "Cook Islands", + "numericCode": "184", + "flags": { + "svg": "https://flagcdn.com/ck.svg", + "png": "https://flagcdn.com/w320/ck.png" + }, + "currencies": [ + { + "code": "NZD", + "name": "New Zealand dollar", + "symbol": "$" + }, + { + "code": "CKD", + "name": "Cook Islands dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_2": "rar", + "name": "Cook Islands Māori", + "nativeName": "Māori" + } + ], + "translations": { + "br": "Inizi Cook", + "pt": "Ilhas Cook", + "nl": "Cookeilanden", + "hr": "Cookovo Otočje", + "fa": "جزایر کوک", + "de": "Cookinseln", + "es": "Islas Cook", + "fr": "Îles Cook", + "ja": "クック諸島", + "it": "Isole Cook", + "hu": "Cook-szigetek" + }, + "flag": "https://flagcdn.com/ck.svg", + "cioc": "COK", + "independent": true + }, + { + "name": "Costa Rica", + "topLevelDomain": [ + ".cr" + ], + "alpha2Code": "CR", + "alpha3Code": "CRI", + "callingCodes": [ + "506" + ], + "capital": "San José", + "altSpellings": [ + "CR", + "Republic of Costa Rica", + "República de Costa Rica" + ], + "subregion": "Central America", + "region": "Americas", + "population": 5094114, + "latlng": [ + 10.0, + -84.0 + ], + "demonym": "Costa Rican", + "area": 51100.0, + "gini": 48.2, + "timezones": [ + "UTC-06:00" + ], + "borders": [ + "NIC", + "PAN" + ], + "nativeName": "Costa Rica", + "numericCode": "188", + "flags": { + "svg": "https://flagcdn.com/cr.svg", + "png": "https://flagcdn.com/w320/cr.png" + }, + "currencies": [ + { + "code": "CRC", + "name": "Costa Rican colón", + "symbol": "₡" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Costa Rica", + "pt": "Costa Rica", + "nl": "Costa Rica", + "hr": "Kostarika", + "fa": "کاستاریکا", + "de": "Costa Rica", + "es": "Costa Rica", + "fr": "Costa Rica", + "ja": "コスタリカ", + "it": "Costa Rica", + "hu": "Costa Rica" + }, + "flag": "https://flagcdn.com/cr.svg", + "regionalBlocs": [ + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "CRC", + "independent": true + }, + { + "name": "Croatia", + "topLevelDomain": [ + ".hr" + ], + "alpha2Code": "HR", + "alpha3Code": "HRV", + "callingCodes": [ + "385" + ], + "capital": "Zagreb", + "altSpellings": [ + "HR", + "Hrvatska", + "Republic of Croatia", + "Republika Hrvatska" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 4047200, + "latlng": [ + 45.16666666, + 15.5 + ], + "demonym": "Croatian", + "area": 56594.0, + "gini": 29.7, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "BIH", + "HUN", + "MNE", + "SRB", + "SVN" + ], + "nativeName": "Hrvatska", + "numericCode": "191", + "flags": { + "svg": "https://flagcdn.com/hr.svg", + "png": "https://flagcdn.com/w320/hr.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "hr", + "iso639_2": "hrv", + "name": "Croatian", + "nativeName": "hrvatski jezik" + } + ], + "translations": { + "br": "Kroatia", + "pt": "Croácia", + "nl": "Kroatië", + "hr": "Hrvatska", + "fa": "کرواسی", + "de": "Kroatien", + "es": "Croacia", + "fr": "Croatie", + "ja": "クロアチア", + "it": "Croazia", + "hu": "Horvátország" + }, + "flag": "https://flagcdn.com/hr.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "CRO", + "independent": true + }, + { + "name": "Cuba", + "topLevelDomain": [ + ".cu" + ], + "alpha2Code": "CU", + "alpha3Code": "CUB", + "callingCodes": [ + "53" + ], + "capital": "Havana", + "altSpellings": [ + "CU", + "Republic of Cuba", + "República de Cuba" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 11326616, + "latlng": [ + 21.5, + -80.0 + ], + "demonym": "Cuban", + "area": 109884.0, + "timezones": [ + "UTC-05:00" + ], + "nativeName": "Cuba", + "numericCode": "192", + "flags": { + "svg": "https://flagcdn.com/cu.svg", + "png": "https://flagcdn.com/w320/cu.png" + }, + "currencies": [ + { + "code": "CUC", + "name": "Cuban convertible peso", + "symbol": "$" + }, + { + "code": "CUP", + "name": "Cuban peso", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Kuba", + "pt": "Cuba", + "nl": "Cuba", + "hr": "Kuba", + "fa": "کوبا", + "de": "Kuba", + "es": "Cuba", + "fr": "Cuba", + "ja": "キューバ", + "it": "Cuba", + "hu": "Kuba" + }, + "flag": "https://flagcdn.com/cu.svg", + "cioc": "CUB", + "independent": true + }, + { + "name": "Curaçao", + "topLevelDomain": [ + ".cw" + ], + "alpha2Code": "CW", + "alpha3Code": "CUW", + "callingCodes": [ + "599" + ], + "capital": "Willemstad", + "altSpellings": [ + "CW", + "Curacao", + "Kòrsou", + "Country of Curaçao", + "Land Curaçao", + "Pais Kòrsou" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 155014, + "latlng": [ + 12.116667, + -68.933333 + ], + "demonym": "Dutch", + "area": 444.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Curaçao", + "numericCode": "531", + "flags": { + "svg": "https://flagcdn.com/cw.svg", + "png": "https://flagcdn.com/w320/cw.png" + }, + "currencies": [ + { + "code": "ANG", + "name": "Netherlands Antillean guilder", + "symbol": "ƒ" + } + ], + "languages": [ + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + }, + { + "iso639_1": "pa", + "iso639_2": "pan", + "name": "(Eastern) Punjabi", + "nativeName": "ਪੰਜਾਬੀ" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Curaçao", + "pt": "Curaçao", + "nl": "Curaçao", + "hr": "Curaçao", + "fa": "کوراسائو", + "de": "Curaçao", + "es": "Curaçao", + "fr": "Curaçao", + "ja": "Curaçao", + "it": "Curaçao", + "hu": "Curaçao" + }, + "flag": "https://flagcdn.com/cw.svg", + "independent": false + }, + { + "name": "Cyprus", + "topLevelDomain": [ + ".cy" + ], + "alpha2Code": "CY", + "alpha3Code": "CYP", + "callingCodes": [ + "357" + ], + "capital": "Nicosia", + "altSpellings": [ + "CY", + "Kýpros", + "Kıbrıs", + "Republic of Cyprus", + "Κυπριακή Δημοκρατία", + "Kıbrıs Cumhuriyeti" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 1207361, + "latlng": [ + 35.0, + 33.0 + ], + "demonym": "Cypriot", + "area": 9251.0, + "gini": 32.7, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "GBR" + ], + "nativeName": "Κύπρος", + "numericCode": "196", + "flags": { + "svg": "https://flagcdn.com/cy.svg", + "png": "https://flagcdn.com/w320/cy.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "el", + "iso639_2": "ell", + "name": "Greek (modern)", + "nativeName": "ελληνικά" + }, + { + "iso639_1": "tr", + "iso639_2": "tur", + "name": "Turkish", + "nativeName": "Türkçe" + }, + { + "iso639_1": "hy", + "iso639_2": "hye", + "name": "Armenian", + "nativeName": "Հայերեն" + } + ], + "translations": { + "br": "Kiprenez", + "pt": "Chipre", + "nl": "Cyprus", + "hr": "Cipar", + "fa": "قبرس", + "de": "Zypern", + "es": "Chipre", + "fr": "Chypre", + "ja": "キプロス", + "it": "Cipro", + "hu": "Ciprus" + }, + "flag": "https://flagcdn.com/cy.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "CYP", + "independent": true + }, + { + "name": "Czech Republic", + "topLevelDomain": [ + ".cz" + ], + "alpha2Code": "CZ", + "alpha3Code": "CZE", + "callingCodes": [ + "420" + ], + "capital": "Prague", + "altSpellings": [ + "CZ", + "Česká republika", + "Česko" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 10698896, + "latlng": [ + 49.75, + 15.5 + ], + "demonym": "Czech", + "area": 78865.0, + "gini": 25.0, + "timezones": [ + "UTC+01:00" + ], + "nativeName": "Česká republika", + "numericCode": "203", + "flags": { + "svg": "https://flagcdn.com/cz.svg", + "png": "https://flagcdn.com/w320/cz.png" + }, + "currencies": [ + { + "code": "CZK", + "name": "Czech koruna", + "symbol": "Kč" + } + ], + "languages": [ + { + "iso639_1": "cs", + "iso639_2": "ces", + "name": "Czech", + "nativeName": "čeština" + }, + { + "iso639_1": "sk", + "iso639_2": "slk", + "name": "Slovak", + "nativeName": "slovenčina" + } + ], + "translations": { + "br": "Tchekia", + "pt": "República Checa", + "nl": "Tsjechië", + "hr": "Češka", + "fa": "جمهوری چک", + "de": "Tschechische Republik", + "es": "República Checa", + "fr": "République tchèque", + "ja": "チェコ", + "it": "Repubblica Ceca", + "hu": "Csehország" + }, + "flag": "https://flagcdn.com/cz.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "CZE", + "independent": true + }, + { + "name": "Denmark", + "topLevelDomain": [ + ".dk" + ], + "alpha2Code": "DK", + "alpha3Code": "DNK", + "callingCodes": [ + "45" + ], + "capital": "Copenhagen", + "altSpellings": [ + "DK", + "Danmark", + "Kingdom of Denmark", + "Kongeriget Danmark" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 5831404, + "latlng": [ + 56.0, + 10.0 + ], + "demonym": "Danish", + "area": 43094.0, + "gini": 28.2, + "timezones": [ + "UTC-04:00", + "UTC-03:00", + "UTC-01:00", + "UTC", + "UTC+01:00" + ], + "borders": [ + "DEU" + ], + "nativeName": "Danmark", + "numericCode": "208", + "flags": { + "svg": "https://flagcdn.com/dk.svg", + "png": "https://flagcdn.com/w320/dk.png" + }, + "currencies": [ + { + "code": "DKK", + "name": "Danish krone", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "da", + "iso639_2": "dan", + "name": "Danish", + "nativeName": "dansk" + } + ], + "translations": { + "br": "Danmark", + "pt": "Dinamarca", + "nl": "Denemarken", + "hr": "Danska", + "fa": "دانمارک", + "de": "Dänemark", + "es": "Dinamarca", + "fr": "Danemark", + "ja": "デンマーク", + "it": "Danimarca", + "hu": "Dánia" + }, + "flag": "https://flagcdn.com/dk.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "DEN", + "independent": true + }, + { + "name": "Djibouti", + "topLevelDomain": [ + ".dj" + ], + "alpha2Code": "DJ", + "alpha3Code": "DJI", + "callingCodes": [ + "253" + ], + "capital": "Djibouti", + "altSpellings": [ + "DJ", + "Jabuuti", + "Gabuuti", + "Republic of Djibouti", + "République de Djibouti", + "Gabuutih Ummuuno", + "Jamhuuriyadda Jabuuti" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 988002, + "latlng": [ + 11.5, + 43.0 + ], + "demonym": "Djibouti", + "area": 23200.0, + "gini": 41.6, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "ERI", + "ETH", + "SOM" + ], + "nativeName": "Djibouti", + "numericCode": "262", + "flags": { + "svg": "https://flagcdn.com/dj.svg", + "png": "https://flagcdn.com/w320/dj.png" + }, + "currencies": [ + { + "code": "DJF", + "name": "Djiboutian franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Djibouti", + "pt": "Djibuti", + "nl": "Djibouti", + "hr": "Džibuti", + "fa": "جیبوتی", + "de": "Dschibuti", + "es": "Yibuti", + "fr": "Djibouti", + "ja": "ジブチ", + "it": "Gibuti", + "hu": "Dzsibuti" + }, + "flag": "https://flagcdn.com/dj.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "DJI", + "independent": true + }, + { + "name": "Dominica", + "topLevelDomain": [ + ".dm" + ], + "alpha2Code": "DM", + "alpha3Code": "DMA", + "callingCodes": [ + "1" + ], + "capital": "Roseau", + "altSpellings": [ + "DM", + "Dominique", + "Wai‘tu kubuli", + "Commonwealth of Dominica" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 71991, + "latlng": [ + 15.41666666, + -61.33333333 + ], + "demonym": "Dominican", + "area": 751.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Dominica", + "numericCode": "212", + "flags": { + "svg": "https://flagcdn.com/dm.svg", + "png": "https://flagcdn.com/w320/dm.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Dominika", + "pt": "Dominica", + "nl": "Dominica", + "hr": "Dominika", + "fa": "دومینیکا", + "de": "Dominica", + "es": "Dominica", + "fr": "Dominique", + "ja": "ドミニカ国", + "it": "Dominica", + "hu": "Dominikai Közösség" + }, + "flag": "https://flagcdn.com/dm.svg", + "cioc": "DMA", + "independent": true + }, + { + "name": "Dominican Republic", + "topLevelDomain": [ + ".do" + ], + "alpha2Code": "DO", + "alpha3Code": "DOM", + "callingCodes": [ + "1" + ], + "capital": "Santo Domingo", + "altSpellings": [ + "DO" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 10847904, + "latlng": [ + 19.0, + -70.66666666 + ], + "demonym": "Dominican", + "area": 48671.0, + "gini": 41.9, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "HTI" + ], + "nativeName": "República Dominicana", + "numericCode": "214", + "flags": { + "svg": "https://flagcdn.com/do.svg", + "png": "https://flagcdn.com/w320/do.png" + }, + "currencies": [ + { + "code": "DOP", + "name": "Dominican peso", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Republik Dominikan", + "pt": "República Dominicana", + "nl": "Dominicaanse Republiek", + "hr": "Dominikanska Republika", + "fa": "جمهوری دومینیکن", + "de": "Dominikanische Republik", + "es": "República Dominicana", + "fr": "République dominicaine", + "ja": "ドミニカ共和国", + "it": "Repubblica Dominicana", + "hu": "Dominikai Köztársaság" + }, + "flag": "https://flagcdn.com/do.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + }, + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "DOM", + "independent": true + }, + { + "name": "Ecuador", + "topLevelDomain": [ + ".ec" + ], + "alpha2Code": "EC", + "alpha3Code": "ECU", + "callingCodes": [ + "593" + ], + "capital": "Quito", + "altSpellings": [ + "EC", + "Republic of Ecuador", + "República del Ecuador" + ], + "subregion": "South America", + "region": "Americas", + "population": 17643060, + "latlng": [ + -2.0, + -77.5 + ], + "demonym": "Ecuadorean", + "area": 276841.0, + "gini": 45.7, + "timezones": [ + "UTC-06:00", + "UTC-05:00" + ], + "borders": [ + "COL", + "PER" + ], + "nativeName": "Ecuador", + "numericCode": "218", + "flags": { + "svg": "https://flagcdn.com/ec.svg", + "png": "https://flagcdn.com/w320/ec.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Ecuador", + "pt": "Equador", + "nl": "Ecuador", + "hr": "Ekvador", + "fa": "اکوادور", + "de": "Ecuador", + "es": "Ecuador", + "fr": "Équateur", + "ja": "エクアドル", + "it": "Ecuador", + "hu": "Ecuador" + }, + "flag": "https://flagcdn.com/ec.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "ECU", + "independent": true + }, + { + "name": "Egypt", + "topLevelDomain": [ + ".eg" + ], + "alpha2Code": "EG", + "alpha3Code": "EGY", + "callingCodes": [ + "20" + ], + "capital": "Cairo", + "altSpellings": [ + "EG", + "Arab Republic of Egypt" + ], + "subregion": "Northern Africa", + "region": "Africa", + "population": 102334403, + "latlng": [ + 27.0, + 30.0 + ], + "demonym": "Egyptian", + "area": 1002450.0, + "gini": 31.5, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "ISR", + "LBY", + "SDN" + ], + "nativeName": "مصر‎", + "numericCode": "818", + "flags": { + "svg": "https://flagcdn.com/eg.svg", + "png": "https://flagcdn.com/w320/eg.png" + }, + "currencies": [ + { + "code": "EGP", + "name": "Egyptian pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Egipt", + "pt": "Egipto", + "nl": "Egypte", + "hr": "Egipat", + "fa": "مصر", + "de": "Ägypten", + "es": "Egipto", + "fr": "Égypte", + "ja": "エジプト", + "it": "Egitto", + "hu": "Egyiptom" + }, + "flag": "https://flagcdn.com/eg.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "EGY", + "independent": true + }, + { + "name": "El Salvador", + "topLevelDomain": [ + ".sv" + ], + "alpha2Code": "SV", + "alpha3Code": "SLV", + "callingCodes": [ + "503" + ], + "capital": "San Salvador", + "altSpellings": [ + "SV", + "Republic of El Salvador", + "República de El Salvador" + ], + "subregion": "Central America", + "region": "Americas", + "population": 6486201, + "latlng": [ + 13.83333333, + -88.91666666 + ], + "demonym": "Salvadoran", + "area": 21041.0, + "gini": 38.8, + "timezones": [ + "UTC-06:00" + ], + "borders": [ + "GTM", + "HND" + ], + "nativeName": "El Salvador", + "numericCode": "222", + "flags": { + "svg": "https://flagcdn.com/sv.svg", + "png": "https://flagcdn.com/w320/sv.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "El Salvador", + "pt": "El Salvador", + "nl": "El Salvador", + "hr": "Salvador", + "fa": "السالوادور", + "de": "El Salvador", + "es": "El Salvador", + "fr": "Salvador", + "ja": "エルサルバドル", + "it": "El Salvador", + "hu": "Salvador" + }, + "flag": "https://flagcdn.com/sv.svg", + "regionalBlocs": [ + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "ESA", + "independent": true + }, + { + "name": "Equatorial Guinea", + "topLevelDomain": [ + ".gq" + ], + "alpha2Code": "GQ", + "alpha3Code": "GNQ", + "callingCodes": [ + "240" + ], + "capital": "Malabo", + "altSpellings": [ + "GQ", + "Republic of Equatorial Guinea", + "República de Guinea Ecuatorial", + "République de Guinée équatoriale", + "República da Guiné Equatorial" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 1402985, + "latlng": [ + 2.0, + 10.0 + ], + "demonym": "Equatorial Guinean", + "area": 28051.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "CMR", + "GAB" + ], + "nativeName": "Guinea Ecuatorial", + "numericCode": "226", + "flags": { + "svg": "https://flagcdn.com/gq.svg", + "png": "https://flagcdn.com/w320/gq.png" + }, + "currencies": [ + { + "code": "XAF", + "name": "Central African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + }, + { + "iso639_2": "fan", + "name": "Fang", + "nativeName": "Fang" + } + ], + "translations": { + "br": "Ginea ar C'heheder", + "pt": "Guiné Equatorial", + "nl": "Equatoriaal-Guinea", + "hr": "Ekvatorijalna Gvineja", + "fa": "گینه استوایی", + "de": "Äquatorial-Guinea", + "es": "Guinea Ecuatorial", + "fr": "Guinée-Équatoriale", + "ja": "赤道ギニア", + "it": "Guinea Equatoriale", + "hu": "Egyenlítői-Guinea" + }, + "flag": "https://flagcdn.com/gq.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "GEQ", + "independent": true + }, + { + "name": "Eritrea", + "topLevelDomain": [ + ".er" + ], + "alpha2Code": "ER", + "alpha3Code": "ERI", + "callingCodes": [ + "291" + ], + "capital": "Asmara", + "altSpellings": [ + "ER", + "State of Eritrea", + "ሃገረ ኤርትራ", + "Dawlat Iritriyá", + "ʾErtrā", + "Iritriyā", + "" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 5352000, + "latlng": [ + 15.0, + 39.0 + ], + "demonym": "Eritrean", + "area": 117600.0, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "DJI", + "ETH", + "SDN" + ], + "nativeName": "ኤርትራ", + "numericCode": "232", + "flags": { + "svg": "https://flagcdn.com/er.svg", + "png": "https://flagcdn.com/w320/er.png" + }, + "currencies": [ + { + "code": "ERN", + "name": "Eritrean nakfa", + "symbol": "Nfk" + } + ], + "languages": [ + { + "iso639_1": "ti", + "iso639_2": "tir", + "name": "Tigrinya", + "nativeName": "ትግርኛ" + }, + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_2": "tig", + "name": "Tigre", + "nativeName": "ትግረ" + }, + { + "iso639_2": "kun", + "name": "Kunama", + "nativeName": "Kunama" + }, + { + "iso639_2": "ssy", + "name": "Saho", + "nativeName": "Saho" + }, + { + "iso639_2": "byn", + "name": "Bilen", + "nativeName": "ብሊና" + }, + { + "iso639_2": "nrb", + "name": "Nara", + "nativeName": "Nara" + }, + { + "iso639_1": "aa", + "iso639_2": "aar", + "name": "Afar", + "nativeName": "Afar" + } + ], + "translations": { + "br": "Eritrea", + "pt": "Eritreia", + "nl": "Eritrea", + "hr": "Eritreja", + "fa": "اریتره", + "de": "Eritrea", + "es": "Eritrea", + "fr": "Érythrée", + "ja": "エリトリア", + "it": "Eritrea", + "hu": "Eritrea" + }, + "flag": "https://flagcdn.com/er.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "ERI", + "independent": true + }, + { + "name": "Estonia", + "topLevelDomain": [ + ".ee" + ], + "alpha2Code": "EE", + "alpha3Code": "EST", + "callingCodes": [ + "372" + ], + "capital": "Tallinn", + "altSpellings": [ + "EE", + "Eesti", + "Republic of Estonia", + "Eesti Vabariik" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 1331057, + "latlng": [ + 59.0, + 26.0 + ], + "demonym": "Estonian", + "area": 45227.0, + "gini": 30.3, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "LVA", + "RUS" + ], + "nativeName": "Eesti", + "numericCode": "233", + "flags": { + "svg": "https://flagcdn.com/ee.svg", + "png": "https://flagcdn.com/w320/ee.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "et", + "iso639_2": "est", + "name": "Estonian", + "nativeName": "eesti" + } + ], + "translations": { + "br": "Estonia", + "pt": "Estónia", + "nl": "Estland", + "hr": "Estonija", + "fa": "استونی", + "de": "Estland", + "es": "Estonia", + "fr": "Estonie", + "ja": "エストニア", + "it": "Estonia", + "hu": "Észtország" + }, + "flag": "https://flagcdn.com/ee.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "EST", + "independent": true + }, + { + "name": "Ethiopia", + "topLevelDomain": [ + ".et" + ], + "alpha2Code": "ET", + "alpha3Code": "ETH", + "callingCodes": [ + "251" + ], + "capital": "Addis Ababa", + "altSpellings": [ + "ET", + "ʾĪtyōṗṗyā", + "Federal Democratic Republic of Ethiopia", + "የኢትዮጵያ ፌዴራላዊ ዲሞክራሲያዊ ሪፐብሊክ" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 114963583, + "latlng": [ + 8.0, + 38.0 + ], + "demonym": "Ethiopian", + "area": 1104300.0, + "gini": 35.0, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "DJI", + "ERI", + "KEN", + "SOM", + "SSD", + "SDN" + ], + "nativeName": "ኢትዮጵያ", + "numericCode": "231", + "flags": { + "svg": "https://flagcdn.com/et.svg", + "png": "https://flagcdn.com/w320/et.png" + }, + "currencies": [ + { + "code": "ETB", + "name": "Ethiopian birr", + "symbol": "Br" + } + ], + "languages": [ + { + "iso639_1": "am", + "iso639_2": "amh", + "name": "Amharic", + "nativeName": "አማርኛ" + } + ], + "translations": { + "br": "Etiopia", + "pt": "Etiópia", + "nl": "Ethiopië", + "hr": "Etiopija", + "fa": "اتیوپی", + "de": "Äthiopien", + "es": "Etiopía", + "fr": "Éthiopie", + "ja": "エチオピア", + "it": "Etiopia", + "hu": "Etiópia" + }, + "flag": "https://flagcdn.com/et.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "ETH", + "independent": true + }, + { + "name": "Falkland Islands (Malvinas)", + "topLevelDomain": [ + ".fk" + ], + "alpha2Code": "FK", + "alpha3Code": "FLK", + "callingCodes": [ + "500" + ], + "capital": "Stanley", + "altSpellings": [ + "FK", + "Islas Malvinas" + ], + "subregion": "South America", + "region": "Americas", + "population": 2563, + "latlng": [ + -51.75, + -59.0 + ], + "demonym": "Falkland Islander", + "area": 12173.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Falkland Islands", + "numericCode": "238", + "flags": { + "svg": "https://flagcdn.com/fk.svg", + "png": "https://flagcdn.com/w320/fk.png" + }, + "currencies": [ + { + "code": "FKP", + "name": "Falkland Islands pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Maloù", + "pt": "Ilhas Falkland", + "nl": "Falklandeilanden [Islas Malvinas]", + "hr": "Falklandski Otoci", + "fa": "جزایر فالکلند", + "de": "Falklandinseln", + "es": "Islas Malvinas", + "fr": "Îles Malouines", + "ja": "フォークランド(マルビナス)諸島", + "it": "Isole Falkland o Isole Malvine", + "hu": "Falkland-szigetek" + }, + "flag": "https://flagcdn.com/fk.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "independent": false + }, + { + "name": "Faroe Islands", + "topLevelDomain": [ + ".fo" + ], + "alpha2Code": "FO", + "alpha3Code": "FRO", + "callingCodes": [ + "298" + ], + "capital": "Tórshavn", + "altSpellings": [ + "FO", + "Føroyar", + "Færøerne" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 48865, + "latlng": [ + 62.0, + -7.0 + ], + "demonym": "Faroese", + "area": 1393.0, + "timezones": [ + "UTC+00:00" + ], + "nativeName": "Føroyar", + "numericCode": "234", + "flags": { + "svg": "https://flagcdn.com/fo.svg", + "png": "https://flagcdn.com/w320/fo.png" + }, + "currencies": [ + { + "code": "DKK", + "name": "Danish krone", + "symbol": "kr" + }, + { + "code": "FOK", + "name": "Faroese króna", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "fo", + "iso639_2": "fao", + "name": "Faroese", + "nativeName": "føroyskt" + } + ], + "translations": { + "br": "Inizi Faero", + "pt": "Ilhas Faroé", + "nl": "Faeröer", + "hr": "Farski Otoci", + "fa": "جزایر فارو", + "de": "Färöer-Inseln", + "es": "Islas Faroe", + "fr": "Îles Féroé", + "ja": "フェロー諸島", + "it": "Isole Far Oer", + "hu": "Feröer" + }, + "flag": "https://flagcdn.com/fo.svg", + "independent": false + }, + { + "name": "Fiji", + "topLevelDomain": [ + ".fj" + ], + "alpha2Code": "FJ", + "alpha3Code": "FJI", + "callingCodes": [ + "679" + ], + "capital": "Suva", + "altSpellings": [ + "FJ", + "Viti", + "Republic of Fiji", + "Matanitu ko Viti", + "Fijī Gaṇarājya" + ], + "subregion": "Melanesia", + "region": "Oceania", + "population": 896444, + "latlng": [ + -18.0, + 175.0 + ], + "demonym": "Fijian", + "area": 18272.0, + "gini": 36.7, + "timezones": [ + "UTC+12:00" + ], + "nativeName": "Fiji", + "numericCode": "242", + "flags": { + "svg": "https://flagcdn.com/fj.svg", + "png": "https://flagcdn.com/w320/fj.png" + }, + "currencies": [ + { + "code": "FJD", + "name": "Fijian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fj", + "iso639_2": "fij", + "name": "Fijian", + "nativeName": "vosa Vakaviti" + }, + { + "iso639_2": "hif", + "name": "Fiji Hindi", + "nativeName": "फ़िजी बात" + }, + { + "iso639_2": "rtm", + "name": "Rotuman", + "nativeName": "Fäeag Rotuma" + } + ], + "translations": { + "br": "Fidji", + "pt": "Fiji", + "nl": "Fiji", + "hr": "Fiđi", + "fa": "فیجی", + "de": "Fidschi", + "es": "Fiyi", + "fr": "Fidji", + "ja": "フィジー", + "it": "Figi", + "hu": "Fidzsi-szigetek" + }, + "flag": "https://flagcdn.com/fj.svg", + "cioc": "FIJ", + "independent": true + }, + { + "name": "Finland", + "topLevelDomain": [ + ".fi" + ], + "alpha2Code": "FI", + "alpha3Code": "FIN", + "callingCodes": [ + "358" + ], + "capital": "Helsinki", + "altSpellings": [ + "FI", + "Suomi", + "Republic of Finland", + "Suomen tasavalta", + "Republiken Finland" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 5530719, + "latlng": [ + 64.0, + 26.0 + ], + "demonym": "Finnish", + "area": 338424.0, + "gini": 27.3, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "NOR", + "SWE", + "RUS" + ], + "nativeName": "Suomi", + "numericCode": "246", + "flags": { + "svg": "https://flagcdn.com/fi.svg", + "png": "https://flagcdn.com/w320/fi.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fi", + "iso639_2": "fin", + "name": "Finnish", + "nativeName": "suomi" + }, + { + "iso639_1": "sv", + "iso639_2": "swe", + "name": "Swedish", + "nativeName": "svenska" + } + ], + "translations": { + "br": "Finland", + "pt": "Finlândia", + "nl": "Finland", + "hr": "Finska", + "fa": "فنلاند", + "de": "Finnland", + "es": "Finlandia", + "fr": "Finlande", + "ja": "フィンランド", + "it": "Finlandia", + "hu": "Finnország" + }, + "flag": "https://flagcdn.com/fi.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "FIN", + "independent": true + }, + { + "name": "France", + "topLevelDomain": [ + ".fr" + ], + "alpha2Code": "FR", + "alpha3Code": "FRA", + "callingCodes": [ + "33" + ], + "capital": "Paris", + "altSpellings": [ + "FR", + "French Republic", + "République française" + ], + "subregion": "Western Europe", + "region": "Europe", + "population": 67391582, + "latlng": [ + 46.0, + 2.0 + ], + "demonym": "French", + "area": 640679.0, + "gini": 32.4, + "timezones": [ + "UTC-10:00", + "UTC-09:30", + "UTC-09:00", + "UTC-08:00", + "UTC-04:00", + "UTC-03:00", + "UTC+01:00", + "UTC+02:00", + "UTC+03:00", + "UTC+04:00", + "UTC+05:00", + "UTC+10:00", + "UTC+11:00", + "UTC+12:00" + ], + "borders": [ + "AND", + "BEL", + "DEU", + "ITA", + "LUX", + "MCO", + "ESP", + "CHE" + ], + "nativeName": "France", + "numericCode": "250", + "flags": { + "svg": "https://flagcdn.com/fr.svg", + "png": "https://flagcdn.com/w320/fr.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Frañs", + "pt": "França", + "nl": "Frankrijk", + "hr": "Francuska", + "fa": "فرانسه", + "de": "Frankreich", + "es": "Francia", + "fr": "France", + "ja": "フランス", + "it": "Francia", + "hu": "Franciaország" + }, + "flag": "https://flagcdn.com/fr.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "FRA", + "independent": true + }, + { + "name": "French Guiana", + "topLevelDomain": [ + ".gf" + ], + "alpha2Code": "GF", + "alpha3Code": "GUF", + "callingCodes": [ + "594" + ], + "capital": "Cayenne", + "altSpellings": [ + "GF", + "Guiana", + "Guyane" + ], + "subregion": "South America", + "region": "Americas", + "population": 254541, + "latlng": [ + 4.0, + -53.0 + ], + "demonym": "French Guianan", + "timezones": [ + "UTC-03:00" + ], + "borders": [ + "BRA", + "SUR" + ], + "nativeName": "Guyane française", + "numericCode": "254", + "flags": { + "svg": "https://flagcdn.com/gf.svg", + "png": "https://flagcdn.com/w320/gf.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Gwiana C'hall", + "pt": "Guiana Francesa", + "nl": "Frans-Guyana", + "hr": "Francuska Gvajana", + "fa": "گویان فرانسه", + "de": "Französisch Guyana", + "es": "Guayana Francesa", + "fr": "Guayane", + "ja": "フランス領ギアナ", + "it": "Guyana francese", + "hu": "Francia Guyana" + }, + "flag": "https://flagcdn.com/gf.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + }, + { + "acronym": "EU", + "name": "European Union" + } + ], + "independent": false + }, + { + "name": "French Polynesia", + "topLevelDomain": [ + ".pf" + ], + "alpha2Code": "PF", + "alpha3Code": "PYF", + "callingCodes": [ + "689" + ], + "capital": "Papeetē", + "altSpellings": [ + "PF", + "Polynésie française", + "French Polynesia", + "Pōrīnetia Farāni" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 280904, + "latlng": [ + -15.0, + -140.0 + ], + "demonym": "French Polynesian", + "area": 4167.0, + "timezones": [ + "UTC-10:00", + "UTC-09:30", + "UTC-09:00" + ], + "nativeName": "Polynésie française", + "numericCode": "258", + "flags": { + "svg": "https://flagcdn.com/pf.svg", + "png": "https://flagcdn.com/w320/pf.png" + }, + "currencies": [ + { + "code": "XPF", + "name": "CFP franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Polinezia C'hall", + "pt": "Polinésia Francesa", + "nl": "Frans-Polynesië", + "hr": "Francuska Polinezija", + "fa": "پلی‌نزی فرانسه", + "de": "Französisch-Polynesien", + "es": "Polinesia Francesa", + "fr": "Polynésie française", + "ja": "フランス領ポリネシア", + "it": "Polinesia Francese", + "hu": "Francia Polinézia" + }, + "flag": "https://flagcdn.com/pf.svg", + "independent": false + }, + { + "name": "French Southern Territories", + "topLevelDomain": [ + ".tf" + ], + "alpha2Code": "TF", + "alpha3Code": "ATF", + "callingCodes": [ + "262" + ], + "capital": "Port-aux-Français", + "altSpellings": [ + "TF" + ], + "subregion": "Southern Africa", + "region": "Africa", + "population": 140, + "latlng": [ + -49.25, + 69.167 + ], + "demonym": "French", + "area": 7747.0, + "timezones": [ + "UTC+05:00" + ], + "nativeName": "Territoire des Terres australes et antarctiques françaises", + "numericCode": "260", + "flags": { + "svg": "https://flagcdn.com/tf.svg", + "png": "https://flagcdn.com/w320/tf.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Douaroù Aostral hag Antarktikel Frañs", + "pt": "Terras Austrais e Antárticas Francesas", + "nl": "Franse Gebieden in de zuidelijke Indische Oceaan", + "hr": "Francuski južni i antarktički teritoriji", + "fa": "سرزمین‌های جنوبی و جنوبگانی فرانسه", + "de": "Französische Süd- und Antarktisgebiete", + "es": "Tierras Australes y Antárticas Francesas", + "fr": "Terres australes et antarctiques françaises", + "ja": "フランス領南方・南極地域", + "it": "Territori Francesi del Sud", + "hu": "Francia déli és antarktiszi területek" + }, + "flag": "https://flagcdn.com/tf.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "independent": false + }, + { + "name": "Gabon", + "topLevelDomain": [ + ".ga" + ], + "alpha2Code": "GA", + "alpha3Code": "GAB", + "callingCodes": [ + "241" + ], + "capital": "Libreville", + "altSpellings": [ + "GA", + "Gabonese Republic", + "République Gabonaise" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 2225728, + "latlng": [ + -1.0, + 11.75 + ], + "demonym": "Gabonese", + "area": 267668.0, + "gini": 38.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "CMR", + "COG", + "GNQ" + ], + "nativeName": "Gabon", + "numericCode": "266", + "flags": { + "svg": "https://flagcdn.com/ga.svg", + "png": "https://flagcdn.com/w320/ga.png" + }, + "currencies": [ + { + "code": "XAF", + "name": "Central African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Gabon", + "pt": "Gabão", + "nl": "Gabon", + "hr": "Gabon", + "fa": "گابن", + "de": "Gabun", + "es": "Gabón", + "fr": "Gabon", + "ja": "ガボン", + "it": "Gabon", + "hu": "Gabon" + }, + "flag": "https://flagcdn.com/ga.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "GAB", + "independent": true + }, + { + "name": "Gambia", + "topLevelDomain": [ + ".gm" + ], + "alpha2Code": "GM", + "alpha3Code": "GMB", + "callingCodes": [ + "220" + ], + "capital": "Banjul", + "altSpellings": [ + "GM", + "Republic of the Gambia" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 2416664, + "latlng": [ + 13.46666666, + -16.56666666 + ], + "demonym": "Gambian", + "area": 11295.0, + "gini": 35.9, + "timezones": [ + "UTC+00:00" + ], + "borders": [ + "SEN" + ], + "nativeName": "Gambia", + "numericCode": "270", + "flags": { + "svg": "https://flagcdn.com/gm.svg", + "png": "https://flagcdn.com/w320/gm.png" + }, + "currencies": [ + { + "code": "GMD", + "name": "Gambian dalasi", + "symbol": "D" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Gambia", + "pt": "Gâmbia", + "nl": "Gambia", + "hr": "Gambija", + "fa": "گامبیا", + "de": "Gambia", + "es": "Gambia", + "fr": "Gambie", + "ja": "ガンビア", + "it": "Gambia", + "hu": "Gambia" + }, + "flag": "https://flagcdn.com/gm.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "GAM", + "independent": true + }, + { + "name": "Georgia", + "topLevelDomain": [ + ".ge" + ], + "alpha2Code": "GE", + "alpha3Code": "GEO", + "callingCodes": [ + "995" + ], + "capital": "Tbilisi", + "altSpellings": [ + "GE", + "Sakartvelo" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 3714000, + "latlng": [ + 42.0, + 43.5 + ], + "demonym": "Georgian", + "area": 69700.0, + "gini": 35.9, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "ARM", + "AZE", + "RUS", + "TUR" + ], + "nativeName": "საქართველო", + "numericCode": "268", + "flags": { + "svg": "https://flagcdn.com/ge.svg", + "png": "https://flagcdn.com/w320/ge.png" + }, + "currencies": [ + { + "code": "GEL", + "name": "Georgian Lari", + "symbol": "ლ" + } + ], + "languages": [ + { + "iso639_1": "ka", + "iso639_2": "kat", + "name": "Georgian", + "nativeName": "ქართული" + } + ], + "translations": { + "br": "Jorjia", + "pt": "Geórgia", + "nl": "Georgië", + "hr": "Németország", + "fa": "گرجستان", + "de": "Georgien", + "es": "Georgia", + "fr": "Géorgie", + "ja": "グルジア", + "it": "Georgia", + "hu": "Grúzia" + }, + "flag": "https://flagcdn.com/ge.svg", + "cioc": "GEO", + "independent": true + }, + { + "name": "Germany", + "topLevelDomain": [ + ".de" + ], + "alpha2Code": "DE", + "alpha3Code": "DEU", + "callingCodes": [ + "49" + ], + "capital": "Berlin", + "altSpellings": [ + "DE", + "Federal Republic of Germany", + "Bundesrepublik Deutschland" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 83240525, + "latlng": [ + 51.0, + 9.0 + ], + "demonym": "German", + "area": 357114.0, + "gini": 31.9, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AUT", + "BEL", + "CZE", + "DNK", + "FRA", + "LUX", + "NLD", + "POL", + "CHE" + ], + "nativeName": "Deutschland", + "numericCode": "276", + "flags": { + "svg": "https://flagcdn.com/de.svg", + "png": "https://flagcdn.com/w320/de.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "de", + "iso639_2": "deu", + "name": "German", + "nativeName": "Deutsch" + } + ], + "translations": { + "br": "Alamagn", + "pt": "Alemanha", + "nl": "Duitsland", + "hr": "Njemačka", + "fa": "آلمان", + "de": "Deutschland", + "es": "Alemania", + "fr": "Allemagne", + "ja": "ドイツ", + "it": "Germania", + "hu": "Grúzia" + }, + "flag": "https://flagcdn.com/de.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "GER", + "independent": true + }, + { + "name": "Ghana", + "topLevelDomain": [ + ".gh" + ], + "alpha2Code": "GH", + "alpha3Code": "GHA", + "callingCodes": [ + "233" + ], + "capital": "Accra", + "altSpellings": [ + "GH" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 31072945, + "latlng": [ + 8.0, + -2.0 + ], + "demonym": "Ghanaian", + "area": 238533.0, + "gini": 43.5, + "timezones": [ + "UTC" + ], + "borders": [ + "BFA", + "CIV", + "TGO" + ], + "nativeName": "Ghana", + "numericCode": "288", + "flags": { + "svg": "https://flagcdn.com/gh.svg", + "png": "https://flagcdn.com/w320/gh.png" + }, + "currencies": [ + { + "code": "GHS", + "name": "Ghanaian cedi", + "symbol": "₵" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Ghana", + "pt": "Gana", + "nl": "Ghana", + "hr": "Gana", + "fa": "غنا", + "de": "Ghana", + "es": "Ghana", + "fr": "Ghana", + "ja": "ガーナ", + "it": "Ghana", + "hu": "Ghána" + }, + "flag": "https://flagcdn.com/gh.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "GHA", + "independent": true + }, + { + "name": "Gibraltar", + "topLevelDomain": [ + ".gi" + ], + "alpha2Code": "GI", + "alpha3Code": "GIB", + "callingCodes": [ + "350" + ], + "capital": "Gibraltar", + "altSpellings": [ + "GI" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 33691, + "latlng": [ + 36.13333333, + -5.35 + ], + "demonym": "Gibraltar", + "area": 6.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "ESP" + ], + "nativeName": "Gibraltar", + "numericCode": "292", + "flags": { + "svg": "https://flagcdn.com/gi.svg", + "png": "https://flagcdn.com/w320/gi.png" + }, + "currencies": [ + { + "code": "GIP", + "name": "Gibraltar pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Jibraltar", + "pt": "Gibraltar", + "nl": "Gibraltar", + "hr": "Gibraltar", + "fa": "جبل‌طارق", + "de": "Gibraltar", + "es": "Gibraltar", + "fr": "Gibraltar", + "ja": "ジブラルタル", + "it": "Gibilterra", + "hu": "Gibraltár" + }, + "flag": "https://flagcdn.com/gi.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "independent": false + }, + { + "name": "Greece", + "topLevelDomain": [ + ".gr" + ], + "alpha2Code": "GR", + "alpha3Code": "GRC", + "callingCodes": [ + "30" + ], + "capital": "Athens", + "altSpellings": [ + "GR", + "Elláda", + "Hellenic Republic", + "Ελληνική Δημοκρατία" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 10715549, + "latlng": [ + 39.0, + 22.0 + ], + "demonym": "Greek", + "area": 131990.0, + "gini": 32.9, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "ALB", + "BGR", + "TUR", + "MKD" + ], + "nativeName": "Ελλάδα", + "numericCode": "300", + "flags": { + "svg": "https://flagcdn.com/gr.svg", + "png": "https://flagcdn.com/w320/gr.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "el", + "iso639_2": "ell", + "name": "Greek (modern)", + "nativeName": "ελληνικά" + } + ], + "translations": { + "br": "Gres", + "pt": "Grécia", + "nl": "Griekenland", + "hr": "Grčka", + "fa": "یونان", + "de": "Griechenland", + "es": "Grecia", + "fr": "Grèce", + "ja": "ギリシャ", + "it": "Grecia", + "hu": "Görögország" + }, + "flag": "https://flagcdn.com/gr.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "GRE", + "independent": true + }, + { + "name": "Greenland", + "topLevelDomain": [ + ".gl" + ], + "alpha2Code": "GL", + "alpha3Code": "GRL", + "callingCodes": [ + "299" + ], + "capital": "Nuuk", + "altSpellings": [ + "GL", + "Grønland" + ], + "subregion": "Northern America", + "region": "Americas", + "population": 56367, + "latlng": [ + 72.0, + -40.0 + ], + "demonym": "Greenlandic", + "area": 2166086.0, + "timezones": [ + "UTC-04:00", + "UTC-03:00", + "UTC-01:00", + "UTC+00:00" + ], + "nativeName": "Kalaallit Nunaat", + "numericCode": "304", + "flags": { + "svg": "https://flagcdn.com/gl.svg", + "png": "https://flagcdn.com/w320/gl.png" + }, + "currencies": [ + { + "code": "DKK", + "name": "Danish krone", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "kl", + "iso639_2": "kal", + "name": "Greenlandic", + "nativeName": "kalaallisut" + } + ], + "translations": { + "br": "Greunland", + "pt": "Gronelândia", + "nl": "Groenland", + "hr": "Grenland", + "fa": "گرینلند", + "de": "Grönland", + "es": "Groenlandia", + "fr": "Groenland", + "ja": "グリーンランド", + "it": "Groenlandia", + "hu": "Grönland" + }, + "flag": "https://flagcdn.com/gl.svg", + "independent": false + }, + { + "name": "Grenada", + "topLevelDomain": [ + ".gd" + ], + "alpha2Code": "GD", + "alpha3Code": "GRD", + "callingCodes": [ + "1" + ], + "capital": "St. George's", + "altSpellings": [ + "GD" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 112519, + "latlng": [ + 12.11666666, + -61.66666666 + ], + "demonym": "Grenadian", + "area": 344.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Grenada", + "numericCode": "308", + "flags": { + "svg": "https://flagcdn.com/gd.svg", + "png": "https://flagcdn.com/w320/gd.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Grenada", + "pt": "Granada", + "nl": "Grenada", + "hr": "Grenada", + "fa": "گرنادا", + "de": "Grenada", + "es": "Grenada", + "fr": "Grenade", + "ja": "グレナダ", + "it": "Grenada", + "hu": "Grenada" + }, + "flag": "https://flagcdn.com/gd.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "GRN", + "independent": true + }, + { + "name": "Guadeloupe", + "topLevelDomain": [ + ".gp" + ], + "alpha2Code": "GP", + "alpha3Code": "GLP", + "callingCodes": [ + "590" + ], + "capital": "Basse-Terre", + "altSpellings": [ + "GP", + "Gwadloup" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 400132, + "latlng": [ + 16.25, + -61.583333 + ], + "demonym": "Guadeloupian", + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Guadeloupe", + "numericCode": "312", + "flags": { + "svg": "https://flagcdn.com/gp.svg", + "png": "https://flagcdn.com/w320/gp.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Gwadeloup", + "pt": "Guadalupe", + "nl": "Guadeloupe", + "hr": "Gvadalupa", + "fa": "جزیره گوادلوپ", + "de": "Guadeloupe", + "es": "Guadalupe", + "fr": "Guadeloupe", + "ja": "グアドループ", + "it": "Guadeloupa", + "hu": "Guadeloupe" + }, + "flag": "https://flagcdn.com/gp.svg", + "independent": false + }, + { + "name": "Guam", + "topLevelDomain": [ + ".gu" + ], + "alpha2Code": "GU", + "alpha3Code": "GUM", + "callingCodes": [ + "1" + ], + "capital": "Hagåtña", + "altSpellings": [ + "GU", + "Guåhån" + ], + "subregion": "Micronesia", + "region": "Oceania", + "population": 168783, + "latlng": [ + 13.46666666, + 144.78333333 + ], + "demonym": "Guamanian", + "area": 549.0, + "timezones": [ + "UTC+10:00" + ], + "nativeName": "Guam", + "numericCode": "316", + "flags": { + "svg": "https://flagcdn.com/gu.svg", + "png": "https://flagcdn.com/w320/gu.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "ch", + "iso639_2": "cha", + "name": "Chamorro", + "nativeName": "Chamoru" + }, + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Guam", + "pt": "Guame", + "nl": "Guam", + "hr": "Guam", + "fa": "گوام", + "de": "Guam", + "es": "Guam", + "fr": "Guam", + "ja": "グアム", + "it": "Guam", + "hu": "Guam" + }, + "flag": "https://flagcdn.com/gu.svg", + "cioc": "GUM", + "independent": false + }, + { + "name": "Guatemala", + "topLevelDomain": [ + ".gt" + ], + "alpha2Code": "GT", + "alpha3Code": "GTM", + "callingCodes": [ + "502" + ], + "capital": "Guatemala City", + "altSpellings": [ + "GT" + ], + "subregion": "Central America", + "region": "Americas", + "population": 16858333, + "latlng": [ + 15.5, + -90.25 + ], + "demonym": "Guatemalan", + "area": 108889.0, + "gini": 48.3, + "timezones": [ + "UTC-06:00" + ], + "borders": [ + "BLZ", + "SLV", + "HND", + "MEX" + ], + "nativeName": "Guatemala", + "numericCode": "320", + "flags": { + "svg": "https://flagcdn.com/gt.svg", + "png": "https://flagcdn.com/w320/gt.png" + }, + "currencies": [ + { + "code": "GTQ", + "name": "Guatemalan quetzal", + "symbol": "Q" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Guatemala", + "pt": "Guatemala", + "nl": "Guatemala", + "hr": "Gvatemala", + "fa": "گواتمالا", + "de": "Guatemala", + "es": "Guatemala", + "fr": "Guatemala", + "ja": "グアテマラ", + "it": "Guatemala", + "hu": "Guatemala" + }, + "flag": "https://flagcdn.com/gt.svg", + "regionalBlocs": [ + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "GUA", + "independent": true + }, + { + "name": "Guernsey", + "topLevelDomain": [ + ".gg" + ], + "alpha2Code": "GG", + "alpha3Code": "GGY", + "callingCodes": [ + "44" + ], + "capital": "St. Peter Port", + "altSpellings": [ + "GG", + "Bailiwick of Guernsey", + "Bailliage de Guernesey" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 62999, + "latlng": [ + 49.46666666, + -2.58333333 + ], + "demonym": "Channel Islander", + "area": 78.0, + "timezones": [ + "UTC+00:00" + ], + "nativeName": "Guernsey", + "numericCode": "831", + "flags": { + "svg": "https://flagcdn.com/gg.svg", + "png": "https://flagcdn.com/w320/gg.png" + }, + "currencies": [ + { + "code": "GBP", + "name": "British pound", + "symbol": "£" + }, + { + "code": "GGP", + "name": "Guernsey pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Gwernenez", + "pt": "Guernsey", + "nl": "Guernsey", + "hr": "Guernsey", + "fa": "گرنزی", + "de": "Guernsey", + "es": "Guernsey", + "fr": "Guernesey", + "ja": "ガーンジー", + "it": "Guernsey", + "hu": "Guernsey" + }, + "flag": "https://flagcdn.com/gg.svg", + "independent": false + }, + { + "name": "Guinea", + "topLevelDomain": [ + ".gn" + ], + "alpha2Code": "GN", + "alpha3Code": "GIN", + "callingCodes": [ + "224" + ], + "capital": "Conakry", + "altSpellings": [ + "GN", + "Republic of Guinea", + "République de Guinée" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 13132792, + "latlng": [ + 11.0, + -10.0 + ], + "demonym": "Guinean", + "area": 245857.0, + "gini": 33.7, + "timezones": [ + "UTC" + ], + "borders": [ + "CIV", + "GNB", + "LBR", + "MLI", + "SEN", + "SLE" + ], + "nativeName": "Guinée", + "numericCode": "324", + "flags": { + "svg": "https://flagcdn.com/gn.svg", + "png": "https://flagcdn.com/w320/gn.png" + }, + "currencies": [ + { + "code": "GNF", + "name": "Guinean franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "ff", + "iso639_2": "ful", + "name": "Fula", + "nativeName": "Fulfulde" + } + ], + "translations": { + "br": "Ginea", + "pt": "Guiné", + "nl": "Guinee", + "hr": "Gvineja", + "fa": "گینه", + "de": "Guinea", + "es": "Guinea", + "fr": "Guinée", + "ja": "ギニア", + "it": "Guinea", + "hu": "Guinea" + }, + "flag": "https://flagcdn.com/gn.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "GUI", + "independent": true + }, + { + "name": "Guinea-Bissau", + "topLevelDomain": [ + ".gw" + ], + "alpha2Code": "GW", + "alpha3Code": "GNB", + "callingCodes": [ + "245" + ], + "capital": "Bissau", + "altSpellings": [ + "GW", + "Republic of Guinea-Bissau", + "República da Guiné-Bissau" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 1967998, + "latlng": [ + 12.0, + -15.0 + ], + "demonym": "Guinea-Bissauan", + "area": 36125.0, + "gini": 50.7, + "timezones": [ + "UTC" + ], + "borders": [ + "GIN", + "SEN" + ], + "nativeName": "Guiné-Bissau", + "numericCode": "624", + "flags": { + "svg": "https://flagcdn.com/gw.svg", + "png": "https://flagcdn.com/w320/gw.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Ginea-Bissau", + "pt": "Guiné-Bissau", + "nl": "Guinee-Bissau", + "hr": "Gvineja Bisau", + "fa": "گینه بیسائو", + "de": "Guinea-Bissau", + "es": "Guinea-Bisáu", + "fr": "Guinée-Bissau", + "ja": "ギニアビサウ", + "it": "Guinea-Bissau", + "hu": "Bissau-Guinea" + }, + "flag": "https://flagcdn.com/gw.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "GBS", + "independent": true + }, + { + "name": "Guyana", + "topLevelDomain": [ + ".gy" + ], + "alpha2Code": "GY", + "alpha3Code": "GUY", + "callingCodes": [ + "592" + ], + "capital": "Georgetown", + "altSpellings": [ + "GY", + "Co-operative Republic of Guyana" + ], + "subregion": "South America", + "region": "Americas", + "population": 786559, + "latlng": [ + 5.0, + -59.0 + ], + "demonym": "Guyanese", + "area": 214969.0, + "gini": 45.1, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "BRA", + "SUR", + "VEN" + ], + "nativeName": "Guyana", + "numericCode": "328", + "flags": { + "svg": "https://flagcdn.com/gy.svg", + "png": "https://flagcdn.com/w320/gy.png" + }, + "currencies": [ + { + "code": "GYD", + "name": "Guyanese dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Guyana", + "pt": "Guiana", + "nl": "Guyana", + "hr": "Gvajana", + "fa": "گویان", + "de": "Guyana", + "es": "Guyana", + "fr": "Guyane", + "ja": "ガイアナ", + "it": "Guyana", + "hu": "Guyana" + }, + "flag": "https://flagcdn.com/gy.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + }, + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "GUY", + "independent": true + }, + { + "name": "Haiti", + "topLevelDomain": [ + ".ht" + ], + "alpha2Code": "HT", + "alpha3Code": "HTI", + "callingCodes": [ + "509" + ], + "capital": "Port-au-Prince", + "altSpellings": [ + "HT", + "Republic of Haiti", + "République d'Haïti", + "Repiblik Ayiti" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 11402533, + "latlng": [ + 19.0, + -72.41666666 + ], + "demonym": "Haitian", + "area": 27750.0, + "gini": 41.1, + "timezones": [ + "UTC-05:00" + ], + "borders": [ + "DOM" + ], + "nativeName": "Haïti", + "numericCode": "332", + "flags": { + "svg": "https://flagcdn.com/ht.svg", + "png": "https://flagcdn.com/w320/ht.png" + }, + "currencies": [ + { + "code": "HTG", + "name": "Haitian gourde", + "symbol": "G" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "ht", + "iso639_2": "hat", + "name": "Haitian", + "nativeName": "Kreyòl ayisyen" + } + ], + "translations": { + "br": "Haiti", + "pt": "Haiti", + "nl": "Haïti", + "hr": "Haiti", + "fa": "هائیتی", + "de": "Haiti", + "es": "Haiti", + "fr": "Haïti", + "ja": "ハイチ", + "it": "Haiti", + "hu": "Haiti" + }, + "flag": "https://flagcdn.com/ht.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "HAI", + "independent": true + }, + { + "name": "Heard Island and McDonald Islands", + "topLevelDomain": [ + ".hm", + ".aq" + ], + "alpha2Code": "HM", + "alpha3Code": "HMD", + "callingCodes": [ + "672" + ], + "altSpellings": [ + "HM" + ], + "subregion": "Antarctic", + "region": "Antarctic", + "population": 0, + "latlng": [ + -53.1, + 72.51666666 + ], + "demonym": "Heard and McDonald Islander", + "area": 412.0, + "timezones": [ + "UTC+05:00" + ], + "nativeName": "Heard Island and McDonald Islands", + "numericCode": "334", + "flags": { + "svg": "https://flagcdn.com/hm.svg", + "png": "https://flagcdn.com/w320/hm.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Heard ha McDonald", + "pt": "Ilha Heard e Ilhas McDonald", + "nl": "Heard- en McDonaldeilanden", + "hr": "Otok Heard i otočje McDonald", + "fa": "جزیره هرد و جزایر مک‌دونالد", + "de": "Heard und die McDonaldinseln", + "es": "Islas Heard y McDonald", + "fr": "Îles Heard-et-MacDonald", + "ja": "ハード島とマクドナルド諸島", + "it": "Isole Heard e McDonald", + "hu": "Heard-sziget és McDonald-szigetek" + }, + "flag": "https://flagcdn.com/hm.svg", + "independent": false + }, + { + "name": "Vatican City", + "topLevelDomain": [ + ".va" + ], + "alpha2Code": "VA", + "alpha3Code": "VAT", + "callingCodes": [ + "379" + ], + "capital": "Vatican City", + "altSpellings": [ + "Vatican", + "The Vatican" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 451, + "latlng": [ + 41.9, + 12.45 + ], + "demonym": "Vatican", + "area": 0.44, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "ITA" + ], + "nativeName": "Status Civitatis Vaticanae", + "numericCode": "336", + "flags": { + "svg": "https://flagcdn.com/va.svg", + "png": "https://flagcdn.com/w320/va.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "la", + "iso639_2": "lat", + "name": "Latin", + "nativeName": "latine" + }, + { + "iso639_1": "it", + "iso639_2": "ita", + "name": "Italian", + "nativeName": "Italiano" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "Français" + }, + { + "iso639_1": "de", + "iso639_2": "deu", + "name": "German", + "nativeName": "Deutsch" + } + ], + "translations": { + "br": "Vatikan", + "pt": "Vaticano", + "nl": "Heilige Stoel", + "hr": "Sveta Stolica", + "fa": "سریر مقدس", + "de": "Heiliger Stuhl", + "es": "Santa Sede", + "fr": "Saint-Siège", + "ja": "聖座", + "it": "Santa Sede", + "hu": "Vatikán" + }, + "flag": "https://flagcdn.com/va.svg", + "independent": true + }, + { + "name": "Honduras", + "topLevelDomain": [ + ".hn" + ], + "alpha2Code": "HN", + "alpha3Code": "HND", + "callingCodes": [ + "504" + ], + "capital": "Tegucigalpa", + "altSpellings": [ + "HN", + "Republic of Honduras", + "República de Honduras" + ], + "subregion": "Central America", + "region": "Americas", + "population": 9904608, + "latlng": [ + 15.0, + -86.5 + ], + "demonym": "Honduran", + "area": 112492.0, + "gini": 48.2, + "timezones": [ + "UTC-06:00" + ], + "borders": [ + "GTM", + "SLV", + "NIC" + ], + "nativeName": "Honduras", + "numericCode": "340", + "flags": { + "svg": "https://flagcdn.com/hn.svg", + "png": "https://flagcdn.com/w320/hn.png" + }, + "currencies": [ + { + "code": "HNL", + "name": "Honduran lempira", + "symbol": "L" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Honduras", + "pt": "Honduras", + "nl": "Honduras", + "hr": "Honduras", + "fa": "هندوراس", + "de": "Honduras", + "es": "Honduras", + "fr": "Honduras", + "ja": "ホンジュラス", + "it": "Honduras", + "hu": "Honduras" + }, + "flag": "https://flagcdn.com/hn.svg", + "regionalBlocs": [ + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "HON", + "independent": true + }, + { + "name": "Hungary", + "topLevelDomain": [ + ".hu" + ], + "alpha2Code": "HU", + "alpha3Code": "HUN", + "callingCodes": [ + "36" + ], + "capital": "Budapest", + "altSpellings": [ + "HU" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 9749763, + "latlng": [ + 47.0, + 20.0 + ], + "demonym": "Hungarian", + "area": 93028.0, + "gini": 29.6, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AUT", + "HRV", + "ROU", + "SRB", + "SVK", + "SVN", + "UKR" + ], + "nativeName": "Magyarország", + "numericCode": "348", + "flags": { + "svg": "https://flagcdn.com/hu.svg", + "png": "https://flagcdn.com/w320/hu.png" + }, + "currencies": [ + { + "code": "HUF", + "name": "Hungarian forint", + "symbol": "Ft" + } + ], + "languages": [ + { + "iso639_1": "hu", + "iso639_2": "hun", + "name": "Hungarian", + "nativeName": "magyar" + } + ], + "translations": { + "br": "Hungaria", + "pt": "Hungria", + "nl": "Hongarije", + "hr": "Mađarska", + "fa": "مجارستان", + "de": "Ungarn", + "es": "Hungría", + "fr": "Hongrie", + "ja": "ハンガリー", + "it": "Ungheria", + "hu": "Magyarország" + }, + "flag": "https://flagcdn.com/hu.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "HUN", + "independent": true + }, + { + "name": "Hong Kong", + "topLevelDomain": [ + ".hk" + ], + "alpha2Code": "HK", + "alpha3Code": "HKG", + "callingCodes": [ + "852" + ], + "capital": "City of Victoria", + "altSpellings": [ + "HK", + "香港" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 7481800, + "latlng": [ + 22.25, + 114.16666666 + ], + "demonym": "Chinese", + "area": 1104.0, + "timezones": [ + "UTC+08:00" + ], + "borders": [ + "CHN" + ], + "nativeName": "香港", + "numericCode": "344", + "flags": { + "svg": "https://flagcdn.com/hk.svg", + "png": "https://flagcdn.com/w320/hk.png" + }, + "currencies": [ + { + "code": "HKD", + "name": "Hong Kong dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "zh", + "iso639_2": "zho", + "name": "Chinese", + "nativeName": "中文 (Zhōngwén)" + } + ], + "translations": { + "br": "Hong Kong", + "pt": "Hong Kong", + "nl": "Hongkong", + "hr": "Hong Kong", + "fa": "هنگ‌کنگ", + "de": "Hong Kong", + "es": "Hong Kong", + "fr": "Hong Kong", + "ja": "香港", + "it": "Hong Kong", + "hu": "Hong Kong" + }, + "flag": "https://flagcdn.com/hk.svg", + "cioc": "HKG", + "independent": false + }, + { + "name": "Iceland", + "topLevelDomain": [ + ".is" + ], + "alpha2Code": "IS", + "alpha3Code": "ISL", + "callingCodes": [ + "354" + ], + "capital": "Reykjavík", + "altSpellings": [ + "IS", + "Island", + "Republic of Iceland", + "Lýðveldið Ísland" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 366425, + "latlng": [ + 65.0, + -18.0 + ], + "demonym": "Icelander", + "area": 103000.0, + "gini": 26.1, + "timezones": [ + "UTC" + ], + "nativeName": "Ísland", + "numericCode": "352", + "flags": { + "svg": "https://flagcdn.com/is.svg", + "png": "https://flagcdn.com/w320/is.png" + }, + "currencies": [ + { + "code": "ISK", + "name": "Icelandic króna", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "is", + "iso639_2": "isl", + "name": "Icelandic", + "nativeName": "Íslenska" + } + ], + "translations": { + "br": "Island", + "pt": "Islândia", + "nl": "IJsland", + "hr": "Island", + "fa": "ایسلند", + "de": "Island", + "es": "Islandia", + "fr": "Islande", + "ja": "アイスランド", + "it": "Islanda", + "hu": "Izland" + }, + "flag": "https://flagcdn.com/is.svg", + "regionalBlocs": [ + { + "acronym": "EFTA", + "name": "European Free Trade Association" + } + ], + "cioc": "ISL", + "independent": true + }, + { + "name": "India", + "topLevelDomain": [ + ".in" + ], + "alpha2Code": "IN", + "alpha3Code": "IND", + "callingCodes": [ + "91" + ], + "capital": "New Delhi", + "altSpellings": [ + "IN", + "Bhārat", + "Republic of India", + "Bharat Ganrajya" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 1380004385, + "latlng": [ + 20.0, + 77.0 + ], + "demonym": "Indian", + "area": 3287590.0, + "gini": 35.7, + "timezones": [ + "UTC+05:30" + ], + "borders": [ + "AFG", + "BGD", + "BTN", + "MMR", + "CHN", + "NPL", + "PAK", + "LKA" + ], + "nativeName": "भारत", + "numericCode": "356", + "flags": { + "svg": "https://flagcdn.com/in.svg", + "png": "https://flagcdn.com/w320/in.png" + }, + "currencies": [ + { + "code": "INR", + "name": "Indian rupee", + "symbol": "₹" + } + ], + "languages": [ + { + "iso639_1": "hi", + "iso639_2": "hin", + "name": "Hindi", + "nativeName": "हिन्दी" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "India", + "pt": "Índia", + "nl": "India", + "hr": "Indija", + "fa": "هند", + "de": "Indien", + "es": "India", + "fr": "Inde", + "ja": "インド", + "it": "India", + "hu": "India" + }, + "flag": "https://flagcdn.com/in.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "IND", + "independent": true + }, + { + "name": "Indonesia", + "topLevelDomain": [ + ".id" + ], + "alpha2Code": "ID", + "alpha3Code": "IDN", + "callingCodes": [ + "62" + ], + "capital": "Jakarta", + "altSpellings": [ + "ID", + "Republic of Indonesia", + "Republik Indonesia" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 273523621, + "latlng": [ + -5.0, + 120.0 + ], + "demonym": "Indonesian", + "area": 1904569.0, + "gini": 38.2, + "timezones": [ + "UTC+07:00", + "UTC+08:00", + "UTC+09:00" + ], + "borders": [ + "TLS", + "MYS", + "PNG" + ], + "nativeName": "Indonesia", + "numericCode": "360", + "flags": { + "svg": "https://flagcdn.com/id.svg", + "png": "https://flagcdn.com/w320/id.png" + }, + "currencies": [ + { + "code": "IDR", + "name": "Indonesian rupiah", + "symbol": "Rp" + } + ], + "languages": [ + { + "iso639_1": "id", + "iso639_2": "ind", + "name": "Indonesian", + "nativeName": "Bahasa Indonesia" + } + ], + "translations": { + "br": "Indonezia", + "pt": "Indonésia", + "nl": "Indonesië", + "hr": "Indonezija", + "fa": "اندونزی", + "de": "Indonesien", + "es": "Indonesia", + "fr": "Indonésie", + "ja": "インドネシア", + "it": "Indonesia", + "hu": "Indonézia" + }, + "flag": "https://flagcdn.com/id.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "INA", + "independent": true + }, + { + "name": "Ivory Coast", + "topLevelDomain": [ + ".ci" + ], + "alpha2Code": "CI", + "alpha3Code": "CIV", + "callingCodes": [ + "225" + ], + "capital": "Yamoussoukro", + "altSpellings": [ + "CI", + "Ivory Coast", + "Republic of Côte d'Ivoire", + "République de Côte d'Ivoire" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 26378275, + "latlng": [ + 8.0, + -5.0 + ], + "demonym": "Ivorian", + "area": 322463.0, + "gini": 41.5, + "timezones": [ + "UTC" + ], + "borders": [ + "BFA", + "GHA", + "GIN", + "LBR", + "MLI" + ], + "nativeName": "Côte d'Ivoire", + "numericCode": "384", + "flags": { + "svg": "https://flagcdn.com/ci.svg", + "png": "https://flagcdn.com/w320/ci.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Aod an Olifant", + "pt": "Costa do Marfim", + "nl": "Ivoorkust", + "hr": "Obala Bjelokosti", + "fa": "ساحل عاج", + "de": "Elfenbeinküste", + "es": "Costa de Marfil", + "fr": "Côte d'Ivoire", + "ja": "コートジボワール", + "it": "Costa D'Avorio", + "hu": "Elefántcsontpart" + }, + "flag": "https://flagcdn.com/ci.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "CIV", + "independent": true + }, + { + "name": "Iran (Islamic Republic of)", + "topLevelDomain": [ + ".ir" + ], + "alpha2Code": "IR", + "alpha3Code": "IRN", + "callingCodes": [ + "98" + ], + "capital": "Tehran", + "altSpellings": [ + "IR", + "Islamic Republic of Iran", + "Jomhuri-ye Eslāmi-ye Irān" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 83992953, + "latlng": [ + 32.0, + 53.0 + ], + "demonym": "Iranian", + "area": 1648195.0, + "gini": 42.0, + "timezones": [ + "UTC+03:30" + ], + "borders": [ + "AFG", + "ARM", + "AZE", + "IRQ", + "PAK", + "TUR", + "TKM" + ], + "nativeName": "ایران", + "numericCode": "364", + "flags": { + "svg": "https://flagcdn.com/ir.svg", + "png": "https://flagcdn.com/w320/ir.png" + }, + "currencies": [ + { + "code": "IRR", + "name": "Iranian rial", + "symbol": "﷼" + } + ], + "languages": [ + { + "iso639_1": "fa", + "iso639_2": "fas", + "name": "Persian (Farsi)", + "nativeName": "فارسی" + } + ], + "translations": { + "br": "Iran", + "pt": "Irão", + "nl": "Iran", + "hr": "Iran", + "fa": "ایران", + "de": "Iran", + "es": "Iran", + "fr": "Iran", + "ja": "イラン・イスラム共和国", + "it": "Iran (Islamic Republic of)", + "hu": "Irán" + }, + "flag": "https://flagcdn.com/ir.svg", + "cioc": "IRI", + "independent": true + }, + { + "name": "Iraq", + "topLevelDomain": [ + ".iq" + ], + "alpha2Code": "IQ", + "alpha3Code": "IRQ", + "callingCodes": [ + "964" + ], + "capital": "Baghdad", + "altSpellings": [ + "IQ", + "Republic of Iraq", + "Jumhūriyyat al-‘Irāq" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 40222503, + "latlng": [ + 33.0, + 44.0 + ], + "demonym": "Iraqi", + "area": 438317.0, + "gini": 29.5, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "IRN", + "JOR", + "KWT", + "SAU", + "SYR", + "TUR" + ], + "nativeName": "العراق", + "numericCode": "368", + "flags": { + "svg": "https://flagcdn.com/iq.svg", + "png": "https://flagcdn.com/w320/iq.png" + }, + "currencies": [ + { + "code": "IQD", + "name": "Iraqi dinar", + "symbol": "ع.د" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + }, + { + "iso639_1": "ku", + "iso639_2": "kur", + "name": "Kurdish", + "nativeName": "Kurdî" + } + ], + "translations": { + "br": "Irak", + "pt": "Iraque", + "nl": "Irak", + "hr": "Irak", + "fa": "عراق", + "de": "Irak", + "es": "Irak", + "fr": "Irak", + "ja": "イラク", + "it": "Iraq", + "hu": "Irak" + }, + "flag": "https://flagcdn.com/iq.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "IRQ", + "independent": true + }, + { + "name": "Ireland", + "topLevelDomain": [ + ".ie" + ], + "alpha2Code": "IE", + "alpha3Code": "IRL", + "callingCodes": [ + "353" + ], + "capital": "Dublin", + "altSpellings": [ + "IE", + "Éire", + "Republic of Ireland", + "Poblacht na hÉireann" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 4994724, + "latlng": [ + 53.0, + -8.0 + ], + "demonym": "Irish", + "area": 70273.0, + "gini": 31.4, + "timezones": [ + "UTC" + ], + "borders": [ + "GBR" + ], + "nativeName": "Éire", + "numericCode": "372", + "flags": { + "svg": "https://flagcdn.com/ie.svg", + "png": "https://flagcdn.com/w320/ie.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "ga", + "iso639_2": "gle", + "name": "Irish", + "nativeName": "Gaeilge" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Iwerzhon", + "pt": "Irlanda", + "nl": "Ierland", + "hr": "Irska", + "fa": "ایرلند", + "de": "Irland", + "es": "Irlanda", + "fr": "Irlande", + "ja": "アイルランド", + "it": "Irlanda", + "hu": "Írország" + }, + "flag": "https://flagcdn.com/ie.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "IRL", + "independent": true + }, + { + "name": "Isle of Man", + "topLevelDomain": [ + ".im" + ], + "alpha2Code": "IM", + "alpha3Code": "IMN", + "callingCodes": [ + "44" + ], + "capital": "Douglas", + "altSpellings": [ + "IM", + "Ellan Vannin", + "Mann", + "Mannin" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 85032, + "latlng": [ + 54.25, + -4.5 + ], + "demonym": "Manx", + "area": 572.0, + "timezones": [ + "UTC+00:00" + ], + "nativeName": "Isle of Man", + "numericCode": "833", + "flags": { + "svg": "https://flagcdn.com/im.svg", + "png": "https://flagcdn.com/w320/im.png" + }, + "currencies": [ + { + "code": "GBP", + "name": "British pound", + "symbol": "£" + }, + { + "code": "IMP[G]", + "name": "Manx pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "gv", + "iso639_2": "glv", + "name": "Manx", + "nativeName": "Gaelg" + } + ], + "translations": { + "br": "Enez Vanav", + "pt": "Ilha de Man", + "nl": "Isle of Man", + "hr": "Otok Man", + "fa": "جزیره من", + "de": "Insel Man", + "es": "Isla de Man", + "fr": "Île de Man", + "ja": "マン島", + "it": "Isola di Man", + "hu": "Man" + }, + "flag": "https://flagcdn.com/im.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "independent": false + }, + { + "name": "Israel", + "topLevelDomain": [ + ".il" + ], + "alpha2Code": "IL", + "alpha3Code": "ISR", + "callingCodes": [ + "972" + ], + "capital": "Jerusalem", + "altSpellings": [ + "IL", + "State of Israel", + "Medīnat Yisrā'el" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 9216900, + "latlng": [ + 31.5, + 34.75 + ], + "demonym": "Israeli", + "area": 20770.0, + "gini": 39.0, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "EGY", + "JOR", + "LBN", + "SYR" + ], + "nativeName": "יִשְׂרָאֵל", + "numericCode": "376", + "flags": { + "svg": "https://flagcdn.com/il.svg", + "png": "https://flagcdn.com/w320/il.png" + }, + "currencies": [ + { + "code": "ILS", + "name": "Israeli new shekel", + "symbol": "₪" + } + ], + "languages": [ + { + "iso639_1": "he", + "iso639_2": "heb", + "name": "Hebrew (modern)", + "nativeName": "עברית" + }, + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Israel", + "pt": "Israel", + "nl": "Israël", + "hr": "Izrael", + "fa": "اسرائیل", + "de": "Israel", + "es": "Israel", + "fr": "Israël", + "ja": "イスラエル", + "it": "Israele", + "hu": "Izrael" + }, + "flag": "https://flagcdn.com/il.svg", + "cioc": "ISR", + "independent": true + }, + { + "name": "Italy", + "topLevelDomain": [ + ".it" + ], + "alpha2Code": "IT", + "alpha3Code": "ITA", + "callingCodes": [ + "39" + ], + "capital": "Rome", + "altSpellings": [ + "IT", + "Italian Republic", + "Repubblica italiana" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 59554023, + "latlng": [ + 42.83333333, + 12.83333333 + ], + "demonym": "Italian", + "area": 301336.0, + "gini": 35.9, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AUT", + "FRA", + "SMR", + "SVN", + "CHE", + "VAT" + ], + "nativeName": "Italia", + "numericCode": "380", + "flags": { + "svg": "https://flagcdn.com/it.svg", + "png": "https://flagcdn.com/w320/it.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "it", + "iso639_2": "ita", + "name": "Italian", + "nativeName": "Italiano" + } + ], + "translations": { + "br": "Italia", + "pt": "Itália", + "nl": "Italië", + "hr": "Italija", + "fa": "ایتالیا", + "de": "Italien", + "es": "Italia", + "fr": "Italie", + "ja": "イタリア", + "it": "Italia", + "hu": "Olaszország" + }, + "flag": "https://flagcdn.com/it.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "ITA", + "independent": true + }, + { + "name": "Jamaica", + "topLevelDomain": [ + ".jm" + ], + "alpha2Code": "JM", + "alpha3Code": "JAM", + "callingCodes": [ + "1" + ], + "capital": "Kingston", + "altSpellings": [ + "JM" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 2961161, + "latlng": [ + 18.25, + -77.5 + ], + "demonym": "Jamaican", + "area": 10991.0, + "gini": 45.5, + "timezones": [ + "UTC-05:00" + ], + "nativeName": "Jamaica", + "numericCode": "388", + "flags": { + "svg": "https://flagcdn.com/jm.svg", + "png": "https://flagcdn.com/w320/jm.png" + }, + "currencies": [ + { + "code": "JMD", + "name": "Jamaican dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Jamaika", + "pt": "Jamaica", + "nl": "Jamaica", + "hr": "Jamajka", + "fa": "جامائیکا", + "de": "Jamaika", + "es": "Jamaica", + "fr": "Jamaïque", + "ja": "ジャマイカ", + "it": "Giamaica", + "hu": "Jamaica" + }, + "flag": "https://flagcdn.com/jm.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "JAM", + "independent": true + }, + { + "name": "Japan", + "topLevelDomain": [ + ".jp" + ], + "alpha2Code": "JP", + "alpha3Code": "JPN", + "callingCodes": [ + "81" + ], + "capital": "Tokyo", + "altSpellings": [ + "JP", + "Nippon", + "Nihon" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 125836021, + "latlng": [ + 36.0, + 138.0 + ], + "demonym": "Japanese", + "area": 377930.0, + "gini": 32.9, + "timezones": [ + "UTC+09:00" + ], + "nativeName": "日本", + "numericCode": "392", + "flags": { + "svg": "https://flagcdn.com/jp.svg", + "png": "https://flagcdn.com/w320/jp.png" + }, + "currencies": [ + { + "code": "JPY", + "name": "Japanese yen", + "symbol": "¥" + } + ], + "languages": [ + { + "iso639_1": "ja", + "iso639_2": "jpn", + "name": "Japanese", + "nativeName": "日本語 (にほんご)" + } + ], + "translations": { + "br": "Japan", + "pt": "Japão", + "nl": "Japan", + "hr": "Japan", + "fa": "ژاپن", + "de": "Japan", + "es": "Japón", + "fr": "Japon", + "ja": "日本", + "it": "Giappone", + "hu": "Japán" + }, + "flag": "https://flagcdn.com/jp.svg", + "cioc": "JPN", + "independent": true + }, + { + "name": "Jersey", + "topLevelDomain": [ + ".je" + ], + "alpha2Code": "JE", + "alpha3Code": "JEY", + "callingCodes": [ + "44" + ], + "capital": "Saint Helier", + "altSpellings": [ + "JE", + "Bailiwick of Jersey", + "Bailliage de Jersey", + "Bailliage dé Jèrri" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 100800, + "latlng": [ + 49.25, + -2.16666666 + ], + "demonym": "Channel Islander", + "area": 116.0, + "timezones": [ + "UTC+01:00" + ], + "nativeName": "Jersey", + "numericCode": "832", + "flags": { + "svg": "https://flagcdn.com/je.svg", + "png": "https://flagcdn.com/w320/je.png" + }, + "currencies": [ + { + "code": "GBP", + "name": "British pound", + "symbol": "£" + }, + { + "code": "JEP[G]", + "name": "Jersey pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Jerzenez", + "pt": "Jersey", + "nl": "Jersey", + "hr": "Jersey", + "fa": "جرزی", + "de": "Jersey", + "es": "Jersey", + "fr": "Jersey", + "ja": "ジャージー", + "it": "Isola di Jersey", + "hu": "Jersey" + }, + "flag": "https://flagcdn.com/je.svg", + "independent": false + }, + { + "name": "Jordan", + "topLevelDomain": [ + ".jo" + ], + "alpha2Code": "JO", + "alpha3Code": "JOR", + "callingCodes": [ + "962" + ], + "capital": "Amman", + "altSpellings": [ + "JO", + "Hashemite Kingdom of Jordan", + "al-Mamlakah al-Urdunīyah al-Hāshimīyah" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 10203140, + "latlng": [ + 31.0, + 36.0 + ], + "demonym": "Jordanian", + "area": 89342.0, + "gini": 33.7, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "IRQ", + "ISR", + "SAU", + "SYR" + ], + "nativeName": "الأردن", + "numericCode": "400", + "flags": { + "svg": "https://flagcdn.com/jo.svg", + "png": "https://flagcdn.com/w320/jo.png" + }, + "currencies": [ + { + "code": "JOD", + "name": "Jordanian dinar", + "symbol": "د.ا" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Jordania", + "pt": "Jordânia", + "nl": "Jordanië", + "hr": "Jordan", + "fa": "اردن", + "de": "Jordanien", + "es": "Jordania", + "fr": "Jordanie", + "ja": "ヨルダン", + "it": "Giordania", + "hu": "Jordánia" + }, + "flag": "https://flagcdn.com/jo.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "JOR", + "independent": true + }, + { + "name": "Kazakhstan", + "topLevelDomain": [ + ".kz", + ".қаз" + ], + "alpha2Code": "KZ", + "alpha3Code": "KAZ", + "callingCodes": [ + "76", + "77" + ], + "capital": "Nur-Sultan", + "altSpellings": [ + "KZ", + "Qazaqstan", + "Казахстан", + "Republic of Kazakhstan", + "Қазақстан Республикасы", + "Qazaqstan Respublïkası", + "Республика Казахстан", + "Respublika Kazakhstan" + ], + "subregion": "Central Asia", + "region": "Asia", + "population": 18754440, + "latlng": [ + 48.0, + 68.0 + ], + "demonym": "Kazakhstani", + "area": 2724900.0, + "gini": 27.8, + "timezones": [ + "UTC+05:00", + "UTC+06:00" + ], + "borders": [ + "CHN", + "KGZ", + "RUS", + "TKM", + "UZB" + ], + "nativeName": "Қазақстан", + "numericCode": "398", + "flags": { + "svg": "https://flagcdn.com/kz.svg", + "png": "https://flagcdn.com/w320/kz.png" + }, + "currencies": [ + { + "code": "KZT", + "name": "Kazakhstani tenge", + "symbol": "₸" + } + ], + "languages": [ + { + "iso639_1": "kk", + "iso639_2": "kaz", + "name": "Kazakh", + "nativeName": "қазақ тілі" + }, + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Kazakstan", + "pt": "Cazaquistão", + "nl": "Kazachstan", + "hr": "Kazahstan", + "fa": "قزاقستان", + "de": "Kasachstan", + "es": "Kazajistán", + "fr": "Kazakhstan", + "ja": "カザフスタン", + "it": "Kazakistan", + "hu": "Kazahsztán" + }, + "flag": "https://flagcdn.com/kz.svg", + "regionalBlocs": [ + { + "acronym": "EEU", + "name": "Eurasian Economic Union", + "otherAcronyms": [ + "EAEU" + ] + } + ], + "cioc": "KAZ", + "independent": true + }, + { + "name": "Kenya", + "topLevelDomain": [ + ".ke" + ], + "alpha2Code": "KE", + "alpha3Code": "KEN", + "callingCodes": [ + "254" + ], + "capital": "Nairobi", + "altSpellings": [ + "KE", + "Republic of Kenya", + "Jamhuri ya Kenya" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 53771300, + "latlng": [ + 1.0, + 38.0 + ], + "demonym": "Kenyan", + "area": 580367.0, + "gini": 40.8, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "ETH", + "SOM", + "SSD", + "TZA", + "UGA" + ], + "nativeName": "Kenya", + "numericCode": "404", + "flags": { + "svg": "https://flagcdn.com/ke.svg", + "png": "https://flagcdn.com/w320/ke.png" + }, + "currencies": [ + { + "code": "KES", + "name": "Kenyan shilling", + "symbol": "Sh" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "sw", + "iso639_2": "swa", + "name": "Swahili", + "nativeName": "Kiswahili" + } + ], + "translations": { + "br": "Kenya", + "pt": "Quénia", + "nl": "Kenia", + "hr": "Kenija", + "fa": "کنیا", + "de": "Kenia", + "es": "Kenia", + "fr": "Kenya", + "ja": "ケニア", + "it": "Kenya", + "hu": "Kenya" + }, + "flag": "https://flagcdn.com/ke.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "KEN", + "independent": true + }, + { + "name": "Kiribati", + "topLevelDomain": [ + ".ki" + ], + "alpha2Code": "KI", + "alpha3Code": "KIR", + "callingCodes": [ + "686" + ], + "capital": "South Tarawa", + "altSpellings": [ + "KI", + "Republic of Kiribati", + "Ribaberiki Kiribati" + ], + "subregion": "Micronesia", + "region": "Oceania", + "population": 119446, + "latlng": [ + 1.41666666, + 173.0 + ], + "demonym": "I-Kiribati", + "area": 811.0, + "gini": 37.0, + "timezones": [ + "UTC+12:00", + "UTC+13:00", + "UTC+14:00" + ], + "nativeName": "Kiribati", + "numericCode": "296", + "flags": { + "svg": "https://flagcdn.com/ki.svg", + "png": "https://flagcdn.com/w320/ki.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + }, + { + "code": "KID", + "name": "Kiribati dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Kiribati", + "pt": "Quiribáti", + "nl": "Kiribati", + "hr": "Kiribati", + "fa": "کیریباتی", + "de": "Kiribati", + "es": "Kiribati", + "fr": "Kiribati", + "ja": "キリバス", + "it": "Kiribati", + "hu": "Kiribati" + }, + "flag": "https://flagcdn.com/ki.svg", + "cioc": "KIR", + "independent": true + }, + { + "name": "Kuwait", + "topLevelDomain": [ + ".kw" + ], + "alpha2Code": "KW", + "alpha3Code": "KWT", + "callingCodes": [ + "965" + ], + "capital": "Kuwait City", + "altSpellings": [ + "KW", + "State of Kuwait", + "Dawlat al-Kuwait" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 4270563, + "latlng": [ + 29.5, + 45.75 + ], + "demonym": "Kuwaiti", + "area": 17818.0, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "IRQ", + "SAU" + ], + "nativeName": "الكويت", + "numericCode": "414", + "flags": { + "svg": "https://flagcdn.com/kw.svg", + "png": "https://flagcdn.com/w320/kw.png" + }, + "currencies": [ + { + "code": "KWD", + "name": "Kuwaiti dinar", + "symbol": "د.ك" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Koweit", + "pt": "Kuwait", + "nl": "Koeweit", + "hr": "Kuvajt", + "fa": "کویت", + "de": "Kuwait", + "es": "Kuwait", + "fr": "Koweït", + "ja": "クウェート", + "it": "Kuwait", + "hu": "Kuvait" + }, + "flag": "https://flagcdn.com/kw.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "KUW", + "independent": true + }, + { + "name": "Kyrgyzstan", + "topLevelDomain": [ + ".kg" + ], + "alpha2Code": "KG", + "alpha3Code": "KGZ", + "callingCodes": [ + "996" + ], + "capital": "Bishkek", + "altSpellings": [ + "KG", + "Киргизия", + "Kyrgyz Republic", + "Кыргыз Республикасы", + "Kyrgyz Respublikasy" + ], + "subregion": "Central Asia", + "region": "Asia", + "population": 6591600, + "latlng": [ + 41.0, + 75.0 + ], + "demonym": "Kirghiz", + "area": 199951.0, + "gini": 29.7, + "timezones": [ + "UTC+06:00" + ], + "borders": [ + "CHN", + "KAZ", + "TJK", + "UZB" + ], + "nativeName": "Кыргызстан", + "numericCode": "417", + "flags": { + "svg": "https://flagcdn.com/kg.svg", + "png": "https://flagcdn.com/w320/kg.png" + }, + "currencies": [ + { + "code": "KGS", + "name": "Kyrgyzstani som", + "symbol": "с" + } + ], + "languages": [ + { + "iso639_1": "ky", + "iso639_2": "kir", + "name": "Kyrgyz", + "nativeName": "Кыргызча" + }, + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Kirgizstan", + "pt": "Quirguizistão", + "nl": "Kirgizië", + "hr": "Kirgistan", + "fa": "قرقیزستان", + "de": "Kirgisistan", + "es": "Kirguizistán", + "fr": "Kirghizistan", + "ja": "キルギス", + "it": "Kirghizistan", + "hu": "Kirgizisztán" + }, + "flag": "https://flagcdn.com/kg.svg", + "regionalBlocs": [ + { + "acronym": "EEU", + "name": "Eurasian Economic Union", + "otherAcronyms": [ + "EAEU" + ] + } + ], + "cioc": "KGZ", + "independent": true + }, + { + "name": "Lao People's Democratic Republic", + "topLevelDomain": [ + ".la" + ], + "alpha2Code": "LA", + "alpha3Code": "LAO", + "callingCodes": [ + "856" + ], + "capital": "Vientiane", + "altSpellings": [ + "LA", + "Lao", + "Laos", + "Lao People's Democratic Republic", + "Sathalanalat Paxathipatai Paxaxon Lao" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 7275556, + "latlng": [ + 18.0, + 105.0 + ], + "demonym": "Laotian", + "area": 236800.0, + "gini": 38.8, + "timezones": [ + "UTC+07:00" + ], + "borders": [ + "MMR", + "KHM", + "CHN", + "THA", + "VNM" + ], + "nativeName": "ສາທາລະນະລັດ ປະຊາທິປະໄຕ ປະຊາຊົນລາວ", + "numericCode": "418", + "flags": { + "svg": "https://flagcdn.com/la.svg", + "png": "https://flagcdn.com/w320/la.png" + }, + "currencies": [ + { + "code": "LAK", + "name": "Lao kip", + "symbol": "₭" + } + ], + "languages": [ + { + "iso639_1": "lo", + "iso639_2": "lao", + "name": "Lao", + "nativeName": "ພາສາລາວ" + } + ], + "translations": { + "br": "Laos", + "pt": "Laos", + "nl": "Laos", + "hr": "Laos", + "fa": "لائوس", + "de": "Laos", + "es": "Laos", + "fr": "Laos", + "ja": "ラオス人民民主共和国", + "it": "Laos", + "hu": "Laosz" + }, + "flag": "https://flagcdn.com/la.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "LAO", + "independent": true + }, + { + "name": "Latvia", + "topLevelDomain": [ + ".lv" + ], + "alpha2Code": "LV", + "alpha3Code": "LVA", + "callingCodes": [ + "371" + ], + "capital": "Riga", + "altSpellings": [ + "LV", + "Republic of Latvia", + "Latvijas Republika" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 1901548, + "latlng": [ + 57.0, + 25.0 + ], + "demonym": "Latvian", + "area": 64559.0, + "gini": 35.1, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "BLR", + "EST", + "LTU", + "RUS" + ], + "nativeName": "Latvija", + "numericCode": "428", + "flags": { + "svg": "https://flagcdn.com/lv.svg", + "png": "https://flagcdn.com/w320/lv.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "lv", + "iso639_2": "lav", + "name": "Latvian", + "nativeName": "latviešu valoda" + } + ], + "translations": { + "br": "Latvia", + "pt": "Letónia", + "nl": "Letland", + "hr": "Latvija", + "fa": "لتونی", + "de": "Lettland", + "es": "Letonia", + "fr": "Lettonie", + "ja": "ラトビア", + "it": "Lettonia", + "hu": "Lettország" + }, + "flag": "https://flagcdn.com/lv.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "LAT", + "independent": true + }, + { + "name": "Lebanon", + "topLevelDomain": [ + ".lb" + ], + "alpha2Code": "LB", + "alpha3Code": "LBN", + "callingCodes": [ + "961" + ], + "capital": "Beirut", + "altSpellings": [ + "LB", + "Lebanese Republic", + "Al-Jumhūrīyah Al-Libnānīyah" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 6825442, + "latlng": [ + 33.83333333, + 35.83333333 + ], + "demonym": "Lebanese", + "area": 10452.0, + "gini": 31.8, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "ISR", + "SYR" + ], + "nativeName": "لبنان", + "numericCode": "422", + "flags": { + "svg": "https://flagcdn.com/lb.svg", + "png": "https://flagcdn.com/w320/lb.png" + }, + "currencies": [ + { + "code": "LBP", + "name": "Lebanese pound", + "symbol": "ل.ل" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Liban", + "pt": "Líbano", + "nl": "Libanon", + "hr": "Libanon", + "fa": "لبنان", + "de": "Libanon", + "es": "Líbano", + "fr": "Liban", + "ja": "レバノン", + "it": "Libano", + "hu": "Libanon" + }, + "flag": "https://flagcdn.com/lb.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "LIB", + "independent": true + }, + { + "name": "Lesotho", + "topLevelDomain": [ + ".ls" + ], + "alpha2Code": "LS", + "alpha3Code": "LSO", + "callingCodes": [ + "266" + ], + "capital": "Maseru", + "altSpellings": [ + "LS", + "Kingdom of Lesotho", + "Muso oa Lesotho" + ], + "subregion": "Southern Africa", + "region": "Africa", + "population": 2142252, + "latlng": [ + -29.5, + 28.5 + ], + "demonym": "Mosotho", + "area": 30355.0, + "gini": 44.9, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "ZAF" + ], + "nativeName": "Lesotho", + "numericCode": "426", + "flags": { + "svg": "https://flagcdn.com/ls.svg", + "png": "https://flagcdn.com/w320/ls.png" + }, + "currencies": [ + { + "code": "LSL", + "name": "Lesotho loti", + "symbol": "L" + }, + { + "code": "ZAR", + "name": "South African rand", + "symbol": "R" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "st", + "iso639_2": "sot", + "name": "Southern Sotho", + "nativeName": "Sesotho" + } + ], + "translations": { + "br": "Lesotho", + "pt": "Lesoto", + "nl": "Lesotho", + "hr": "Lesoto", + "fa": "لسوتو", + "de": "Lesotho", + "es": "Lesotho", + "fr": "Lesotho", + "ja": "レソト", + "it": "Lesotho", + "hu": "Lesotho" + }, + "flag": "https://flagcdn.com/ls.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "LES", + "independent": true + }, + { + "name": "Liberia", + "topLevelDomain": [ + ".lr" + ], + "alpha2Code": "LR", + "alpha3Code": "LBR", + "callingCodes": [ + "231" + ], + "capital": "Monrovia", + "altSpellings": [ + "LR", + "Republic of Liberia" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 5057677, + "latlng": [ + 6.5, + -9.5 + ], + "demonym": "Liberian", + "area": 111369.0, + "gini": 35.3, + "timezones": [ + "UTC" + ], + "borders": [ + "GIN", + "CIV", + "SLE" + ], + "nativeName": "Liberia", + "numericCode": "430", + "flags": { + "svg": "https://flagcdn.com/lr.svg", + "png": "https://flagcdn.com/w320/lr.png" + }, + "currencies": [ + { + "code": "LRD", + "name": "Liberian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Liberia", + "pt": "Libéria", + "nl": "Liberia", + "hr": "Liberija", + "fa": "لیبریا", + "de": "Liberia", + "es": "Liberia", + "fr": "Liberia", + "ja": "リベリア", + "it": "Liberia", + "hu": "Libéria" + }, + "flag": "https://flagcdn.com/lr.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "LBR", + "independent": true + }, + { + "name": "Libya", + "topLevelDomain": [ + ".ly" + ], + "alpha2Code": "LY", + "alpha3Code": "LBY", + "callingCodes": [ + "218" + ], + "capital": "Tripoli", + "altSpellings": [ + "LY", + "State of Libya", + "Dawlat Libya" + ], + "subregion": "Northern Africa", + "region": "Africa", + "population": 6871287, + "latlng": [ + 25.0, + 17.0 + ], + "demonym": "Libyan", + "area": 1759540.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "DZA", + "TCD", + "EGY", + "NER", + "SDN", + "TUN" + ], + "nativeName": "‏ليبيا", + "numericCode": "434", + "flags": { + "svg": "https://flagcdn.com/ly.svg", + "png": "https://flagcdn.com/w320/ly.png" + }, + "currencies": [ + { + "code": "LYD", + "name": "Libyan dinar", + "symbol": "ل.د" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Libia", + "pt": "Líbia", + "nl": "Libië", + "hr": "Libija", + "fa": "لیبی", + "de": "Libyen", + "es": "Libia", + "fr": "Libye", + "ja": "リビア", + "it": "Libia", + "hu": "Líbia" + }, + "flag": "https://flagcdn.com/ly.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "LBA", + "independent": true + }, + { + "name": "Liechtenstein", + "topLevelDomain": [ + ".li" + ], + "alpha2Code": "LI", + "alpha3Code": "LIE", + "callingCodes": [ + "423" + ], + "capital": "Vaduz", + "altSpellings": [ + "LI", + "Principality of Liechtenstein", + "Fürstentum Liechtenstein" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 38137, + "latlng": [ + 47.26666666, + 9.53333333 + ], + "demonym": "Liechtensteiner", + "area": 160.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AUT", + "CHE" + ], + "nativeName": "Liechtenstein", + "numericCode": "438", + "flags": { + "svg": "https://flagcdn.com/li.svg", + "png": "https://flagcdn.com/w320/li.png" + }, + "currencies": [ + { + "code": "CHF", + "name": "Swiss franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "de", + "iso639_2": "deu", + "name": "German", + "nativeName": "Deutsch" + } + ], + "translations": { + "br": "Liechtenstein", + "pt": "Listenstaine", + "nl": "Liechtenstein", + "hr": "Lihtenštajn", + "fa": "لیختن‌اشتاین", + "de": "Liechtenstein", + "es": "Liechtenstein", + "fr": "Liechtenstein", + "ja": "リヒテンシュタイン", + "it": "Liechtenstein", + "hu": "Liechtenstein" + }, + "flag": "https://flagcdn.com/li.svg", + "regionalBlocs": [ + { + "acronym": "EFTA", + "name": "European Free Trade Association" + } + ], + "cioc": "LIE", + "independent": true + }, + { + "name": "Lithuania", + "topLevelDomain": [ + ".lt" + ], + "alpha2Code": "LT", + "alpha3Code": "LTU", + "callingCodes": [ + "370" + ], + "capital": "Vilnius", + "altSpellings": [ + "LT", + "Republic of Lithuania", + "Lietuvos Respublika" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 2794700, + "latlng": [ + 56.0, + 24.0 + ], + "demonym": "Lithuanian", + "area": 65300.0, + "gini": 35.7, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "BLR", + "LVA", + "POL", + "RUS" + ], + "nativeName": "Lietuva", + "numericCode": "440", + "flags": { + "svg": "https://flagcdn.com/lt.svg", + "png": "https://flagcdn.com/w320/lt.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "lt", + "iso639_2": "lit", + "name": "Lithuanian", + "nativeName": "lietuvių kalba" + } + ], + "translations": { + "br": "Lituania", + "pt": "Lituânia", + "nl": "Litouwen", + "hr": "Litva", + "fa": "لیتوانی", + "de": "Litauen", + "es": "Lituania", + "fr": "Lituanie", + "ja": "リトアニア", + "it": "Lituania", + "hu": "Litvánia" + }, + "flag": "https://flagcdn.com/lt.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "LTU", + "independent": true + }, + { + "name": "Luxembourg", + "topLevelDomain": [ + ".lu" + ], + "alpha2Code": "LU", + "alpha3Code": "LUX", + "callingCodes": [ + "352" + ], + "capital": "Luxembourg", + "altSpellings": [ + "LU", + "Grand Duchy of Luxembourg", + "Grand-Duché de Luxembourg", + "Großherzogtum Luxemburg", + "Groussherzogtum Lëtzebuerg" + ], + "subregion": "Western Europe", + "region": "Europe", + "population": 632275, + "latlng": [ + 49.75, + 6.16666666 + ], + "demonym": "Luxembourger", + "area": 2586.0, + "gini": 35.4, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "BEL", + "FRA", + "DEU" + ], + "nativeName": "Lëtzebuerg", + "numericCode": "442", + "flags": { + "svg": "https://flagcdn.com/lu.svg", + "png": "https://flagcdn.com/w320/lu.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "de", + "iso639_2": "deu", + "name": "German", + "nativeName": "Deutsch" + }, + { + "iso639_1": "lb", + "iso639_2": "ltz", + "name": "Luxembourgish", + "nativeName": "Lëtzebuergesch" + } + ], + "translations": { + "br": "Luksembourg", + "pt": "Luxemburgo", + "nl": "Luxemburg", + "hr": "Luksemburg", + "fa": "لوکزامبورگ", + "de": "Luxemburg", + "es": "Luxemburgo", + "fr": "Luxembourg", + "ja": "ルクセンブルク", + "it": "Lussemburgo", + "hu": "Luxemburg" + }, + "flag": "https://flagcdn.com/lu.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "LUX", + "independent": true + }, + { + "name": "Macao", + "topLevelDomain": [ + ".mo" + ], + "alpha2Code": "MO", + "alpha3Code": "MAC", + "callingCodes": [ + "853" + ], + "altSpellings": [ + "MO", + "澳门", + "Macao Special Administrative Region of the People's Republic of China", + "中華人民共和國澳門特別行政區", + "Região Administrativa Especial de Macau da República Popular da China" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 649342, + "latlng": [ + 22.16666666, + 113.55 + ], + "demonym": "Chinese", + "area": 30.0, + "timezones": [ + "UTC+08:00" + ], + "borders": [ + "CHN" + ], + "nativeName": "澳門", + "numericCode": "446", + "flags": { + "svg": "https://flagcdn.com/mo.svg", + "png": "https://flagcdn.com/w320/mo.png" + }, + "currencies": [ + { + "code": "MOP", + "name": "Macanese pataca", + "symbol": "P" + } + ], + "languages": [ + { + "iso639_1": "zh", + "iso639_2": "zho", + "name": "Chinese", + "nativeName": "中文 (Zhōngwén)" + }, + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Makao", + "pt": "Macau", + "nl": "Macao", + "hr": "Makao", + "fa": "مکائو", + "de": "Macao", + "es": "Macao", + "fr": "Macao", + "ja": "マカオ", + "it": "Macao", + "hu": "Makaó" + }, + "flag": "https://flagcdn.com/mo.svg", + "independent": false + }, + { + "name": "North Macedonia", + "topLevelDomain": [ + ".mk" + ], + "alpha2Code": "MK", + "alpha3Code": "MKD", + "callingCodes": [ + "389" + ], + "capital": "Skopje", + "altSpellings": [ + "MK", + "Republic of Macedonia", + "Република Македонија" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 2083380, + "latlng": [ + 41.83333333, + 22.0 + ], + "demonym": "Macedonian", + "area": 25713.0, + "gini": 33.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "ALB", + "BGR", + "GRC", + "UNK", + "SRB" + ], + "nativeName": "Македонија", + "numericCode": "807", + "flags": { + "svg": "https://flagcdn.com/mk.svg", + "png": "https://flagcdn.com/w320/mk.png" + }, + "currencies": [ + { + "code": "MKD", + "name": "Macedonian denar", + "symbol": "ден" + } + ], + "languages": [ + { + "iso639_1": "mk", + "iso639_2": "mkd", + "name": "Macedonian", + "nativeName": "македонски јазик" + } + ], + "translations": { + "br": "Makedonia an Norzh", + "pt": "Macedónia", + "nl": "Macedonië", + "hr": "Makedonija", + "de": "Mazedonien", + "es": "Macedonia", + "fr": "Macédoine", + "ja": "マケドニア旧ユーゴスラビア共和国", + "it": "Macedonia", + "hu": "Macedónia" + }, + "flag": "https://flagcdn.com/mk.svg", + "regionalBlocs": [ + { + "acronym": "CEFTA", + "name": "Central European Free Trade Agreement" + } + ], + "cioc": "MKD", + "independent": true + }, + { + "name": "Madagascar", + "topLevelDomain": [ + ".mg" + ], + "alpha2Code": "MG", + "alpha3Code": "MDG", + "callingCodes": [ + "261" + ], + "capital": "Antananarivo", + "altSpellings": [ + "MG", + "Republic of Madagascar", + "Repoblikan'i Madagasikara", + "République de Madagascar" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 27691019, + "latlng": [ + -20.0, + 47.0 + ], + "demonym": "Malagasy", + "area": 587041.0, + "gini": 42.6, + "timezones": [ + "UTC+03:00" + ], + "nativeName": "Madagasikara", + "numericCode": "450", + "flags": { + "svg": "https://flagcdn.com/mg.svg", + "png": "https://flagcdn.com/w320/mg.png" + }, + "currencies": [ + { + "code": "MGA", + "name": "Malagasy ariary", + "symbol": "Ar" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "mg", + "iso639_2": "mlg", + "name": "Malagasy", + "nativeName": "fiteny malagasy" + } + ], + "translations": { + "br": "Madagaskar", + "pt": "Madagáscar", + "nl": "Madagaskar", + "hr": "Madagaskar", + "fa": "ماداگاسکار", + "de": "Madagaskar", + "es": "Madagascar", + "fr": "Madagascar", + "ja": "マダガスカル", + "it": "Madagascar", + "hu": "Madagaszkár" + }, + "flag": "https://flagcdn.com/mg.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "MAD", + "independent": true + }, + { + "name": "Malawi", + "topLevelDomain": [ + ".mw" + ], + "alpha2Code": "MW", + "alpha3Code": "MWI", + "callingCodes": [ + "265" + ], + "capital": "Lilongwe", + "altSpellings": [ + "MW", + "Republic of Malawi" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 19129955, + "latlng": [ + -13.5, + 34.0 + ], + "demonym": "Malawian", + "area": 118484.0, + "gini": 44.7, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "MOZ", + "TZA", + "ZMB" + ], + "nativeName": "Malawi", + "numericCode": "454", + "flags": { + "svg": "https://flagcdn.com/mw.svg", + "png": "https://flagcdn.com/w320/mw.png" + }, + "currencies": [ + { + "code": "MWK", + "name": "Malawian kwacha", + "symbol": "MK" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "ny", + "iso639_2": "nya", + "name": "Chichewa", + "nativeName": "chiCheŵa" + } + ], + "translations": { + "br": "Malawi", + "pt": "Malávi", + "nl": "Malawi", + "hr": "Malavi", + "fa": "مالاوی", + "de": "Malawi", + "es": "Malawi", + "fr": "Malawi", + "ja": "マラウイ", + "it": "Malawi", + "hu": "Malawi" + }, + "flag": "https://flagcdn.com/mw.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "MAW", + "independent": true + }, + { + "name": "Malaysia", + "topLevelDomain": [ + ".my" + ], + "alpha2Code": "MY", + "alpha3Code": "MYS", + "callingCodes": [ + "60" + ], + "capital": "Kuala Lumpur", + "altSpellings": [ + "MY" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 32365998, + "latlng": [ + 2.5, + 112.5 + ], + "demonym": "Malaysian", + "area": 330803.0, + "gini": 41.1, + "timezones": [ + "UTC+08:00" + ], + "borders": [ + "BRN", + "IDN", + "THA" + ], + "nativeName": "Malaysia", + "numericCode": "458", + "flags": { + "svg": "https://flagcdn.com/my.svg", + "png": "https://flagcdn.com/w320/my.png" + }, + "currencies": [ + { + "code": "MYR", + "name": "Malaysian ringgit", + "symbol": "RM" + } + ], + "languages": [ + { + "iso639_1": "ms", + "iso639_2": "zsm", + "name": "Malaysian", + "nativeName": "بهاس مليسيا" + } + ], + "translations": { + "br": "Malaysia", + "pt": "Malásia", + "nl": "Maleisië", + "hr": "Malezija", + "fa": "مالزی", + "de": "Malaysia", + "es": "Malasia", + "fr": "Malaisie", + "ja": "マレーシア", + "it": "Malesia", + "hu": "Malajzia" + }, + "flag": "https://flagcdn.com/my.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "MAS", + "independent": true + }, + { + "name": "Maldives", + "topLevelDomain": [ + ".mv" + ], + "alpha2Code": "MV", + "alpha3Code": "MDV", + "callingCodes": [ + "960" + ], + "capital": "Malé", + "altSpellings": [ + "MV", + "Maldive Islands", + "Republic of the Maldives", + "Dhivehi Raajjeyge Jumhooriyya" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 540542, + "latlng": [ + 3.25, + 73.0 + ], + "demonym": "Maldivan", + "area": 300.0, + "gini": 31.3, + "timezones": [ + "UTC+05:00" + ], + "nativeName": "Maldives", + "numericCode": "462", + "flags": { + "svg": "https://flagcdn.com/mv.svg", + "png": "https://flagcdn.com/w320/mv.png" + }, + "currencies": [ + { + "code": "MVR", + "name": "Maldivian rufiyaa", + "symbol": ".ރ" + } + ], + "languages": [ + { + "iso639_1": "dv", + "iso639_2": "div", + "name": "Divehi", + "nativeName": "ދިވެހި" + } + ], + "translations": { + "br": "Maldivez", + "pt": "Maldivas", + "nl": "Maldiven", + "hr": "Maldivi", + "fa": "مالدیو", + "de": "Malediven", + "es": "Maldivas", + "fr": "Maldives", + "ja": "モルディブ", + "it": "Maldive", + "hu": "Maldív-szigetek" + }, + "flag": "https://flagcdn.com/mv.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "MDV", + "independent": true + }, + { + "name": "Mali", + "topLevelDomain": [ + ".ml" + ], + "alpha2Code": "ML", + "alpha3Code": "MLI", + "callingCodes": [ + "223" + ], + "capital": "Bamako", + "altSpellings": [ + "ML", + "Republic of Mali", + "République du Mali" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 20250834, + "latlng": [ + 17.0, + -4.0 + ], + "demonym": "Malian", + "area": 1240192.0, + "gini": 33.0, + "timezones": [ + "UTC" + ], + "borders": [ + "DZA", + "BFA", + "GIN", + "CIV", + "MRT", + "NER", + "SEN" + ], + "nativeName": "Mali", + "numericCode": "466", + "flags": { + "svg": "https://flagcdn.com/ml.svg", + "png": "https://flagcdn.com/w320/ml.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Mali", + "pt": "Mali", + "nl": "Mali", + "hr": "Mali", + "fa": "مالی", + "de": "Mali", + "es": "Mali", + "fr": "Mali", + "ja": "マリ", + "it": "Mali", + "hu": "Mali" + }, + "flag": "https://flagcdn.com/ml.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "MLI", + "independent": true + }, + { + "name": "Malta", + "topLevelDomain": [ + ".mt" + ], + "alpha2Code": "MT", + "alpha3Code": "MLT", + "callingCodes": [ + "356" + ], + "capital": "Valletta", + "altSpellings": [ + "MT", + "Republic of Malta", + "Repubblika ta' Malta" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 525285, + "latlng": [ + 35.83333333, + 14.58333333 + ], + "demonym": "Maltese", + "area": 316.0, + "gini": 28.7, + "timezones": [ + "UTC+01:00" + ], + "nativeName": "Malta", + "numericCode": "470", + "flags": { + "svg": "https://flagcdn.com/mt.svg", + "png": "https://flagcdn.com/w320/mt.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "mt", + "iso639_2": "mlt", + "name": "Maltese", + "nativeName": "Malti" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Malta", + "pt": "Malta", + "nl": "Malta", + "hr": "Malta", + "fa": "مالت", + "de": "Malta", + "es": "Malta", + "fr": "Malte", + "ja": "マルタ", + "it": "Malta", + "hu": "Málta" + }, + "flag": "https://flagcdn.com/mt.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "MLT", + "independent": true + }, + { + "name": "Marshall Islands", + "topLevelDomain": [ + ".mh" + ], + "alpha2Code": "MH", + "alpha3Code": "MHL", + "callingCodes": [ + "692" + ], + "capital": "Majuro", + "altSpellings": [ + "MH", + "Republic of the Marshall Islands", + "Aolepān Aorōkin M̧ajeļ" + ], + "subregion": "Micronesia", + "region": "Oceania", + "population": 59194, + "latlng": [ + 9.0, + 168.0 + ], + "demonym": "Marshallese", + "area": 181.0, + "timezones": [ + "UTC+12:00" + ], + "nativeName": "M̧ajeļ", + "numericCode": "584", + "flags": { + "svg": "https://flagcdn.com/mh.svg", + "png": "https://flagcdn.com/w320/mh.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "mh", + "iso639_2": "mah", + "name": "Marshallese", + "nativeName": "Kajin M̧ajeļ" + } + ], + "translations": { + "br": "Inizi Marshall", + "pt": "Ilhas Marshall", + "nl": "Marshalleilanden", + "hr": "Maršalovi Otoci", + "fa": "جزایر مارشال", + "de": "Marshallinseln", + "es": "Islas Marshall", + "fr": "Îles Marshall", + "ja": "マーシャル諸島", + "it": "Isole Marshall", + "hu": "Marshall-szigetek" + }, + "flag": "https://flagcdn.com/mh.svg", + "cioc": "MHL", + "independent": true + }, + { + "name": "Martinique", + "topLevelDomain": [ + ".mq" + ], + "alpha2Code": "MQ", + "alpha3Code": "MTQ", + "callingCodes": [ + "596" + ], + "capital": "Fort-de-France", + "altSpellings": [ + "MQ" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 378243, + "latlng": [ + 14.666667, + -61.0 + ], + "demonym": "French", + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Martinique", + "numericCode": "474", + "flags": { + "svg": "https://flagcdn.com/mq.svg", + "png": "https://flagcdn.com/w320/mq.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Martinik", + "pt": "Martinica", + "nl": "Martinique", + "hr": "Martinique", + "fa": "مونتسرات", + "de": "Martinique", + "es": "Martinica", + "fr": "Martinique", + "ja": "マルティニーク", + "it": "Martinica", + "hu": "Martinique" + }, + "flag": "https://flagcdn.com/mq.svg", + "independent": false + }, + { + "name": "Mauritania", + "topLevelDomain": [ + ".mr" + ], + "alpha2Code": "MR", + "alpha3Code": "MRT", + "callingCodes": [ + "222" + ], + "capital": "Nouakchott", + "altSpellings": [ + "MR", + "Islamic Republic of Mauritania", + "al-Jumhūriyyah al-ʾIslāmiyyah al-Mūrītāniyyah" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 4649660, + "latlng": [ + 20.0, + -12.0 + ], + "demonym": "Mauritanian", + "area": 1030700.0, + "gini": 32.6, + "timezones": [ + "UTC" + ], + "borders": [ + "DZA", + "MLI", + "SEN", + "ESH" + ], + "nativeName": "موريتانيا", + "numericCode": "478", + "flags": { + "svg": "https://flagcdn.com/mr.svg", + "png": "https://flagcdn.com/w320/mr.png" + }, + "currencies": [ + { + "code": "MRO", + "name": "Mauritanian ouguiya", + "symbol": "UM" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Maouritania", + "pt": "Mauritânia", + "nl": "Mauritanië", + "hr": "Mauritanija", + "fa": "موریتانی", + "de": "Mauretanien", + "es": "Mauritania", + "fr": "Mauritanie", + "ja": "モーリタニア", + "it": "Mauritania", + "hu": "Mauritánia" + }, + "flag": "https://flagcdn.com/mr.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "MTN", + "independent": true + }, + { + "name": "Mauritius", + "topLevelDomain": [ + ".mu" + ], + "alpha2Code": "MU", + "alpha3Code": "MUS", + "callingCodes": [ + "230" + ], + "capital": "Port Louis", + "altSpellings": [ + "MU", + "Republic of Mauritius", + "République de Maurice" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 1265740, + "latlng": [ + -20.28333333, + 57.55 + ], + "demonym": "Mauritian", + "area": 2040.0, + "gini": 36.8, + "timezones": [ + "UTC+04:00" + ], + "nativeName": "Maurice", + "numericCode": "480", + "flags": { + "svg": "https://flagcdn.com/mu.svg", + "png": "https://flagcdn.com/w320/mu.png" + }, + "currencies": [ + { + "code": "MUR", + "name": "Mauritian rupee", + "symbol": "₨" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Moris", + "pt": "Maurícia", + "nl": "Mauritius", + "hr": "Mauricijus", + "fa": "موریس", + "de": "Mauritius", + "es": "Mauricio", + "fr": "Île Maurice", + "ja": "モーリシャス", + "it": "Mauritius", + "hu": "Mauritius" + }, + "flag": "https://flagcdn.com/mu.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "MRI", + "independent": true + }, + { + "name": "Mayotte", + "topLevelDomain": [ + ".yt" + ], + "alpha2Code": "YT", + "alpha3Code": "MYT", + "callingCodes": [ + "262" + ], + "capital": "Mamoudzou", + "altSpellings": [ + "YT", + "Department of Mayotte", + "Département de Mayotte" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 226915, + "latlng": [ + -12.83333333, + 45.16666666 + ], + "demonym": "French", + "timezones": [ + "UTC+03:00" + ], + "nativeName": "Mayotte", + "numericCode": "175", + "flags": { + "svg": "https://flagcdn.com/yt.svg", + "png": "https://flagcdn.com/w320/yt.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Mayotte", + "pt": "Mayotte", + "nl": "Mayotte", + "hr": "Mayotte", + "fa": "مایوت", + "de": "Mayotte", + "es": "Mayotte", + "fr": "Mayotte", + "ja": "マヨット", + "it": "Mayotte", + "hu": "Mayotte" + }, + "flag": "https://flagcdn.com/yt.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "independent": false + }, + { + "name": "Mexico", + "topLevelDomain": [ + ".mx" + ], + "alpha2Code": "MX", + "alpha3Code": "MEX", + "callingCodes": [ + "52" + ], + "capital": "Mexico City", + "altSpellings": [ + "MX", + "Mexicanos", + "United Mexican States", + "Estados Unidos Mexicanos" + ], + "subregion": "North America", + "region": "Americas", + "population": 128932753, + "latlng": [ + 23.0, + -102.0 + ], + "demonym": "Mexican", + "area": 1964375.0, + "gini": 45.4, + "timezones": [ + "UTC-08:00", + "UTC-07:00", + "UTC-06:00" + ], + "borders": [ + "BLZ", + "GTM", + "USA" + ], + "nativeName": "México", + "numericCode": "484", + "flags": { + "svg": "https://flagcdn.com/mx.svg", + "png": "https://flagcdn.com/w320/mx.png" + }, + "currencies": [ + { + "code": "MXN", + "name": "Mexican peso", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Mec'hiko", + "pt": "México", + "nl": "Mexico", + "hr": "Meksiko", + "fa": "مکزیک", + "de": "Mexiko", + "es": "México", + "fr": "Mexique", + "ja": "メキシコ", + "it": "Messico", + "hu": "Mexikó" + }, + "flag": "https://flagcdn.com/mx.svg", + "regionalBlocs": [ + { + "acronym": "PA", + "name": "Pacific Alliance", + "otherNames": [ + "Alianza del Pacífico" + ] + }, + { + "acronym": "NAFTA", + "name": "North American Free Trade Agreement", + "otherNames": [ + "Tratado de Libre Comercio de América del Norte", + "Accord de Libre-échange Nord-Américain" + ] + } + ], + "cioc": "MEX", + "independent": true + }, + { + "name": "Micronesia (Federated States of)", + "topLevelDomain": [ + ".fm" + ], + "alpha2Code": "FM", + "alpha3Code": "FSM", + "callingCodes": [ + "691" + ], + "capital": "Palikir", + "altSpellings": [ + "FM", + "Federated States of Micronesia" + ], + "subregion": "Micronesia", + "region": "Oceania", + "population": 115021, + "latlng": [ + 6.91666666, + 158.25 + ], + "demonym": "Micronesian", + "area": 702.0, + "gini": 40.1, + "timezones": [ + "UTC+10:00", + "UTC+11:00" + ], + "nativeName": "Micronesia", + "numericCode": "583", + "flags": { + "svg": "https://flagcdn.com/fm.svg", + "png": "https://flagcdn.com/w320/fm.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Mikronezia", + "pt": "Micronésia", + "nl": "Micronesië", + "hr": "Mikronezija", + "fa": "ایالات فدرال میکرونزی", + "de": "Mikronesien", + "es": "Micronesia", + "fr": "Micronésie", + "ja": "ミクロネシア連邦", + "it": "Micronesia", + "hu": "Mikronézia" + }, + "flag": "https://flagcdn.com/fm.svg", + "cioc": "FSM", + "independent": true + }, + { + "name": "Moldova (Republic of)", + "topLevelDomain": [ + ".md" + ], + "alpha2Code": "MD", + "alpha3Code": "MDA", + "callingCodes": [ + "373" + ], + "capital": "Chișinău", + "altSpellings": [ + "MD", + "Republic of Moldova", + "Republica Moldova" + ], + "subregion": "Eastern Europe", + "region": "Europe", + "population": 2617820, + "latlng": [ + 47.0, + 29.0 + ], + "demonym": "Moldovan", + "area": 33846.0, + "gini": 25.7, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "ROU", + "UKR" + ], + "nativeName": "Moldova", + "numericCode": "498", + "flags": { + "svg": "https://flagcdn.com/md.svg", + "png": "https://flagcdn.com/w320/md.png" + }, + "currencies": [ + { + "code": "MDL", + "name": "Moldovan leu", + "symbol": "L" + } + ], + "languages": [ + { + "iso639_1": "ro", + "iso639_2": "ron", + "name": "Romanian", + "nativeName": "Română" + } + ], + "translations": { + "br": "Moldova", + "pt": "Moldávia", + "nl": "Moldavië", + "hr": "Moldova", + "fa": "مولداوی", + "de": "Moldawie", + "es": "Moldavia", + "fr": "Moldavie", + "ja": "モルドバ共和国", + "it": "Moldavia", + "hu": "Moldova" + }, + "flag": "https://flagcdn.com/md.svg", + "regionalBlocs": [ + { + "acronym": "CEFTA", + "name": "Central European Free Trade Agreement" + } + ], + "cioc": "MDA", + "independent": true + }, + { + "name": "Monaco", + "topLevelDomain": [ + ".mc" + ], + "alpha2Code": "MC", + "alpha3Code": "MCO", + "callingCodes": [ + "377" + ], + "capital": "Monaco", + "altSpellings": [ + "MC", + "Principality of Monaco", + "Principauté de Monaco" + ], + "subregion": "Western Europe", + "region": "Europe", + "population": 39244, + "latlng": [ + 43.73333333, + 7.4 + ], + "demonym": "Monegasque", + "area": 2.02, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "FRA" + ], + "nativeName": "Monaco", + "numericCode": "492", + "flags": { + "svg": "https://flagcdn.com/mc.svg", + "png": "https://flagcdn.com/w320/mc.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Monako", + "pt": "Mónaco", + "nl": "Monaco", + "hr": "Monako", + "fa": "موناکو", + "de": "Monaco", + "es": "Mónaco", + "fr": "Monaco", + "ja": "モナコ", + "it": "Principato di Monaco", + "hu": "Monaco" + }, + "flag": "https://flagcdn.com/mc.svg", + "cioc": "MON", + "independent": true + }, + { + "name": "Mongolia", + "topLevelDomain": [ + ".mn" + ], + "alpha2Code": "MN", + "alpha3Code": "MNG", + "callingCodes": [ + "976" + ], + "capital": "Ulan Bator", + "altSpellings": [ + "MN" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 3278292, + "latlng": [ + 46.0, + 105.0 + ], + "demonym": "Mongolian", + "area": 1564110.0, + "gini": 32.7, + "timezones": [ + "UTC+07:00", + "UTC+08:00" + ], + "borders": [ + "CHN", + "RUS" + ], + "nativeName": "Монгол улс", + "numericCode": "496", + "flags": { + "svg": "https://flagcdn.com/mn.svg", + "png": "https://flagcdn.com/w320/mn.png" + }, + "currencies": [ + { + "code": "MNT", + "name": "Mongolian tögrög", + "symbol": "₮" + } + ], + "languages": [ + { + "iso639_1": "mn", + "iso639_2": "mon", + "name": "Mongolian", + "nativeName": "Монгол хэл" + } + ], + "translations": { + "br": "Mongolia", + "pt": "Mongólia", + "nl": "Mongolië", + "hr": "Mongolija", + "fa": "مغولستان", + "de": "Mongolei", + "es": "Mongolia", + "fr": "Mongolie", + "ja": "モンゴル", + "it": "Mongolia", + "hu": "Mongólia" + }, + "flag": "https://flagcdn.com/mn.svg", + "cioc": "MGL", + "independent": true + }, + { + "name": "Montenegro", + "topLevelDomain": [ + ".me" + ], + "alpha2Code": "ME", + "alpha3Code": "MNE", + "callingCodes": [ + "382" + ], + "capital": "Podgorica", + "altSpellings": [ + "ME", + "Crna Gora" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 621718, + "latlng": [ + 42.5, + 19.3 + ], + "demonym": "Montenegrin", + "area": 13812.0, + "gini": 38.5, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "ALB", + "BIH", + "HRV", + "UNK", + "SRB" + ], + "nativeName": "Црна Гора", + "numericCode": "499", + "flags": { + "svg": "https://flagcdn.com/me.svg", + "png": "https://flagcdn.com/w320/me.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "sr", + "iso639_2": "srp", + "name": "Serbian", + "nativeName": "српски језик" + }, + { + "iso639_1": "bs", + "iso639_2": "bos", + "name": "Bosnian", + "nativeName": "bosanski jezik" + }, + { + "iso639_1": "sq", + "iso639_2": "sqi", + "name": "Albanian", + "nativeName": "Shqip" + }, + { + "iso639_1": "hr", + "iso639_2": "hrv", + "name": "Croatian", + "nativeName": "hrvatski jezik" + } + ], + "translations": { + "br": "Montenegro", + "pt": "Montenegro", + "nl": "Montenegro", + "hr": "Crna Gora", + "fa": "مونته‌نگرو", + "de": "Montenegro", + "es": "Montenegro", + "fr": "Monténégro", + "ja": "モンテネグロ", + "it": "Montenegro", + "hu": "Montenegró" + }, + "flag": "https://flagcdn.com/me.svg", + "regionalBlocs": [ + { + "acronym": "CEFTA", + "name": "Central European Free Trade Agreement" + } + ], + "cioc": "MNE", + "independent": true + }, + { + "name": "Montserrat", + "topLevelDomain": [ + ".ms" + ], + "alpha2Code": "MS", + "alpha3Code": "MSR", + "callingCodes": [ + "1" + ], + "capital": "Plymouth", + "altSpellings": [ + "MS" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 4922, + "latlng": [ + 16.75, + -62.2 + ], + "demonym": "Montserratian", + "area": 102.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Montserrat", + "numericCode": "500", + "flags": { + "svg": "https://flagcdn.com/ms.svg", + "png": "https://flagcdn.com/w320/ms.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Montserrat", + "pt": "Monserrate", + "nl": "Montserrat", + "hr": "Montserrat", + "fa": "مایوت", + "de": "Montserrat", + "es": "Montserrat", + "fr": "Montserrat", + "ja": "モントセラト", + "it": "Montserrat", + "hu": "Montserrat" + }, + "flag": "https://flagcdn.com/ms.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "independent": false + }, + { + "name": "Morocco", + "topLevelDomain": [ + ".ma" + ], + "alpha2Code": "MA", + "alpha3Code": "MAR", + "callingCodes": [ + "212" + ], + "capital": "Rabat", + "altSpellings": [ + "MA", + "Kingdom of Morocco", + "Al-Mamlakah al-Maġribiyah" + ], + "subregion": "Northern Africa", + "region": "Africa", + "population": 36910558, + "latlng": [ + 32.0, + -5.0 + ], + "demonym": "Moroccan", + "area": 446550.0, + "gini": 39.5, + "timezones": [ + "UTC" + ], + "borders": [ + "DZA", + "ESH", + "ESP" + ], + "nativeName": "المغرب", + "numericCode": "504", + "flags": { + "svg": "https://flagcdn.com/ma.svg", + "png": "https://flagcdn.com/w320/ma.png" + }, + "currencies": [ + { + "code": "MAD", + "name": "Moroccan dirham", + "symbol": "د.م." + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Maroko", + "pt": "Marrocos", + "nl": "Marokko", + "hr": "Maroko", + "fa": "المغرب", + "de": "Marokko", + "es": "Marruecos", + "fr": "Maroc", + "ja": "モロッコ", + "it": "Marocco", + "hu": "Marokkó" + }, + "flag": "https://flagcdn.com/ma.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "MAR", + "independent": true + }, + { + "name": "Mozambique", + "topLevelDomain": [ + ".mz" + ], + "alpha2Code": "MZ", + "alpha3Code": "MOZ", + "callingCodes": [ + "258" + ], + "capital": "Maputo", + "altSpellings": [ + "MZ", + "Republic of Mozambique", + "República de Moçambique" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 31255435, + "latlng": [ + -18.25, + 35.0 + ], + "demonym": "Mozambican", + "area": 801590.0, + "gini": 54.0, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "MWI", + "ZAF", + "SWZ", + "TZA", + "ZMB", + "ZWE" + ], + "nativeName": "Moçambique", + "numericCode": "508", + "flags": { + "svg": "https://flagcdn.com/mz.svg", + "png": "https://flagcdn.com/w320/mz.png" + }, + "currencies": [ + { + "code": "MZN", + "name": "Mozambican metical", + "symbol": "MT" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Mozambik", + "pt": "Moçambique", + "nl": "Mozambique", + "hr": "Mozambik", + "fa": "موزامبیک", + "de": "Mosambik", + "es": "Mozambique", + "fr": "Mozambique", + "ja": "モザンビーク", + "it": "Mozambico", + "hu": "Mozambik" + }, + "flag": "https://flagcdn.com/mz.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "MOZ", + "independent": true + }, + { + "name": "Myanmar", + "topLevelDomain": [ + ".mm" + ], + "alpha2Code": "MM", + "alpha3Code": "MMR", + "callingCodes": [ + "95" + ], + "capital": "Naypyidaw", + "altSpellings": [ + "MM", + "Burma", + "Republic of the Union of Myanmar", + "Pyidaunzu Thanmăda Myăma Nainngandaw" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 54409794, + "latlng": [ + 22.0, + 98.0 + ], + "demonym": "Burmese", + "area": 676578.0, + "gini": 30.7, + "timezones": [ + "UTC+06:30" + ], + "borders": [ + "BGD", + "CHN", + "IND", + "LAO", + "THA" + ], + "nativeName": "Myanma", + "numericCode": "104", + "flags": { + "svg": "https://flagcdn.com/mm.svg", + "png": "https://flagcdn.com/w320/mm.png" + }, + "currencies": [ + { + "code": "MMK", + "name": "Burmese kyat", + "symbol": "Ks" + } + ], + "languages": [ + { + "iso639_1": "my", + "iso639_2": "mya", + "name": "Burmese", + "nativeName": "ဗမာစာ" + } + ], + "translations": { + "br": "Myanmar", + "pt": "Myanmar", + "nl": "Myanmar", + "hr": "Mijanmar", + "fa": "میانمار", + "de": "Myanmar", + "es": "Myanmar", + "fr": "Myanmar", + "ja": "ミャンマー", + "it": "Birmania", + "hu": "Mianmar" + }, + "flag": "https://flagcdn.com/mm.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "MYA", + "independent": true + }, + { + "name": "Namibia", + "topLevelDomain": [ + ".na" + ], + "alpha2Code": "NA", + "alpha3Code": "NAM", + "callingCodes": [ + "264" + ], + "capital": "Windhoek", + "altSpellings": [ + "NA", + "Namibië", + "Republic of Namibia" + ], + "subregion": "Southern Africa", + "region": "Africa", + "population": 2540916, + "latlng": [ + -22.0, + 17.0 + ], + "demonym": "Namibian", + "area": 825615.0, + "gini": 59.1, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AGO", + "BWA", + "ZAF", + "ZMB" + ], + "nativeName": "Namibia", + "numericCode": "516", + "flags": { + "svg": "https://flagcdn.com/na.svg", + "png": "https://flagcdn.com/w320/na.png" + }, + "currencies": [ + { + "code": "NAD", + "name": "Namibian dollar", + "symbol": "$" + }, + { + "code": "ZAR", + "name": "South African rand", + "symbol": "R" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "af", + "iso639_2": "afr", + "name": "Afrikaans", + "nativeName": "Afrikaans" + } + ], + "translations": { + "br": "Namibia", + "pt": "Namíbia", + "nl": "Namibië", + "hr": "Namibija", + "fa": "نامیبیا", + "de": "Namibia", + "es": "Namibia", + "fr": "Namibie", + "ja": "ナミビア", + "it": "Namibia", + "hu": "Namíbia" + }, + "flag": "https://flagcdn.com/na.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "NAM", + "independent": true + }, + { + "name": "Nauru", + "topLevelDomain": [ + ".nr" + ], + "alpha2Code": "NR", + "alpha3Code": "NRU", + "callingCodes": [ + "674" + ], + "capital": "Yaren", + "altSpellings": [ + "NR", + "Naoero", + "Pleasant Island", + "Republic of Nauru", + "Ripublik Naoero" + ], + "subregion": "Micronesia", + "region": "Oceania", + "population": 10834, + "latlng": [ + -0.53333333, + 166.91666666 + ], + "demonym": "Nauruan", + "area": 21.0, + "gini": 34.8, + "timezones": [ + "UTC+12:00" + ], + "nativeName": "Nauru", + "numericCode": "520", + "flags": { + "svg": "https://flagcdn.com/nr.svg", + "png": "https://flagcdn.com/w320/nr.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "na", + "iso639_2": "nau", + "name": "Nauruan", + "nativeName": "Dorerin Naoero" + } + ], + "translations": { + "br": "Nauru", + "pt": "Nauru", + "nl": "Nauru", + "hr": "Nauru", + "fa": "نائورو", + "de": "Nauru", + "es": "Nauru", + "fr": "Nauru", + "ja": "ナウル", + "it": "Nauru", + "hu": "Nauru" + }, + "flag": "https://flagcdn.com/nr.svg", + "cioc": "NRU", + "independent": true + }, + { + "name": "Nepal", + "topLevelDomain": [ + ".np" + ], + "alpha2Code": "NP", + "alpha3Code": "NPL", + "callingCodes": [ + "977" + ], + "capital": "Kathmandu", + "altSpellings": [ + "NP", + "Federal Democratic Republic of Nepal", + "Loktāntrik Ganatantra Nepāl" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 29136808, + "latlng": [ + 28.0, + 84.0 + ], + "demonym": "Nepalese", + "area": 147181.0, + "gini": 32.8, + "timezones": [ + "UTC+05:45" + ], + "borders": [ + "CHN", + "IND" + ], + "nativeName": "नेपाल", + "numericCode": "524", + "flags": { + "svg": "https://flagcdn.com/np.svg", + "png": "https://flagcdn.com/w320/np.png" + }, + "currencies": [ + { + "code": "NPR", + "name": "Nepalese rupee", + "symbol": "₨" + } + ], + "languages": [ + { + "iso639_1": "ne", + "iso639_2": "nep", + "name": "Nepali", + "nativeName": "नेपाली" + } + ], + "translations": { + "br": "Nepal", + "pt": "Nepal", + "nl": "Nepal", + "hr": "Nepal", + "fa": "نپال", + "de": "Népal", + "es": "Nepal", + "fr": "Népal", + "ja": "ネパール", + "it": "Nepal", + "hu": "Nepál" + }, + "flag": "https://flagcdn.com/np.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "NEP", + "independent": true + }, + { + "name": "Netherlands", + "topLevelDomain": [ + ".nl" + ], + "alpha2Code": "NL", + "alpha3Code": "NLD", + "callingCodes": [ + "31" + ], + "capital": "Amsterdam", + "altSpellings": [ + "NL", + "Holland", + "Nederland" + ], + "subregion": "Western Europe", + "region": "Europe", + "population": 17441139, + "latlng": [ + 52.5, + 5.75 + ], + "demonym": "Dutch", + "area": 41850.0, + "gini": 28.1, + "timezones": [ + "UTC-04:00", + "UTC+01:00" + ], + "borders": [ + "BEL", + "DEU" + ], + "nativeName": "Nederland", + "numericCode": "528", + "flags": { + "svg": "https://flagcdn.com/nl.svg", + "png": "https://flagcdn.com/w320/nl.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + } + ], + "translations": { + "br": "Izelvroioù", + "pt": "Países Baixos", + "nl": "Nederland", + "hr": "Nizozemska", + "fa": "پادشاهی هلند", + "de": "Niederlande", + "es": "Países Bajos", + "fr": "Pays-Bas", + "ja": "オランダ", + "it": "Paesi Bassi", + "hu": "Hollandia" + }, + "flag": "https://flagcdn.com/nl.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "NED", + "independent": true + }, + { + "name": "New Caledonia", + "topLevelDomain": [ + ".nc" + ], + "alpha2Code": "NC", + "alpha3Code": "NCL", + "callingCodes": [ + "687" + ], + "capital": "Nouméa", + "altSpellings": [ + "NC" + ], + "subregion": "Melanesia", + "region": "Oceania", + "population": 271960, + "latlng": [ + -21.5, + 165.5 + ], + "demonym": "New Caledonian", + "area": 18575.0, + "timezones": [ + "UTC+11:00" + ], + "nativeName": "Nouvelle-Calédonie", + "numericCode": "540", + "flags": { + "svg": "https://flagcdn.com/nc.svg", + "png": "https://flagcdn.com/w320/nc.png" + }, + "currencies": [ + { + "code": "XPF", + "name": "CFP franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Kaledonia-Nevez", + "pt": "Nova Caledónia", + "nl": "Nieuw-Caledonië", + "hr": "Nova Kaledonija", + "fa": "کالدونیای جدید", + "de": "Neukaledonien", + "es": "Nueva Caledonia", + "fr": "Nouvelle-Calédonie", + "ja": "ニューカレドニア", + "it": "Nuova Caledonia", + "hu": "Új-Kaledónia" + }, + "flag": "https://flagcdn.com/nc.svg", + "independent": false + }, + { + "name": "New Zealand", + "topLevelDomain": [ + ".nz" + ], + "alpha2Code": "NZ", + "alpha3Code": "NZL", + "callingCodes": [ + "64" + ], + "capital": "Wellington", + "altSpellings": [ + "NZ", + "Aotearoa" + ], + "subregion": "Australia and New Zealand", + "region": "Oceania", + "population": 5084300, + "latlng": [ + -41.0, + 174.0 + ], + "demonym": "New Zealander", + "area": 270467.0, + "timezones": [ + "UTC-11:00", + "UTC-10:00", + "UTC+12:00", + "UTC+12:45", + "UTC+13:00" + ], + "nativeName": "New Zealand", + "numericCode": "554", + "flags": { + "svg": "https://flagcdn.com/nz.svg", + "png": "https://flagcdn.com/w320/nz.png" + }, + "currencies": [ + { + "code": "NZD", + "name": "New Zealand dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "mi", + "iso639_2": "mri", + "name": "Māori", + "nativeName": "te reo Māori" + } + ], + "translations": { + "br": "Zeland-Nevez", + "pt": "Nova Zelândia", + "nl": "Nieuw-Zeeland", + "hr": "Novi Zeland", + "fa": "نیوزیلند", + "de": "Neuseeland", + "es": "Nueva Zelanda", + "fr": "Nouvelle-Zélande", + "ja": "ニュージーランド", + "it": "Nuova Zelanda", + "hu": "Új-Zéland" + }, + "flag": "https://flagcdn.com/nz.svg", + "cioc": "NZL", + "independent": true + }, + { + "name": "Nicaragua", + "topLevelDomain": [ + ".ni" + ], + "alpha2Code": "NI", + "alpha3Code": "NIC", + "callingCodes": [ + "505" + ], + "capital": "Managua", + "altSpellings": [ + "NI", + "Republic of Nicaragua", + "República de Nicaragua" + ], + "subregion": "Central America", + "region": "Americas", + "population": 6624554, + "latlng": [ + 13.0, + -85.0 + ], + "demonym": "Nicaraguan", + "area": 130373.0, + "gini": 46.2, + "timezones": [ + "UTC-06:00" + ], + "borders": [ + "CRI", + "HND" + ], + "nativeName": "Nicaragua", + "numericCode": "558", + "flags": { + "svg": "https://flagcdn.com/ni.svg", + "png": "https://flagcdn.com/w320/ni.png" + }, + "currencies": [ + { + "code": "NIO", + "name": "Nicaraguan córdoba", + "symbol": "C$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Nicaragua", + "pt": "Nicarágua", + "nl": "Nicaragua", + "hr": "Nikaragva", + "fa": "نیکاراگوئه", + "de": "Nicaragua", + "es": "Nicaragua", + "fr": "Nicaragua", + "ja": "ニカラグア", + "it": "Nicaragua", + "hu": "Nicaragua" + }, + "flag": "https://flagcdn.com/ni.svg", + "regionalBlocs": [ + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "NCA", + "independent": true + }, + { + "name": "Niger", + "topLevelDomain": [ + ".ne" + ], + "alpha2Code": "NE", + "alpha3Code": "NER", + "callingCodes": [ + "227" + ], + "capital": "Niamey", + "altSpellings": [ + "NE", + "Nijar", + "Republic of Niger", + "République du Niger" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 24206636, + "latlng": [ + 16.0, + 8.0 + ], + "demonym": "Nigerien", + "area": 1267000.0, + "gini": 34.3, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "DZA", + "BEN", + "BFA", + "TCD", + "LBY", + "MLI", + "NGA" + ], + "nativeName": "Niger", + "numericCode": "562", + "flags": { + "svg": "https://flagcdn.com/ne.svg", + "png": "https://flagcdn.com/w320/ne.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Niger", + "pt": "Níger", + "nl": "Niger", + "hr": "Niger", + "fa": "نیجر", + "de": "Niger", + "es": "Níger", + "fr": "Niger", + "ja": "ニジェール", + "it": "Niger", + "hu": "Niger" + }, + "flag": "https://flagcdn.com/ne.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "NIG", + "independent": true + }, + { + "name": "Nigeria", + "topLevelDomain": [ + ".ng" + ], + "alpha2Code": "NG", + "alpha3Code": "NGA", + "callingCodes": [ + "234" + ], + "capital": "Abuja", + "altSpellings": [ + "NG", + "Nijeriya", + "Naíjíríà", + "Federal Republic of Nigeria" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 206139587, + "latlng": [ + 10.0, + 8.0 + ], + "demonym": "Nigerian", + "area": 923768.0, + "gini": 35.1, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "BEN", + "CMR", + "TCD", + "NER" + ], + "nativeName": "Nigeria", + "numericCode": "566", + "flags": { + "svg": "https://flagcdn.com/ng.svg", + "png": "https://flagcdn.com/w320/ng.png" + }, + "currencies": [ + { + "code": "NGN", + "name": "Nigerian naira", + "symbol": "₦" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Nigeria", + "pt": "Nigéria", + "nl": "Nigeria", + "hr": "Nigerija", + "fa": "نیجریه", + "de": "Nigeria", + "es": "Nigeria", + "fr": "Nigéria", + "ja": "ナイジェリア", + "it": "Nigeria", + "hu": "Nigéria" + }, + "flag": "https://flagcdn.com/ng.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "NGR", + "independent": true + }, + { + "name": "Niue", + "topLevelDomain": [ + ".nu" + ], + "alpha2Code": "NU", + "alpha3Code": "NIU", + "callingCodes": [ + "683" + ], + "capital": "Alofi", + "altSpellings": [ + "NU" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 1470, + "latlng": [ + -19.03333333, + -169.86666666 + ], + "demonym": "Niuean", + "area": 260.0, + "timezones": [ + "UTC-11:00" + ], + "nativeName": "Niuē", + "numericCode": "570", + "flags": { + "svg": "https://flagcdn.com/nu.svg", + "png": "https://flagcdn.com/w320/nu.png" + }, + "currencies": [ + { + "code": "NZD", + "name": "New Zealand dollar", + "symbol": "$" + }, + { + "code": "NZD", + "name": "Niue dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Niue", + "pt": "Niue", + "nl": "Niue", + "hr": "Niue", + "fa": "نیووی", + "de": "Niue", + "es": "Niue", + "fr": "Niue", + "ja": "ニウエ", + "it": "Niue", + "hu": "Niue" + }, + "flag": "https://flagcdn.com/nu.svg", + "independent": true + }, + { + "name": "Norfolk Island", + "topLevelDomain": [ + ".nf" + ], + "alpha2Code": "NF", + "alpha3Code": "NFK", + "callingCodes": [ + "672" + ], + "capital": "Kingston", + "altSpellings": [ + "NF", + "Territory of Norfolk Island", + "Teratri of Norf'k Ailen" + ], + "subregion": "Australia and New Zealand", + "region": "Oceania", + "population": 2302, + "latlng": [ + -29.03333333, + 167.95 + ], + "demonym": "Norfolk Islander", + "area": 36.0, + "timezones": [ + "UTC+11:30" + ], + "nativeName": "Norfolk Island", + "numericCode": "574", + "flags": { + "svg": "https://flagcdn.com/nf.svg", + "png": "https://flagcdn.com/w320/nf.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Enez Norfolk", + "pt": "Ilha Norfolk", + "nl": "Norfolkeiland", + "hr": "Otok Norfolk", + "fa": "جزیره نورفک", + "de": "Norfolkinsel", + "es": "Isla de Norfolk", + "fr": "Île de Norfolk", + "ja": "ノーフォーク島", + "it": "Isola Norfolk", + "hu": "Norfolk-sziget" + }, + "flag": "https://flagcdn.com/nf.svg", + "independent": false + }, + { + "name": "Korea (Democratic People's Republic of)", + "topLevelDomain": [ + ".kp" + ], + "alpha2Code": "KP", + "alpha3Code": "PRK", + "callingCodes": [ + "850" + ], + "capital": "Pyongyang", + "altSpellings": [ + "KP", + "Democratic People's Republic of Korea", + "조선민주주의인민공화국", + "Chosŏn Minjujuŭi Inmin Konghwaguk" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 25778815, + "latlng": [ + 40.0, + 127.0 + ], + "demonym": "North Korean", + "area": 120538.0, + "timezones": [ + "UTC+09:00" + ], + "borders": [ + "CHN", + "KOR", + "RUS" + ], + "nativeName": "북한", + "numericCode": "408", + "flags": { + "svg": "https://flagcdn.com/kp.svg", + "png": "https://flagcdn.com/w320/kp.png" + }, + "currencies": [ + { + "code": "KPW", + "name": "North Korean won", + "symbol": "₩" + } + ], + "languages": [ + { + "iso639_1": "ko", + "iso639_2": "kor", + "name": "Korean", + "nativeName": "한국어" + } + ], + "translations": { + "br": "Korea an Norzh", + "pt": "Coreia do Norte", + "nl": "Noord-Korea", + "hr": "Sjeverna Koreja", + "fa": "کره جنوبی", + "de": "Nordkorea", + "es": "Corea del Norte", + "fr": "Corée du Nord", + "ja": "朝鮮民主主義人民共和国", + "it": "Corea del Nord", + "hu": "Észak-Korea" + }, + "flag": "https://flagcdn.com/kp.svg", + "cioc": "PRK", + "independent": true + }, + { + "name": "Northern Mariana Islands", + "topLevelDomain": [ + ".mp" + ], + "alpha2Code": "MP", + "alpha3Code": "MNP", + "callingCodes": [ + "1" + ], + "capital": "Saipan", + "altSpellings": [ + "MP", + "Commonwealth of the Northern Mariana Islands", + "Sankattan Siha Na Islas Mariånas" + ], + "subregion": "Micronesia", + "region": "Oceania", + "population": 57557, + "latlng": [ + 15.2, + 145.75 + ], + "demonym": "American", + "area": 464.0, + "timezones": [ + "UTC+10:00" + ], + "nativeName": "Northern Mariana Islands", + "numericCode": "580", + "flags": { + "svg": "https://flagcdn.com/mp.svg", + "png": "https://flagcdn.com/w320/mp.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "ch", + "iso639_2": "cha", + "name": "Chamorro", + "nativeName": "Chamoru" + } + ], + "translations": { + "br": "Inizi Mariana an Norzh", + "pt": "Ilhas Marianas", + "nl": "Noordelijke Marianeneilanden", + "hr": "Sjevernomarijanski otoci", + "fa": "جزایر ماریانای شمالی", + "de": "Nördliche Marianen", + "es": "Islas Marianas del Norte", + "fr": "Îles Mariannes du Nord", + "ja": "北マリアナ諸島", + "it": "Isole Marianne Settentrionali", + "hu": "Északi-Mariana-szigetek" + }, + "flag": "https://flagcdn.com/mp.svg", + "independent": false + }, + { + "name": "Norway", + "topLevelDomain": [ + ".no" + ], + "alpha2Code": "NO", + "alpha3Code": "NOR", + "callingCodes": [ + "47" + ], + "capital": "Oslo", + "altSpellings": [ + "NO", + "Norge", + "Noreg", + "Kingdom of Norway", + "Kongeriket Norge", + "Kongeriket Noreg" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 5379475, + "latlng": [ + 62.0, + 10.0 + ], + "demonym": "Norwegian", + "area": 323802.0, + "gini": 27.6, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "FIN", + "SWE", + "RUS" + ], + "nativeName": "Norge", + "numericCode": "578", + "flags": { + "svg": "https://flagcdn.com/no.svg", + "png": "https://flagcdn.com/w320/no.png" + }, + "currencies": [ + { + "code": "NOK", + "name": "Norwegian krone", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "no", + "iso639_2": "nor", + "name": "Norwegian", + "nativeName": "Norsk" + }, + { + "iso639_1": "nb", + "iso639_2": "nob", + "name": "Norwegian Bokmål", + "nativeName": "Norsk bokmål" + }, + { + "iso639_1": "nn", + "iso639_2": "nno", + "name": "Norwegian Nynorsk", + "nativeName": "Norsk nynorsk" + } + ], + "translations": { + "br": "Norvegia", + "pt": "Noruega", + "nl": "Noorwegen", + "hr": "Norveška", + "fa": "نروژ", + "de": "Norwegen", + "es": "Noruega", + "fr": "Norvège", + "ja": "ノルウェー", + "it": "Norvegia", + "hu": "Norvégia" + }, + "flag": "https://flagcdn.com/no.svg", + "regionalBlocs": [ + { + "acronym": "EFTA", + "name": "European Free Trade Association" + } + ], + "cioc": "NOR", + "independent": true + }, + { + "name": "Oman", + "topLevelDomain": [ + ".om" + ], + "alpha2Code": "OM", + "alpha3Code": "OMN", + "callingCodes": [ + "968" + ], + "capital": "Muscat", + "altSpellings": [ + "OM", + "Sultanate of Oman", + "Salṭanat ʻUmān" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 5106622, + "latlng": [ + 21.0, + 57.0 + ], + "demonym": "Omani", + "area": 309500.0, + "timezones": [ + "UTC+04:00" + ], + "borders": [ + "SAU", + "ARE", + "YEM" + ], + "nativeName": "عمان", + "numericCode": "512", + "flags": { + "svg": "https://flagcdn.com/om.svg", + "png": "https://flagcdn.com/w320/om.png" + }, + "currencies": [ + { + "code": "OMR", + "name": "Omani rial", + "symbol": "ر.ع." + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Oman", + "pt": "Omã", + "nl": "Oman", + "hr": "Oman", + "fa": "عمان", + "de": "Oman", + "es": "Omán", + "fr": "Oman", + "ja": "オマーン", + "it": "oman", + "hu": "Omán" + }, + "flag": "https://flagcdn.com/om.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "OMA", + "independent": true + }, + { + "name": "Pakistan", + "topLevelDomain": [ + ".pk" + ], + "alpha2Code": "PK", + "alpha3Code": "PAK", + "callingCodes": [ + "92" + ], + "capital": "Islamabad", + "altSpellings": [ + "PK", + "Pākistān", + "Islamic Republic of Pakistan", + "Islāmī Jumhūriya'eh Pākistān" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 220892331, + "latlng": [ + 30.0, + 70.0 + ], + "demonym": "Pakistani", + "area": 881912.0, + "gini": 31.6, + "timezones": [ + "UTC+05:00" + ], + "borders": [ + "AFG", + "CHN", + "IND", + "IRN" + ], + "nativeName": "Pakistan", + "numericCode": "586", + "flags": { + "svg": "https://flagcdn.com/pk.svg", + "png": "https://flagcdn.com/w320/pk.png" + }, + "currencies": [ + { + "code": "PKR", + "name": "Pakistani rupee", + "symbol": "₨" + } + ], + "languages": [ + { + "iso639_1": "ur", + "iso639_2": "urd", + "name": "Urdu", + "nativeName": "اردو" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Pakistan", + "pt": "Paquistão", + "nl": "Pakistan", + "hr": "Pakistan", + "fa": "پاکستان", + "de": "Pakistan", + "es": "Pakistán", + "fr": "Pakistan", + "ja": "パキスタン", + "it": "Pakistan", + "hu": "Pakisztán" + }, + "flag": "https://flagcdn.com/pk.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "PAK", + "independent": true + }, + { + "name": "Palau", + "topLevelDomain": [ + ".pw" + ], + "alpha2Code": "PW", + "alpha3Code": "PLW", + "callingCodes": [ + "680" + ], + "capital": "Ngerulmud", + "altSpellings": [ + "PW", + "Republic of Palau", + "Beluu er a Belau" + ], + "subregion": "Micronesia", + "region": "Oceania", + "population": 18092, + "latlng": [ + 7.5, + 134.5 + ], + "demonym": "Palauan", + "area": 459.0, + "timezones": [ + "UTC+09:00" + ], + "nativeName": "Palau", + "numericCode": "585", + "flags": { + "svg": "https://flagcdn.com/pw.svg", + "png": "https://flagcdn.com/w320/pw.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Palau", + "pt": "Palau", + "nl": "Palau", + "hr": "Palau", + "fa": "پالائو", + "de": "Palau", + "es": "Palau", + "fr": "Palaos", + "ja": "パラオ", + "it": "Palau", + "hu": "Palau" + }, + "flag": "https://flagcdn.com/pw.svg", + "cioc": "PLW", + "independent": true + }, + { + "name": "Palestine, State of", + "topLevelDomain": [ + ".ps" + ], + "alpha2Code": "PS", + "alpha3Code": "PSE", + "callingCodes": [ + "970" + ], + "capital": "Ramallah", + "altSpellings": [ + "PS", + "State of Palestine", + "Dawlat Filasṭin" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 4803269, + "latlng": [ + 31.9, + 35.2 + ], + "demonym": "Palestinian", + "gini": 33.7, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "ISR", + "EGY", + "JOR" + ], + "nativeName": "فلسطين", + "numericCode": "275", + "flags": { + "svg": "https://flagcdn.com/ps.svg", + "png": "https://flagcdn.com/w320/ps.png" + }, + "currencies": [ + { + "code": "EGP", + "name": "Egyptian pound", + "symbol": "E£" + }, + { + "code": "ILS", + "name": "Israeli new shekel", + "symbol": "₪" + }, + { + "code": "JOD", + "name": "Jordanian dinar", + "symbol": "د.أ" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Palestina", + "pt": "Palestina", + "nl": "Palestijnse gebieden", + "hr": "Palestina", + "fa": "فلسطین", + "de": "Palästina", + "es": "Palestina", + "fr": "Palestine", + "ja": "パレスチナ", + "it": "Palestina", + "hu": "Palesztina" + }, + "flag": "https://flagcdn.com/ps.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "PLE", + "independent": true + }, + { + "name": "Panama", + "topLevelDomain": [ + ".pa" + ], + "alpha2Code": "PA", + "alpha3Code": "PAN", + "callingCodes": [ + "507" + ], + "capital": "Panama City", + "altSpellings": [ + "PA", + "Republic of Panama", + "República de Panamá" + ], + "subregion": "Central America", + "region": "Americas", + "population": 4314768, + "latlng": [ + 9.0, + -80.0 + ], + "demonym": "Panamanian", + "area": 75417.0, + "gini": 49.8, + "timezones": [ + "UTC-05:00" + ], + "borders": [ + "COL", + "CRI" + ], + "nativeName": "Panamá", + "numericCode": "591", + "flags": { + "svg": "https://flagcdn.com/pa.svg", + "png": "https://flagcdn.com/w320/pa.png" + }, + "currencies": [ + { + "code": "PAB", + "name": "Panamanian balboa", + "symbol": "B/." + }, + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Panama", + "pt": "Panamá", + "nl": "Panama", + "hr": "Panama", + "fa": "پاناما", + "de": "Panama", + "es": "Panamá", + "fr": "Panama", + "ja": "パナマ", + "it": "Panama", + "hu": "Panama" + }, + "flag": "https://flagcdn.com/pa.svg", + "regionalBlocs": [ + { + "acronym": "CAIS", + "name": "Central American Integration System", + "otherAcronyms": [ + "SICA" + ], + "otherNames": [ + "Sistema de la Integración Centroamericana," + ] + } + ], + "cioc": "PAN", + "independent": true + }, + { + "name": "Papua New Guinea", + "topLevelDomain": [ + ".pg" + ], + "alpha2Code": "PG", + "alpha3Code": "PNG", + "callingCodes": [ + "675" + ], + "capital": "Port Moresby", + "altSpellings": [ + "PG", + "Independent State of Papua New Guinea", + "Independen Stet bilong Papua Niugini" + ], + "subregion": "Melanesia", + "region": "Oceania", + "population": 8947027, + "latlng": [ + -6.0, + 147.0 + ], + "demonym": "Papua New Guinean", + "area": 462840.0, + "gini": 41.9, + "timezones": [ + "UTC+10:00" + ], + "borders": [ + "IDN" + ], + "nativeName": "Papua Niugini", + "numericCode": "598", + "flags": { + "svg": "https://flagcdn.com/pg.svg", + "png": "https://flagcdn.com/w320/pg.png" + }, + "currencies": [ + { + "code": "PGK", + "name": "Papua New Guinean kina", + "symbol": "K" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Papoua-Ginea Nevez", + "pt": "Papua Nova Guiné", + "nl": "Papoea-Nieuw-Guinea", + "hr": "Papua Nova Gvineja", + "fa": "پاپوآ گینه نو", + "de": "Papua-Neuguinea", + "es": "Papúa Nueva Guinea", + "fr": "Papouasie-Nouvelle-Guinée", + "ja": "パプアニューギニア", + "it": "Papua Nuova Guinea", + "hu": "Pápua Új-Guinea" + }, + "flag": "https://flagcdn.com/pg.svg", + "cioc": "PNG", + "independent": true + }, + { + "name": "Paraguay", + "topLevelDomain": [ + ".py" + ], + "alpha2Code": "PY", + "alpha3Code": "PRY", + "callingCodes": [ + "595" + ], + "capital": "Asunción", + "altSpellings": [ + "PY", + "Republic of Paraguay", + "República del Paraguay", + "Tetã Paraguái" + ], + "subregion": "South America", + "region": "Americas", + "population": 7132530, + "latlng": [ + -23.0, + -58.0 + ], + "demonym": "Paraguayan", + "area": 406752.0, + "gini": 45.7, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "ARG", + "BOL", + "BRA" + ], + "nativeName": "Paraguay", + "numericCode": "600", + "flags": { + "svg": "https://flagcdn.com/py.svg", + "png": "https://flagcdn.com/w320/py.png" + }, + "currencies": [ + { + "code": "PYG", + "name": "Paraguayan guaraní", + "symbol": "₲" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + }, + { + "iso639_1": "gn", + "iso639_2": "grn", + "name": "Guaraní", + "nativeName": "Avañe'ẽ" + } + ], + "translations": { + "br": "Paraguay", + "pt": "Paraguai", + "nl": "Paraguay", + "hr": "Paragvaj", + "fa": "پاراگوئه", + "de": "Paraguay", + "es": "Paraguay", + "fr": "Paraguay", + "ja": "パラグアイ", + "it": "Paraguay", + "hu": "Paraguay" + }, + "flag": "https://flagcdn.com/py.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "PAR", + "independent": true + }, + { + "name": "Peru", + "topLevelDomain": [ + ".pe" + ], + "alpha2Code": "PE", + "alpha3Code": "PER", + "callingCodes": [ + "51" + ], + "capital": "Lima", + "altSpellings": [ + "PE", + "Republic of Peru", + " República del Perú" + ], + "subregion": "South America", + "region": "Americas", + "population": 32971846, + "latlng": [ + -10.0, + -76.0 + ], + "demonym": "Peruvian", + "area": 1285216.0, + "gini": 41.5, + "timezones": [ + "UTC-05:00" + ], + "borders": [ + "BOL", + "BRA", + "CHL", + "COL", + "ECU" + ], + "nativeName": "Perú", + "numericCode": "604", + "flags": { + "svg": "https://flagcdn.com/pe.svg", + "png": "https://flagcdn.com/w320/pe.png" + }, + "currencies": [ + { + "code": "PEN", + "name": "Peruvian sol", + "symbol": "S/." + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Perou", + "pt": "Peru", + "nl": "Peru", + "hr": "Peru", + "fa": "پرو", + "de": "Peru", + "es": "Perú", + "fr": "Pérou", + "ja": "ペルー", + "it": "Perù", + "hu": "Peru" + }, + "flag": "https://flagcdn.com/pe.svg", + "regionalBlocs": [ + { + "acronym": "PA", + "name": "Pacific Alliance", + "otherNames": [ + "Alianza del Pacífico" + ] + }, + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "PER", + "independent": true + }, + { + "name": "Philippines", + "topLevelDomain": [ + ".ph" + ], + "alpha2Code": "PH", + "alpha3Code": "PHL", + "callingCodes": [ + "63" + ], + "capital": "Manila", + "altSpellings": [ + "PH", + "Republic of the Philippines", + "Repúblika ng Pilipinas" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 109581085, + "latlng": [ + 13.0, + 122.0 + ], + "demonym": "Filipino", + "area": 342353.0, + "gini": 42.3, + "timezones": [ + "UTC+08:00" + ], + "nativeName": "Pilipinas", + "numericCode": "608", + "flags": { + "svg": "https://flagcdn.com/ph.svg", + "png": "https://flagcdn.com/w320/ph.png" + }, + "currencies": [ + { + "code": "PHP", + "name": "Philippine peso", + "symbol": "₱" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Filipinez", + "pt": "Filipinas", + "nl": "Filipijnen", + "hr": "Filipini", + "fa": "جزایر الندفیلیپین", + "de": "Philippinen", + "es": "Filipinas", + "fr": "Philippines", + "ja": "フィリピン", + "it": "Filippine", + "hu": "Fülöp-szigetek" + }, + "flag": "https://flagcdn.com/ph.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "PHI", + "independent": true + }, + { + "name": "Pitcairn", + "topLevelDomain": [ + ".pn" + ], + "alpha2Code": "PN", + "alpha3Code": "PCN", + "callingCodes": [ + "64" + ], + "capital": "Adamstown", + "altSpellings": [ + "PN", + "Pitcairn Henderson Ducie and Oeno Islands" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 56, + "latlng": [ + -25.06666666, + -130.1 + ], + "demonym": "Pitcairn Islander", + "area": 47.0, + "timezones": [ + "UTC-08:00" + ], + "nativeName": "Pitcairn Islands", + "numericCode": "612", + "flags": { + "svg": "https://flagcdn.com/pn.svg", + "png": "https://flagcdn.com/w320/pn.png" + }, + "currencies": [ + { + "code": "NZD", + "name": "New Zealand dollar", + "symbol": "$" + }, + { + "code": "PND", + "name": "Pitcairn Islands dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Pitcairn", + "pt": "Ilhas Picárnia", + "nl": "Pitcairneilanden", + "hr": "Pitcairnovo otočje", + "fa": "پیتکرن", + "de": "Pitcairn", + "es": "Islas Pitcairn", + "fr": "Îles Pitcairn", + "ja": "ピトケアン", + "it": "Isole Pitcairn", + "hu": "Pitcairn-szigetek" + }, + "flag": "https://flagcdn.com/pn.svg", + "independent": true + }, + { + "name": "Poland", + "topLevelDomain": [ + ".pl" + ], + "alpha2Code": "PL", + "alpha3Code": "POL", + "callingCodes": [ + "48" + ], + "capital": "Warsaw", + "altSpellings": [ + "PL", + "Republic of Poland", + "Rzeczpospolita Polska" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 37950802, + "latlng": [ + 52.0, + 20.0 + ], + "demonym": "Polish", + "area": 312679.0, + "gini": 30.2, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "BLR", + "CZE", + "DEU", + "LTU", + "RUS", + "SVK", + "UKR" + ], + "nativeName": "Polska", + "numericCode": "616", + "flags": { + "svg": "https://flagcdn.com/pl.svg", + "png": "https://flagcdn.com/w320/pl.png" + }, + "currencies": [ + { + "code": "PLN", + "name": "Polish złoty", + "symbol": "zł" + } + ], + "languages": [ + { + "iso639_1": "pl", + "iso639_2": "pol", + "name": "Polish", + "nativeName": "język polski" + } + ], + "translations": { + "br": "Polonia", + "pt": "Polónia", + "nl": "Polen", + "hr": "Poljska", + "fa": "لهستان", + "de": "Polen", + "es": "Polonia", + "fr": "Pologne", + "ja": "ポーランド", + "it": "Polonia", + "hu": "Lengyelország" + }, + "flag": "https://flagcdn.com/pl.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "POL", + "independent": true + }, + { + "name": "Portugal", + "topLevelDomain": [ + ".pt" + ], + "alpha2Code": "PT", + "alpha3Code": "PRT", + "callingCodes": [ + "351" + ], + "capital": "Lisbon", + "altSpellings": [ + "PT", + "Portuguesa", + "Portuguese Republic", + "República Portuguesa" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 10305564, + "latlng": [ + 39.5, + -8.0 + ], + "demonym": "Portuguese", + "area": 92090.0, + "gini": 33.5, + "timezones": [ + "UTC-01:00", + "UTC" + ], + "borders": [ + "ESP" + ], + "nativeName": "Portugal", + "numericCode": "620", + "flags": { + "svg": "https://flagcdn.com/pt.svg", + "png": "https://flagcdn.com/w320/pt.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Portugal", + "pt": "Portugal", + "nl": "Portugal", + "hr": "Portugal", + "fa": "پرتغال", + "de": "Portugal", + "es": "Portugal", + "fr": "Portugal", + "ja": "ポルトガル", + "it": "Portogallo", + "hu": "Portugália" + }, + "flag": "https://flagcdn.com/pt.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "POR", + "independent": true + }, + { + "name": "Puerto Rico", + "topLevelDomain": [ + ".pr" + ], + "alpha2Code": "PR", + "alpha3Code": "PRI", + "callingCodes": [ + "1" + ], + "capital": "San Juan", + "altSpellings": [ + "PR", + "Commonwealth of Puerto Rico", + "Estado Libre Asociado de Puerto Rico" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 3194034, + "latlng": [ + 18.25, + -66.5 + ], + "demonym": "Puerto Rican", + "area": 8870.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Puerto Rico", + "numericCode": "630", + "flags": { + "svg": "https://flagcdn.com/pr.svg", + "png": "https://flagcdn.com/w320/pr.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Puerto Rico", + "pt": "Porto Rico", + "nl": "Puerto Rico", + "hr": "Portoriko", + "fa": "پورتو ریکو", + "de": "Puerto Rico", + "es": "Puerto Rico", + "fr": "Porto Rico", + "ja": "プエルトリコ", + "it": "Porto Rico", + "hu": "Puerto Rico" + }, + "flag": "https://flagcdn.com/pr.svg", + "cioc": "PUR", + "independent": false + }, + { + "name": "Qatar", + "topLevelDomain": [ + ".qa" + ], + "alpha2Code": "QA", + "alpha3Code": "QAT", + "callingCodes": [ + "974" + ], + "capital": "Doha", + "altSpellings": [ + "QA", + "State of Qatar", + "Dawlat Qaṭar" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 2881060, + "latlng": [ + 25.5, + 51.25 + ], + "demonym": "Qatari", + "area": 11586.0, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "SAU" + ], + "nativeName": "قطر", + "numericCode": "634", + "flags": { + "svg": "https://flagcdn.com/qa.svg", + "png": "https://flagcdn.com/w320/qa.png" + }, + "currencies": [ + { + "code": "QAR", + "name": "Qatari riyal", + "symbol": "ر.ق" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Katar", + "pt": "Catar", + "nl": "Qatar", + "hr": "Katar", + "fa": "قطر", + "de": "Katar", + "es": "Catar", + "fr": "Qatar", + "ja": "カタール", + "it": "Qatar", + "hu": "Katar" + }, + "flag": "https://flagcdn.com/qa.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "QAT", + "independent": true + }, + { + "name": "Republic of Kosovo", + "topLevelDomain": [ + "" + ], + "alpha2Code": "XK", + "alpha3Code": "UNK", + "callingCodes": [ + "383" + ], + "capital": "Pristina", + "altSpellings": [ + "XK", + "Република Косово" + ], + "subregion": "Eastern Europe", + "region": "Europe", + "population": 1775378, + "latlng": [ + 42.666667, + 21.166667 + ], + "demonym": "Kosovar", + "area": 10908.0, + "gini": 29.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "ALB", + "MKD", + "MNE", + "SRB" + ], + "nativeName": "Republika e Kosovës", + "numericCode": "926", + "flags": { + "svg": "https://flagcdn.com/xk.svg", + "png": "https://flagcdn.com/w320/xk.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "sq", + "iso639_2": "sqi", + "name": "Albanian", + "nativeName": "Shqip" + }, + { + "iso639_1": "sr", + "iso639_2": "srp", + "name": "Serbian", + "nativeName": "српски језик" + } + ], + "translations": { + "br": "Kosovo", + "pt": "Kosovo", + "nl": "Republiek van Kosovo", + "hr": "Kosovo", + "fa": "کوزوو", + "de": "Republic of Kosovo", + "es": "Kosovo", + "fr": "Kosovo", + "ja": "Republic of Kosovo", + "it": "Republic of Kosovo", + "hu": "Koszovó" + }, + "flag": "https://flagcdn.com/xk.svg", + "regionalBlocs": [ + { + "acronym": "CEFTA", + "name": "Central European Free Trade Agreement" + } + ], + "independent": true + }, + { + "name": "Réunion", + "topLevelDomain": [ + ".re" + ], + "alpha2Code": "RE", + "alpha3Code": "REU", + "callingCodes": [ + "262" + ], + "capital": "Saint-Denis", + "altSpellings": [ + "RE", + "Reunion" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 840974, + "latlng": [ + -21.15, + 55.5 + ], + "demonym": "French", + "timezones": [ + "UTC+04:00" + ], + "nativeName": "La Réunion", + "numericCode": "638", + "flags": { + "svg": "https://flagcdn.com/re.svg", + "png": "https://flagcdn.com/w320/re.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Reünion", + "pt": "Reunião", + "nl": "Réunion", + "hr": "Réunion", + "fa": "رئونیون", + "de": "Réunion", + "es": "Reunión", + "fr": "Réunion", + "ja": "レユニオン", + "it": "Riunione", + "hu": "Réunion" + }, + "flag": "https://flagcdn.com/re.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "independent": false + }, + { + "name": "Romania", + "topLevelDomain": [ + ".ro" + ], + "alpha2Code": "RO", + "alpha3Code": "ROU", + "callingCodes": [ + "40" + ], + "capital": "Bucharest", + "altSpellings": [ + "RO", + "Rumania", + "Roumania", + "România" + ], + "subregion": "Eastern Europe", + "region": "Europe", + "population": 19286123, + "latlng": [ + 46.0, + 25.0 + ], + "demonym": "Romanian", + "area": 238391.0, + "gini": 35.8, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "BGR", + "HUN", + "MDA", + "SRB", + "UKR" + ], + "nativeName": "România", + "numericCode": "642", + "flags": { + "svg": "https://flagcdn.com/ro.svg", + "png": "https://flagcdn.com/w320/ro.png" + }, + "currencies": [ + { + "code": "RON", + "name": "Romanian leu", + "symbol": "lei" + } + ], + "languages": [ + { + "iso639_1": "ro", + "iso639_2": "ron", + "name": "Romanian", + "nativeName": "Română" + } + ], + "translations": { + "br": "Roumania", + "pt": "Roménia", + "nl": "Roemenië", + "hr": "Rumunjska", + "fa": "رومانی", + "de": "Rumänien", + "es": "Rumania", + "fr": "Roumanie", + "ja": "ルーマニア", + "it": "Romania", + "hu": "Románia" + }, + "flag": "https://flagcdn.com/ro.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "ROU", + "independent": true + }, + { + "name": "Russian Federation", + "topLevelDomain": [ + ".ru" + ], + "alpha2Code": "RU", + "alpha3Code": "RUS", + "callingCodes": [ + "7" + ], + "capital": "Moscow", + "altSpellings": [ + "RU", + "Rossiya", + "Russian Federation", + "Российская Федерация", + "Rossiyskaya Federatsiya" + ], + "subregion": "Eastern Europe", + "region": "Europe", + "population": 144104080, + "latlng": [ + 60.0, + 100.0 + ], + "demonym": "Russian", + "area": 17124442.0, + "gini": 37.5, + "timezones": [ + "UTC+03:00", + "UTC+04:00", + "UTC+06:00", + "UTC+07:00", + "UTC+08:00", + "UTC+09:00", + "UTC+10:00", + "UTC+11:00", + "UTC+12:00" + ], + "borders": [ + "AZE", + "BLR", + "CHN", + "EST", + "FIN", + "GEO", + "KAZ", + "PRK", + "LVA", + "LTU", + "MNG", + "NOR", + "POL", + "UKR" + ], + "nativeName": "Россия", + "numericCode": "643", + "flags": { + "svg": "https://flagcdn.com/ru.svg", + "png": "https://flagcdn.com/w320/ru.png" + }, + "currencies": [ + { + "code": "RUB", + "name": "Russian ruble", + "symbol": "₽" + } + ], + "languages": [ + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Rusia", + "pt": "Rússia", + "nl": "Rusland", + "hr": "Rusija", + "fa": "روسیه", + "de": "Russland", + "es": "Rusia", + "fr": "Russie", + "ja": "ロシア連邦", + "it": "Russia", + "hu": "Oroszország" + }, + "flag": "https://flagcdn.com/ru.svg", + "regionalBlocs": [ + { + "acronym": "EEU", + "name": "Eurasian Economic Union", + "otherAcronyms": [ + "EAEU" + ] + } + ], + "cioc": "RUS", + "independent": true + }, + { + "name": "Rwanda", + "topLevelDomain": [ + ".rw" + ], + "alpha2Code": "RW", + "alpha3Code": "RWA", + "callingCodes": [ + "250" + ], + "capital": "Kigali", + "altSpellings": [ + "RW", + "Republic of Rwanda", + "Repubulika y'u Rwanda", + "République du Rwanda" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 12952209, + "latlng": [ + -2.0, + 30.0 + ], + "demonym": "Rwandan", + "area": 26338.0, + "gini": 43.7, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "BDI", + "COD", + "TZA", + "UGA" + ], + "nativeName": "Rwanda", + "numericCode": "646", + "flags": { + "svg": "https://flagcdn.com/rw.svg", + "png": "https://flagcdn.com/w320/rw.png" + }, + "currencies": [ + { + "code": "RWF", + "name": "Rwandan franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "rw", + "iso639_2": "kin", + "name": "Kinyarwanda", + "nativeName": "Ikinyarwanda" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Rwanda", + "pt": "Ruanda", + "nl": "Rwanda", + "hr": "Ruanda", + "fa": "رواندا", + "de": "Ruanda", + "es": "Ruanda", + "fr": "Rwanda", + "ja": "ルワンダ", + "it": "Ruanda", + "hu": "Ruanda" + }, + "flag": "https://flagcdn.com/rw.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "RWA", + "independent": true + }, + { + "name": "Saint Barthélemy", + "topLevelDomain": [ + ".bl" + ], + "alpha2Code": "BL", + "alpha3Code": "BLM", + "callingCodes": [ + "590" + ], + "capital": "Gustavia", + "altSpellings": [ + "BL", + "St. Barthelemy", + "Collectivity of Saint Barthélemy", + "Collectivité de Saint-Barthélemy" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 9417, + "latlng": [ + 18.5, + -63.41666666 + ], + "demonym": "Saint Barthélemy Islander", + "area": 21.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Saint-Barthélemy", + "numericCode": "652", + "flags": { + "svg": "https://flagcdn.com/bl.svg", + "png": "https://flagcdn.com/w320/bl.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Saint-Barthélemy", + "pt": "São Bartolomeu", + "nl": "Saint Barthélemy", + "hr": "Saint Barthélemy", + "fa": "سن-بارتلمی", + "de": "Saint-Barthélemy", + "es": "San Bartolomé", + "fr": "Saint-Barthélemy", + "ja": "サン・バルテルミー", + "it": "Antille Francesi", + "hu": "Saint-Barthélemy" + }, + "flag": "https://flagcdn.com/bl.svg", + "independent": false + }, + { + "name": "Saint Helena, Ascension and Tristan da Cunha", + "topLevelDomain": [ + ".sh" + ], + "alpha2Code": "SH", + "alpha3Code": "SHN", + "callingCodes": [ + "290" + ], + "capital": "Jamestown", + "altSpellings": [ + "SH" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 4255, + "latlng": [ + -15.95, + -5.7 + ], + "demonym": "Saint Helenian", + "timezones": [ + "UTC+00:00" + ], + "nativeName": "Saint Helena", + "numericCode": "654", + "flags": { + "svg": "https://flagcdn.com/sh.svg", + "png": "https://flagcdn.com/w320/sh.png" + }, + "currencies": [ + { + "code": "SHP", + "name": "Saint Helena pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Saint Helena, Ascension ha Tristan da Cunha", + "pt": "Santa Helena", + "nl": "Sint-Helena", + "hr": "Sveta Helena", + "fa": "سنت هلنا، اسنشن و تریستان دا کونا", + "de": "Sankt Helena", + "es": "Santa Helena", + "fr": "Sainte-Hélène", + "ja": "セントヘレナ・アセンションおよびトリスタンダクーニャ", + "it": "Sant'Elena", + "hu": "Szent Ilona" + }, + "flag": "https://flagcdn.com/sh.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "independent": false + }, + { + "name": "Saint Kitts and Nevis", + "topLevelDomain": [ + ".kn" + ], + "alpha2Code": "KN", + "alpha3Code": "KNA", + "callingCodes": [ + "1" + ], + "capital": "Basseterre", + "altSpellings": [ + "KN", + "Federation of Saint Christopher and Nevis" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 53192, + "latlng": [ + 17.33333333, + -62.75 + ], + "demonym": "Kittian and Nevisian", + "area": 261.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Saint Kitts and Nevis", + "numericCode": "659", + "flags": { + "svg": "https://flagcdn.com/kn.svg", + "png": "https://flagcdn.com/w320/kn.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Saint Kitts ha Nevis", + "pt": "São Cristóvão e Neves", + "nl": "Saint Kitts en Nevis", + "hr": "Sveti Kristof i Nevis", + "fa": "سنت کیتس و نویس", + "de": "St. Kitts und Nevis", + "es": "San Cristóbal y Nieves", + "fr": "Saint-Christophe-et-Niévès", + "ja": "セントクリストファー・ネイビス", + "it": "Saint Kitts e Nevis", + "hu": "Saint Kitts és Nevis" + }, + "flag": "https://flagcdn.com/kn.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "SKN", + "independent": true + }, + { + "name": "Saint Lucia", + "topLevelDomain": [ + ".lc" + ], + "alpha2Code": "LC", + "alpha3Code": "LCA", + "callingCodes": [ + "1" + ], + "capital": "Castries", + "altSpellings": [ + "LC" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 183629, + "latlng": [ + 13.88333333, + -60.96666666 + ], + "demonym": "Saint Lucian", + "area": 616.0, + "gini": 51.2, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Saint Lucia", + "numericCode": "662", + "flags": { + "svg": "https://flagcdn.com/lc.svg", + "png": "https://flagcdn.com/w320/lc.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Santez-Lusia", + "pt": "Santa Lúcia", + "nl": "Saint Lucia", + "hr": "Sveta Lucija", + "fa": "سنت لوسیا", + "de": "Saint Lucia", + "es": "Santa Lucía", + "fr": "Saint-Lucie", + "ja": "セントルシア", + "it": "Santa Lucia", + "hu": "Saint Lucia" + }, + "flag": "https://flagcdn.com/lc.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "LCA", + "independent": true + }, + { + "name": "Saint Martin (French part)", + "topLevelDomain": [ + ".mf", + ".fr", + ".gp" + ], + "alpha2Code": "MF", + "alpha3Code": "MAF", + "callingCodes": [ + "590" + ], + "capital": "Marigot", + "altSpellings": [ + "MF", + "Collectivity of Saint Martin", + "Collectivité de Saint-Martin" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 38659, + "latlng": [ + 18.08333333, + -63.95 + ], + "demonym": "Saint Martin Islander", + "area": 53.0, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "SXM", + "NLD" + ], + "nativeName": "Saint-Martin", + "numericCode": "663", + "flags": { + "svg": "https://flagcdn.com/mf.svg", + "png": "https://flagcdn.com/w320/mf.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + } + ], + "translations": { + "br": "Saint-Martin", + "pt": "Ilha São Martinho", + "nl": "Saint-Martin", + "hr": "Sveti Martin", + "fa": "سینت مارتن", + "de": "Saint Martin", + "es": "Saint Martin", + "fr": "Saint-Martin", + "ja": "サン・マルタン(フランス領)", + "it": "Saint Martin", + "hu": "Saint-Martin" + }, + "flag": "https://flagcdn.com/mf.svg", + "independent": false + }, + { + "name": "Saint Pierre and Miquelon", + "topLevelDomain": [ + ".pm" + ], + "alpha2Code": "PM", + "alpha3Code": "SPM", + "callingCodes": [ + "508" + ], + "capital": "Saint-Pierre", + "altSpellings": [ + "PM", + "Collectivité territoriale de Saint-Pierre-et-Miquelon" + ], + "subregion": "Northern America", + "region": "Americas", + "population": 6069, + "latlng": [ + 46.83333333, + -56.33333333 + ], + "demonym": "French", + "area": 242.0, + "timezones": [ + "UTC-03:00" + ], + "nativeName": "Saint-Pierre-et-Miquelon", + "numericCode": "666", + "flags": { + "svg": "https://flagcdn.com/pm.svg", + "png": "https://flagcdn.com/w320/pm.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Sant-Pêr-ha-Mikelon", + "pt": "São Pedro e Miquelon", + "nl": "Saint Pierre en Miquelon", + "hr": "Sveti Petar i Mikelon", + "fa": "سن پیر و میکلن", + "de": "Saint-Pierre und Miquelon", + "es": "San Pedro y Miquelón", + "fr": "Saint-Pierre-et-Miquelon", + "ja": "サンピエール島・ミクロン島", + "it": "Saint-Pierre e Miquelon", + "hu": "Saint-Pierre és Miquelon" + }, + "flag": "https://flagcdn.com/pm.svg", + "independent": false + }, + { + "name": "Saint Vincent and the Grenadines", + "topLevelDomain": [ + ".vc" + ], + "alpha2Code": "VC", + "alpha3Code": "VCT", + "callingCodes": [ + "1" + ], + "capital": "Kingstown", + "altSpellings": [ + "VC" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 110947, + "latlng": [ + 13.25, + -61.2 + ], + "demonym": "Saint Vincentian", + "area": 389.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Saint Vincent and the Grenadines", + "numericCode": "670", + "flags": { + "svg": "https://flagcdn.com/vc.svg", + "png": "https://flagcdn.com/w320/vc.png" + }, + "currencies": [ + { + "code": "XCD", + "name": "East Caribbean dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Sant-Visant hag ar Grenadinez", + "pt": "São Vicente e Granadinas", + "nl": "Saint Vincent en de Grenadines", + "hr": "Sveti Vincent i Grenadini", + "fa": "سنت وینسنت و گرنادین‌ها", + "de": "Saint Vincent und die Grenadinen", + "es": "San Vicente y Granadinas", + "fr": "Saint-Vincent-et-les-Grenadines", + "ja": "セントビンセントおよびグレナディーン諸島", + "it": "Saint Vincent e Grenadine", + "hu": "Saint Vincent és a Grenadine-szigetek" + }, + "flag": "https://flagcdn.com/vc.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "VIN", + "independent": true + }, + { + "name": "Samoa", + "topLevelDomain": [ + ".ws" + ], + "alpha2Code": "WS", + "alpha3Code": "WSM", + "callingCodes": [ + "685" + ], + "capital": "Apia", + "altSpellings": [ + "WS", + "Independent State of Samoa", + "Malo Saʻoloto Tutoʻatasi o Sāmoa" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 198410, + "latlng": [ + -13.58333333, + -172.33333333 + ], + "demonym": "Samoan", + "area": 2842.0, + "gini": 38.7, + "timezones": [ + "UTC+13:00" + ], + "nativeName": "Samoa", + "numericCode": "882", + "flags": { + "svg": "https://flagcdn.com/ws.svg", + "png": "https://flagcdn.com/w320/ws.png" + }, + "currencies": [ + { + "code": "WST", + "name": "Samoan tālā", + "symbol": "T" + } + ], + "languages": [ + { + "iso639_1": "sm", + "iso639_2": "smo", + "name": "Samoan", + "nativeName": "gagana fa'a Samoa" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Samoa", + "pt": "Samoa", + "nl": "Samoa", + "hr": "Samoa", + "fa": "ساموآ", + "de": "Samoa", + "es": "Samoa", + "fr": "Samoa", + "ja": "サモア", + "it": "Samoa", + "hu": "Szamoa" + }, + "flag": "https://flagcdn.com/ws.svg", + "cioc": "SAM", + "independent": true + }, + { + "name": "San Marino", + "topLevelDomain": [ + ".sm" + ], + "alpha2Code": "SM", + "alpha3Code": "SMR", + "callingCodes": [ + "378" + ], + "capital": "City of San Marino", + "altSpellings": [ + "SM", + "Republic of San Marino", + "Repubblica di San Marino" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 33938, + "latlng": [ + 43.76666666, + 12.41666666 + ], + "demonym": "Sammarinese", + "area": 61.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "ITA" + ], + "nativeName": "San Marino", + "numericCode": "674", + "flags": { + "svg": "https://flagcdn.com/sm.svg", + "png": "https://flagcdn.com/w320/sm.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "it", + "iso639_2": "ita", + "name": "Italian", + "nativeName": "Italiano" + } + ], + "translations": { + "br": "San Marino", + "pt": "São Marinho", + "nl": "San Marino", + "hr": "San Marino", + "fa": "سان مارینو", + "de": "San Marino", + "es": "San Marino", + "fr": "Saint-Marin", + "ja": "サンマリノ", + "it": "San Marino", + "hu": "San Marino" + }, + "flag": "https://flagcdn.com/sm.svg", + "cioc": "SMR", + "independent": true + }, + { + "name": "Sao Tome and Principe", + "topLevelDomain": [ + ".st" + ], + "alpha2Code": "ST", + "alpha3Code": "STP", + "callingCodes": [ + "239" + ], + "capital": "São Tomé", + "altSpellings": [ + "ST", + "Democratic Republic of São Tomé and Príncipe", + "República Democrática de São Tomé e Príncipe" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 219161, + "latlng": [ + 1.0, + 7.0 + ], + "demonym": "Sao Tomean", + "area": 964.0, + "gini": 56.3, + "timezones": [ + "UTC" + ], + "nativeName": "São Tomé e Príncipe", + "numericCode": "678", + "flags": { + "svg": "https://flagcdn.com/st.svg", + "png": "https://flagcdn.com/w320/st.png" + }, + "currencies": [ + { + "code": "STD", + "name": "São Tomé and Príncipe dobra", + "symbol": "Db" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "São Tomé ha Príncipe", + "pt": "São Tomé e Príncipe", + "nl": "Sao Tomé en Principe", + "hr": "Sveti Toma i Princip", + "fa": "کواترو دو فرویرو", + "de": "São Tomé und Príncipe", + "es": "Santo Tomé y Príncipe", + "fr": "Sao Tomé-et-Principe", + "ja": "サントメ・プリンシペ", + "it": "São Tomé e Príncipe", + "hu": "São Tomé és Príncipe" + }, + "flag": "https://flagcdn.com/st.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "STP", + "independent": true + }, + { + "name": "Saudi Arabia", + "topLevelDomain": [ + ".sa" + ], + "alpha2Code": "SA", + "alpha3Code": "SAU", + "callingCodes": [ + "966" + ], + "capital": "Riyadh", + "altSpellings": [ + "SA", + "Kingdom of Saudi Arabia", + "Al-Mamlakah al-‘Arabiyyah as-Su‘ūdiyyah" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 34813867, + "latlng": [ + 25.0, + 45.0 + ], + "demonym": "Saudi Arabian", + "area": 2149690.0, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "IRQ", + "JOR", + "KWT", + "OMN", + "QAT", + "ARE", + "YEM" + ], + "nativeName": "العربية السعودية", + "numericCode": "682", + "flags": { + "svg": "https://flagcdn.com/sa.svg", + "png": "https://flagcdn.com/w320/sa.png" + }, + "currencies": [ + { + "code": "SAR", + "name": "Saudi riyal", + "symbol": "ر.س" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Arabia Saoudat", + "pt": "Arábia Saudita", + "nl": "Saoedi-Arabië", + "hr": "Saudijska Arabija", + "fa": "عربستان سعودی", + "de": "Saudi-Arabien", + "es": "Arabia Saudí", + "fr": "Arabie Saoudite", + "ja": "サウジアラビア", + "it": "Arabia Saudita", + "hu": "Szaúd-Arábia" + }, + "flag": "https://flagcdn.com/sa.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "KSA", + "independent": true + }, + { + "name": "Senegal", + "topLevelDomain": [ + ".sn" + ], + "alpha2Code": "SN", + "alpha3Code": "SEN", + "callingCodes": [ + "221" + ], + "capital": "Dakar", + "altSpellings": [ + "SN", + "Republic of Senegal", + "République du Sénégal" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 16743930, + "latlng": [ + 14.0, + -14.0 + ], + "demonym": "Senegalese", + "area": 196722.0, + "gini": 40.3, + "timezones": [ + "UTC" + ], + "borders": [ + "GMB", + "GIN", + "GNB", + "MLI", + "MRT" + ], + "nativeName": "Sénégal", + "numericCode": "686", + "flags": { + "svg": "https://flagcdn.com/sn.svg", + "png": "https://flagcdn.com/w320/sn.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Senegal", + "pt": "Senegal", + "nl": "Senegal", + "hr": "Senegal", + "fa": "سنگال", + "de": "Senegal", + "es": "Senegal", + "fr": "Sénégal", + "ja": "セネガル", + "it": "Senegal", + "hu": "Szenegál" + }, + "flag": "https://flagcdn.com/sn.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "SEN", + "independent": true + }, + { + "name": "Serbia", + "topLevelDomain": [ + ".rs" + ], + "alpha2Code": "RS", + "alpha3Code": "SRB", + "callingCodes": [ + "381" + ], + "capital": "Belgrade", + "altSpellings": [ + "RS", + "Srbija", + "Republic of Serbia", + "Република Србија", + "Republika Srbija" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 6908224, + "latlng": [ + 44.0, + 21.0 + ], + "demonym": "Serbian", + "area": 88361.0, + "gini": 36.2, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "BIH", + "BGR", + "HRV", + "HUN", + "UNK", + "MKD", + "MNE", + "ROU" + ], + "nativeName": "Србија", + "numericCode": "688", + "flags": { + "svg": "https://flagcdn.com/rs.svg", + "png": "https://flagcdn.com/w320/rs.png" + }, + "currencies": [ + { + "code": "RSD", + "name": "Serbian dinar", + "symbol": "дин." + } + ], + "languages": [ + { + "iso639_1": "sr", + "iso639_2": "srp", + "name": "Serbian", + "nativeName": "српски језик" + } + ], + "translations": { + "br": "Serbia", + "pt": "Sérvia", + "nl": "Servië", + "hr": "Srbija", + "fa": "صربستان", + "de": "Serbien", + "es": "Serbia", + "fr": "Serbie", + "ja": "セルビア", + "it": "Serbia", + "hu": "Szerbia" + }, + "flag": "https://flagcdn.com/rs.svg", + "regionalBlocs": [ + { + "acronym": "CEFTA", + "name": "Central European Free Trade Agreement" + } + ], + "cioc": "SRB", + "independent": true + }, + { + "name": "Seychelles", + "topLevelDomain": [ + ".sc" + ], + "alpha2Code": "SC", + "alpha3Code": "SYC", + "callingCodes": [ + "248" + ], + "capital": "Victoria", + "altSpellings": [ + "SC", + "Republic of Seychelles", + "Repiblik Sesel", + "République des Seychelles" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 98462, + "latlng": [ + -4.58333333, + 55.66666666 + ], + "demonym": "Seychellois", + "area": 452.0, + "gini": 32.1, + "timezones": [ + "UTC+04:00" + ], + "nativeName": "Seychelles", + "numericCode": "690", + "flags": { + "svg": "https://flagcdn.com/sc.svg", + "png": "https://flagcdn.com/w320/sc.png" + }, + "currencies": [ + { + "code": "SCR", + "name": "Seychellois rupee", + "symbol": "₨" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Sechelez", + "pt": "Seicheles", + "nl": "Seychellen", + "hr": "Sejšeli", + "fa": "سیشل", + "de": "Seychellen", + "es": "Seychelles", + "fr": "Seychelles", + "ja": "セーシェル", + "it": "Seychelles", + "hu": "Seychelle-szigetek" + }, + "flag": "https://flagcdn.com/sc.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "SEY", + "independent": true + }, + { + "name": "Sierra Leone", + "topLevelDomain": [ + ".sl" + ], + "alpha2Code": "SL", + "alpha3Code": "SLE", + "callingCodes": [ + "232" + ], + "capital": "Freetown", + "altSpellings": [ + "SL", + "Republic of Sierra Leone" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 7976985, + "latlng": [ + 8.5, + -11.5 + ], + "demonym": "Sierra Leonean", + "area": 71740.0, + "gini": 35.7, + "timezones": [ + "UTC" + ], + "borders": [ + "GIN", + "LBR" + ], + "nativeName": "Sierra Leone", + "numericCode": "694", + "flags": { + "svg": "https://flagcdn.com/sl.svg", + "png": "https://flagcdn.com/w320/sl.png" + }, + "currencies": [ + { + "code": "SLL", + "name": "Sierra Leonean leone", + "symbol": "Le" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Sierra Leone", + "pt": "Serra Leoa", + "nl": "Sierra Leone", + "hr": "Sijera Leone", + "fa": "سیرالئون", + "de": "Sierra Leone", + "es": "Sierra Leone", + "fr": "Sierra Leone", + "ja": "シエラレオネ", + "it": "Sierra Leone", + "hu": "Sierra Leone" + }, + "flag": "https://flagcdn.com/sl.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "SLE", + "independent": true + }, + { + "name": "Singapore", + "topLevelDomain": [ + ".sg" + ], + "alpha2Code": "SG", + "alpha3Code": "SGP", + "callingCodes": [ + "65" + ], + "capital": "Singapore", + "altSpellings": [ + "SG", + "Singapura", + "Republik Singapura", + "新加坡共和国" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 5685807, + "latlng": [ + 1.36666666, + 103.8 + ], + "demonym": "Singaporean", + "area": 710.0, + "timezones": [ + "UTC+08:00" + ], + "nativeName": "Singapore", + "numericCode": "702", + "flags": { + "svg": "https://flagcdn.com/sg.svg", + "png": "https://flagcdn.com/w320/sg.png" + }, + "currencies": [ + { + "code": "SGD", + "name": "Singapore dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "ms", + "iso639_2": "msa", + "name": "Malay", + "nativeName": "bahasa Melayu" + }, + { + "iso639_1": "ta", + "iso639_2": "tam", + "name": "Tamil", + "nativeName": "தமிழ்" + }, + { + "iso639_1": "zh", + "iso639_2": "zho", + "name": "Chinese", + "nativeName": "中文 (Zhōngwén)" + } + ], + "translations": { + "br": "Singapour", + "pt": "Singapura", + "nl": "Singapore", + "hr": "Singapur", + "fa": "سنگاپور", + "de": "Singapur", + "es": "Singapur", + "fr": "Singapour", + "ja": "シンガポール", + "it": "Singapore", + "hu": "Szingapúr" + }, + "flag": "https://flagcdn.com/sg.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "SIN", + "independent": true + }, + { + "name": "Sint Maarten (Dutch part)", + "topLevelDomain": [ + ".sx" + ], + "alpha2Code": "SX", + "alpha3Code": "SXM", + "callingCodes": [ + "1" + ], + "capital": "Philipsburg", + "altSpellings": [ + "SX" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 40812, + "latlng": [ + 18.033333, + -63.05 + ], + "demonym": "Dutch", + "area": 34.0, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "MAF" + ], + "nativeName": "Sint Maarten", + "numericCode": "534", + "flags": { + "svg": "https://flagcdn.com/sx.svg", + "png": "https://flagcdn.com/w320/sx.png" + }, + "currencies": [ + { + "code": "ANG", + "name": "Netherlands Antillean guilder", + "symbol": "ƒ" + } + ], + "languages": [ + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Sint Maarten", + "pt": "São Martinho", + "nl": "Sint Maarten", + "hr": "Sint Maarten (Dutch part)", + "fa": "سینت مارتن", + "de": "Sint Maarten (niederl. Teil)", + "es": "Sint Maarten (Dutch part)", + "fr": "Saint Martin (partie néerlandaise)", + "ja": "Sint Maarten (Dutch part)", + "it": "Saint Martin (parte olandese)", + "hu": "Sint Maarten" + }, + "flag": "https://flagcdn.com/sx.svg", + "independent": false + }, + { + "name": "Slovakia", + "topLevelDomain": [ + ".sk" + ], + "alpha2Code": "SK", + "alpha3Code": "SVK", + "callingCodes": [ + "421" + ], + "capital": "Bratislava", + "altSpellings": [ + "SK", + "Slovak Republic", + "Slovenská republika" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 5458827, + "latlng": [ + 48.66666666, + 19.5 + ], + "demonym": "Slovak", + "area": 49037.0, + "gini": 25.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AUT", + "CZE", + "HUN", + "POL", + "UKR" + ], + "nativeName": "Slovensko", + "numericCode": "703", + "flags": { + "svg": "https://flagcdn.com/sk.svg", + "png": "https://flagcdn.com/w320/sk.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "sk", + "iso639_2": "slk", + "name": "Slovak", + "nativeName": "slovenčina" + } + ], + "translations": { + "br": "Slovakia", + "pt": "Eslováquia", + "nl": "Slowakije", + "hr": "Slovačka", + "fa": "اسلواکی", + "de": "Slowakei", + "es": "República Eslovaca", + "fr": "Slovaquie", + "ja": "スロバキア", + "it": "Slovacchia", + "hu": "Szlovákia" + }, + "flag": "https://flagcdn.com/sk.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "SVK", + "independent": true + }, + { + "name": "Slovenia", + "topLevelDomain": [ + ".si" + ], + "alpha2Code": "SI", + "alpha3Code": "SVN", + "callingCodes": [ + "386" + ], + "capital": "Ljubljana", + "altSpellings": [ + "SI", + "Republic of Slovenia", + "Republika Slovenija" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 2100126, + "latlng": [ + 46.11666666, + 14.81666666 + ], + "demonym": "Slovene", + "area": 20273.0, + "gini": 24.6, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AUT", + "HRV", + "ITA", + "HUN" + ], + "nativeName": "Slovenija", + "numericCode": "705", + "flags": { + "svg": "https://flagcdn.com/si.svg", + "png": "https://flagcdn.com/w320/si.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "sl", + "iso639_2": "slv", + "name": "Slovene", + "nativeName": "slovenski jezik" + } + ], + "translations": { + "br": "Slovenia", + "pt": "Eslovénia", + "nl": "Slovenië", + "hr": "Slovenija", + "fa": "اسلوونی", + "de": "Slowenien", + "es": "Eslovenia", + "fr": "Slovénie", + "ja": "スロベニア", + "it": "Slovenia", + "hu": "Szlovénia" + }, + "flag": "https://flagcdn.com/si.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "SLO", + "independent": true + }, + { + "name": "Solomon Islands", + "topLevelDomain": [ + ".sb" + ], + "alpha2Code": "SB", + "alpha3Code": "SLB", + "callingCodes": [ + "677" + ], + "capital": "Honiara", + "altSpellings": [ + "SB" + ], + "subregion": "Melanesia", + "region": "Oceania", + "population": 686878, + "latlng": [ + -8.0, + 159.0 + ], + "demonym": "Solomon Islander", + "area": 28896.0, + "gini": 37.1, + "timezones": [ + "UTC+11:00" + ], + "nativeName": "Solomon Islands", + "numericCode": "090", + "flags": { + "svg": "https://flagcdn.com/sb.svg", + "png": "https://flagcdn.com/w320/sb.png" + }, + "currencies": [ + { + "code": "SBD", + "name": "Solomon Islands dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Salomon", + "pt": "Ilhas Salomão", + "nl": "Salomonseilanden", + "hr": "Solomonski Otoci", + "fa": "جزایر سلیمان", + "de": "Salomonen", + "es": "Islas Salomón", + "fr": "Îles Salomon", + "ja": "ソロモン諸島", + "it": "Isole Salomone", + "hu": "Salamon-szigetek" + }, + "flag": "https://flagcdn.com/sb.svg", + "cioc": "SOL", + "independent": true + }, + { + "name": "Somalia", + "topLevelDomain": [ + ".so" + ], + "alpha2Code": "SO", + "alpha3Code": "SOM", + "callingCodes": [ + "252" + ], + "capital": "Mogadishu", + "altSpellings": [ + "SO", + "aṣ-Ṣūmāl", + "Federal Republic of Somalia", + "Jamhuuriyadda Federaalka Soomaaliya", + "Jumhūriyyat aṣ-Ṣūmāl al-Fiderāliyya" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 15893219, + "latlng": [ + 10.0, + 49.0 + ], + "demonym": "Somali", + "area": 637657.0, + "gini": 36.8, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "DJI", + "ETH", + "KEN" + ], + "nativeName": "Soomaaliya", + "numericCode": "706", + "flags": { + "svg": "https://flagcdn.com/so.svg", + "png": "https://flagcdn.com/w320/so.png" + }, + "currencies": [ + { + "code": "SOS", + "name": "Somali shilling", + "symbol": "Sh" + } + ], + "languages": [ + { + "iso639_1": "so", + "iso639_2": "som", + "name": "Somali", + "nativeName": "Soomaaliga" + }, + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Somalia", + "pt": "Somália", + "nl": "Somalië", + "hr": "Somalija", + "fa": "سومالی", + "de": "Somalia", + "es": "Somalia", + "fr": "Somalie", + "ja": "ソマリア", + "it": "Somalia", + "hu": "Szomália" + }, + "flag": "https://flagcdn.com/so.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "SOM", + "independent": true + }, + { + "name": "South Africa", + "topLevelDomain": [ + ".za" + ], + "alpha2Code": "ZA", + "alpha3Code": "ZAF", + "callingCodes": [ + "27" + ], + "capital": "Pretoria", + "altSpellings": [ + "ZA", + "RSA", + "Suid-Afrika", + "Republic of South Africa" + ], + "subregion": "Southern Africa", + "region": "Africa", + "population": 59308690, + "latlng": [ + -29.0, + 24.0 + ], + "demonym": "South African", + "area": 1221037.0, + "gini": 63.0, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "BWA", + "LSO", + "MOZ", + "NAM", + "SWZ", + "ZWE" + ], + "nativeName": "South Africa", + "numericCode": "710", + "flags": { + "svg": "https://flagcdn.com/za.svg", + "png": "https://flagcdn.com/w320/za.png" + }, + "currencies": [ + { + "code": "ZAR", + "name": "South African rand", + "symbol": "R" + } + ], + "languages": [ + { + "iso639_1": "af", + "iso639_2": "afr", + "name": "Afrikaans", + "nativeName": "Afrikaans" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "nr", + "iso639_2": "nbl", + "name": "Southern Ndebele", + "nativeName": "isiNdebele" + }, + { + "iso639_1": "st", + "iso639_2": "sot", + "name": "Southern Sotho", + "nativeName": "Sesotho" + }, + { + "iso639_1": "ss", + "iso639_2": "ssw", + "name": "Swati", + "nativeName": "SiSwati" + }, + { + "iso639_1": "tn", + "iso639_2": "tsn", + "name": "Tswana", + "nativeName": "Setswana" + }, + { + "iso639_1": "ts", + "iso639_2": "tso", + "name": "Tsonga", + "nativeName": "Xitsonga" + }, + { + "iso639_1": "ve", + "iso639_2": "ven", + "name": "Venda", + "nativeName": "Tshivenḓa" + }, + { + "iso639_1": "xh", + "iso639_2": "xho", + "name": "Xhosa", + "nativeName": "isiXhosa" + }, + { + "iso639_1": "zu", + "iso639_2": "zul", + "name": "Zulu", + "nativeName": "isiZulu" + } + ], + "translations": { + "br": "Suafrika", + "pt": "República Sul-Africana", + "nl": "Zuid-Afrika", + "hr": "Južnoafrička Republika", + "fa": "آفریقای جنوبی", + "de": "Republik Südafrika", + "es": "República de Sudáfrica", + "fr": "Afrique du Sud", + "ja": "南アフリカ", + "it": "Sud Africa", + "hu": "Dél-afrikai Köztársaság" + }, + "flag": "https://flagcdn.com/za.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "RSA", + "independent": true + }, + { + "name": "South Georgia and the South Sandwich Islands", + "topLevelDomain": [ + ".gs" + ], + "alpha2Code": "GS", + "alpha3Code": "SGS", + "callingCodes": [ + "500" + ], + "capital": "King Edward Point", + "altSpellings": [ + "GS", + "South Georgia and the South Sandwich Islands" + ], + "subregion": "South America", + "region": "Americas", + "population": 30, + "latlng": [ + -54.5, + -37.0 + ], + "demonym": "South Georgia and the South Sandwich Islander", + "timezones": [ + "UTC-02:00" + ], + "nativeName": "South Georgia", + "numericCode": "239", + "flags": { + "svg": "https://flagcdn.com/gs.svg", + "png": "https://flagcdn.com/w320/gs.png" + }, + "currencies": [ + { + "code": "FKP", + "name": "Falkland Islands Pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Georgia ar Su hag Inizi Sandwich ar Su", + "pt": "Ilhas Geórgia do Sul e Sanduíche do Sul", + "nl": "Zuid-Georgia en Zuidelijke Sandwicheilanden", + "hr": "Južna Georgija i otočje Južni Sandwich", + "fa": "جزایر جورجیای جنوبی و ساندویچ جنوبی", + "de": "Südgeorgien und die Südlichen Sandwichinseln", + "es": "Islas Georgias del Sur y Sandwich del Sur", + "fr": "Géorgie du Sud-et-les Îles Sandwich du Sud", + "ja": "サウスジョージア・サウスサンドウィッチ諸島", + "it": "Georgia del Sud e Isole Sandwich Meridionali", + "hu": "Déli-Georgia és Déli-Sandwich-szigetek" + }, + "flag": "https://flagcdn.com/gs.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "independent": false + }, + { + "name": "Korea (Republic of)", + "topLevelDomain": [ + ".kr" + ], + "alpha2Code": "KR", + "alpha3Code": "KOR", + "callingCodes": [ + "82" + ], + "capital": "Seoul", + "altSpellings": [ + "KR", + "Republic of Korea" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 51780579, + "latlng": [ + 37.0, + 127.5 + ], + "demonym": "South Korean", + "area": 100210.0, + "gini": 31.4, + "timezones": [ + "UTC+09:00" + ], + "borders": [ + "PRK" + ], + "nativeName": "대한민국", + "numericCode": "410", + "flags": { + "svg": "https://flagcdn.com/kr.svg", + "png": "https://flagcdn.com/w320/kr.png" + }, + "currencies": [ + { + "code": "KRW", + "name": "South Korean won", + "symbol": "₩" + } + ], + "languages": [ + { + "iso639_1": "ko", + "iso639_2": "kor", + "name": "Korean", + "nativeName": "한국어" + } + ], + "translations": { + "br": "Korea ar Su", + "pt": "Coreia do Sul", + "nl": "Zuid-Korea", + "hr": "Južna Koreja", + "fa": "کره شمالی", + "de": "Südkorea", + "es": "Corea del Sur", + "fr": "Corée du Sud", + "ja": "大韓民国", + "it": "Corea del Sud", + "hu": "Dél-Korea" + }, + "flag": "https://flagcdn.com/kr.svg", + "cioc": "KOR", + "independent": true + }, + { + "name": "Spain", + "topLevelDomain": [ + ".es" + ], + "alpha2Code": "ES", + "alpha3Code": "ESP", + "callingCodes": [ + "34" + ], + "capital": "Madrid", + "altSpellings": [ + "ES", + "Kingdom of Spain", + "Reino de España" + ], + "subregion": "Southern Europe", + "region": "Europe", + "population": 47351567, + "latlng": [ + 40.0, + -4.0 + ], + "demonym": "Spanish", + "area": 505992.0, + "gini": 34.7, + "timezones": [ + "UTC", + "UTC+01:00" + ], + "borders": [ + "AND", + "FRA", + "GIB", + "PRT", + "MAR" + ], + "nativeName": "España", + "numericCode": "724", + "flags": { + "svg": "https://flagcdn.com/es.svg", + "png": "https://flagcdn.com/w320/es.png" + }, + "currencies": [ + { + "code": "EUR", + "name": "Euro", + "symbol": "€" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Spagn", + "pt": "Espanha", + "nl": "Spanje", + "hr": "Španjolska", + "fa": "اسپانیا", + "de": "Spanien", + "es": "España", + "fr": "Espagne", + "ja": "スペイン", + "it": "Spagna", + "hu": "Spanyolország" + }, + "flag": "https://flagcdn.com/es.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "ESP", + "independent": true + }, + { + "name": "Sri Lanka", + "topLevelDomain": [ + ".lk" + ], + "alpha2Code": "LK", + "alpha3Code": "LKA", + "callingCodes": [ + "94" + ], + "capital": "Sri Jayawardenepura Kotte", + "altSpellings": [ + "LK", + "ilaṅkai", + "Democratic Socialist Republic of Sri Lanka" + ], + "subregion": "Southern Asia", + "region": "Asia", + "population": 21919000, + "latlng": [ + 7.0, + 81.0 + ], + "demonym": "Sri Lankan", + "area": 65610.0, + "gini": 39.3, + "timezones": [ + "UTC+05:30" + ], + "borders": [ + "IND" + ], + "nativeName": "śrī laṃkāva", + "numericCode": "144", + "flags": { + "svg": "https://flagcdn.com/lk.svg", + "png": "https://flagcdn.com/w320/lk.png" + }, + "currencies": [ + { + "code": "LKR", + "name": "Sri Lankan rupee", + "symbol": "Rs" + } + ], + "languages": [ + { + "iso639_1": "si", + "iso639_2": "sin", + "name": "Sinhalese", + "nativeName": "සිංහල" + }, + { + "iso639_1": "ta", + "iso639_2": "tam", + "name": "Tamil", + "nativeName": "தமிழ்" + } + ], + "translations": { + "br": "Sri Lanka", + "pt": "Sri Lanka", + "nl": "Sri Lanka", + "hr": "Šri Lanka", + "fa": "سری‌لانکا", + "de": "Sri Lanka", + "es": "Sri Lanka", + "fr": "Sri Lanka", + "ja": "スリランカ", + "it": "Sri Lanka", + "hu": "Srí Lanka" + }, + "flag": "https://flagcdn.com/lk.svg", + "regionalBlocs": [ + { + "acronym": "SAARC", + "name": "South Asian Association for Regional Cooperation" + } + ], + "cioc": "SRI", + "independent": true + }, + { + "name": "Sudan", + "topLevelDomain": [ + ".sd" + ], + "alpha2Code": "SD", + "alpha3Code": "SDN", + "callingCodes": [ + "249" + ], + "capital": "Khartoum", + "altSpellings": [ + "SD", + "Republic of the Sudan", + "Jumhūrīyat as-Sūdān" + ], + "subregion": "Northern Africa", + "region": "Africa", + "population": 43849269, + "latlng": [ + 15.0, + 30.0 + ], + "demonym": "Sudanese", + "area": 1886068.0, + "gini": 34.2, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "CAF", + "TCD", + "EGY", + "ERI", + "ETH", + "LBY", + "SSD" + ], + "nativeName": "السودان", + "numericCode": "729", + "flags": { + "svg": "https://flagcdn.com/sd.svg", + "png": "https://flagcdn.com/w320/sd.png" + }, + "currencies": [ + { + "code": "SDG", + "name": "Sudanese pound", + "symbol": "ج.س." + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Soudan", + "pt": "Sudão", + "nl": "Soedan", + "hr": "Sudan", + "fa": "سودان", + "de": "Sudan", + "es": "Sudán", + "fr": "Soudan", + "ja": "スーダン", + "it": "Sudan", + "hu": "Szudán" + }, + "flag": "https://flagcdn.com/sd.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "SUD", + "independent": true + }, + { + "name": "South Sudan", + "topLevelDomain": [ + ".ss" + ], + "alpha2Code": "SS", + "alpha3Code": "SSD", + "callingCodes": [ + "211" + ], + "capital": "Juba", + "altSpellings": [ + "SS" + ], + "subregion": "Middle Africa", + "region": "Africa", + "population": 11193729, + "latlng": [ + 7.0, + 30.0 + ], + "demonym": "South Sudanese", + "area": 619745.0, + "gini": 44.1, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "CAF", + "COD", + "ETH", + "KEN", + "SDN", + "UGA" + ], + "nativeName": "South Sudan", + "numericCode": "728", + "flags": { + "svg": "https://flagcdn.com/ss.svg", + "png": "https://flagcdn.com/w320/ss.png" + }, + "currencies": [ + { + "code": "SSP", + "name": "South Sudanese pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Soudan ar Su", + "pt": "Sudão do Sul", + "nl": "Zuid-Soedan", + "hr": "Južni Sudan", + "fa": "سودان جنوبی", + "de": "Südsudan", + "es": "Sudán del Sur", + "fr": "Soudan du Sud", + "ja": "南スーダン", + "it": "Sudan del sud", + "hu": "Dél-Szudán" + }, + "flag": "https://flagcdn.com/ss.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "SSD", + "independent": true + }, + { + "name": "Suriname", + "topLevelDomain": [ + ".sr" + ], + "alpha2Code": "SR", + "alpha3Code": "SUR", + "callingCodes": [ + "597" + ], + "capital": "Paramaribo", + "altSpellings": [ + "SR", + "Sarnam", + "Sranangron", + "Republic of Suriname", + "Republiek Suriname" + ], + "subregion": "South America", + "region": "Americas", + "population": 586634, + "latlng": [ + 4.0, + -56.0 + ], + "demonym": "Surinamer", + "area": 163820.0, + "gini": 57.9, + "timezones": [ + "UTC-03:00" + ], + "borders": [ + "BRA", + "FRA", + "GUF", + "GUY" + ], + "nativeName": "Suriname", + "numericCode": "740", + "flags": { + "svg": "https://flagcdn.com/sr.svg", + "png": "https://flagcdn.com/w320/sr.png" + }, + "currencies": [ + { + "code": "SRD", + "name": "Surinamese dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "nl", + "iso639_2": "nld", + "name": "Dutch", + "nativeName": "Nederlands" + } + ], + "translations": { + "br": "Surinam", + "pt": "Suriname", + "nl": "Suriname", + "hr": "Surinam", + "fa": "سورینام", + "de": "Suriname", + "es": "Surinam", + "fr": "Surinam", + "ja": "スリナム", + "it": "Suriname", + "hu": "Suriname" + }, + "flag": "https://flagcdn.com/sr.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + }, + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "SUR", + "independent": true + }, + { + "name": "Svalbard and Jan Mayen", + "topLevelDomain": [ + ".sj" + ], + "alpha2Code": "SJ", + "alpha3Code": "SJM", + "callingCodes": [ + "47" + ], + "capital": "Longyearbyen", + "altSpellings": [ + "SJ", + "Svalbard and Jan Mayen Islands" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 2562, + "latlng": [ + 78.0, + 20.0 + ], + "demonym": "Norwegian", + "timezones": [ + "UTC+01:00" + ], + "nativeName": "Svalbard og Jan Mayen", + "numericCode": "744", + "flags": { + "svg": "https://flagcdn.com/sj.svg", + "png": "https://flagcdn.com/w320/sj.png" + }, + "currencies": [ + { + "code": "NOK", + "name": "Norwegian krone", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "no", + "iso639_2": "nor", + "name": "Norwegian", + "nativeName": "Norsk" + } + ], + "translations": { + "br": "Svalbard ha Jan Mayen", + "pt": "Svalbard", + "nl": "Svalbard en Jan Mayen", + "hr": "Svalbard i Jan Mayen", + "fa": "سوالبارد و یان ماین", + "de": "Svalbard und Jan Mayen", + "es": "Islas Svalbard y Jan Mayen", + "fr": "Svalbard et Jan Mayen", + "ja": "スヴァールバル諸島およびヤンマイエン島", + "it": "Svalbard e Jan Mayen", + "hu": "Spitzbergák és Jan Mayen-szigetek" + }, + "flag": "https://flagcdn.com/sj.svg", + "independent": false + }, + { + "name": "Swaziland", + "topLevelDomain": [ + ".sz" + ], + "alpha2Code": "SZ", + "alpha3Code": "SWZ", + "callingCodes": [ + "268" + ], + "capital": "Mbabane", + "altSpellings": [ + "SZ", + "weSwatini", + "Swatini", + "Ngwane", + "Kingdom of Swaziland", + "Umbuso waseSwatini" + ], + "subregion": "Southern Africa", + "region": "Africa", + "population": 1160164, + "latlng": [ + -26.5, + 31.5 + ], + "demonym": "Swazi", + "area": 17364.0, + "gini": 54.6, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "MOZ", + "ZAF" + ], + "nativeName": "Swaziland", + "numericCode": "748", + "flags": { + "svg": "https://flagcdn.com/sz.svg", + "png": "https://flagcdn.com/w320/sz.png" + }, + "currencies": [ + { + "code": "SZL", + "name": "Swazi lilangeni", + "symbol": "L" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "ss", + "iso639_2": "ssw", + "name": "Swati", + "nativeName": "SiSwati" + } + ], + "translations": { + "br": "Eswatini", + "pt": "Suazilândia", + "nl": "Swaziland", + "hr": "Svazi", + "fa": "سوازیلند", + "de": "Swasiland", + "es": "Suazilandia", + "fr": "Swaziland", + "ja": "スワジランド", + "it": "Swaziland", + "hu": "Szváziföld" + }, + "flag": "https://flagcdn.com/sz.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "SWZ", + "independent": true + }, + { + "name": "Sweden", + "topLevelDomain": [ + ".se" + ], + "alpha2Code": "SE", + "alpha3Code": "SWE", + "callingCodes": [ + "46" + ], + "capital": "Stockholm", + "altSpellings": [ + "SE", + "Kingdom of Sweden", + "Konungariket Sverige" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 10353442, + "latlng": [ + 62.0, + 15.0 + ], + "demonym": "Swedish", + "area": 450295.0, + "gini": 30.0, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "FIN", + "NOR" + ], + "nativeName": "Sverige", + "numericCode": "752", + "flags": { + "svg": "https://flagcdn.com/se.svg", + "png": "https://flagcdn.com/w320/se.png" + }, + "currencies": [ + { + "code": "SEK", + "name": "Swedish krona", + "symbol": "kr" + } + ], + "languages": [ + { + "iso639_1": "sv", + "iso639_2": "swe", + "name": "Swedish", + "nativeName": "svenska" + } + ], + "translations": { + "br": "Sveden", + "pt": "Suécia", + "nl": "Zweden", + "hr": "Švedska", + "fa": "سوئد", + "de": "Schweden", + "es": "Suecia", + "fr": "Suède", + "ja": "スウェーデン", + "it": "Svezia", + "hu": "Svédország" + }, + "flag": "https://flagcdn.com/se.svg", + "regionalBlocs": [ + { + "acronym": "EU", + "name": "European Union" + } + ], + "cioc": "SWE", + "independent": true + }, + { + "name": "Switzerland", + "topLevelDomain": [ + ".ch" + ], + "alpha2Code": "CH", + "alpha3Code": "CHE", + "callingCodes": [ + "41" + ], + "capital": "Bern", + "altSpellings": [ + "CH", + "Swiss Confederation", + "Schweiz", + "Suisse", + "Svizzera", + "Svizra" + ], + "subregion": "Central Europe", + "region": "Europe", + "population": 8636896, + "latlng": [ + 47.0, + 8.0 + ], + "demonym": "Swiss", + "area": 41284.0, + "gini": 33.1, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "AUT", + "FRA", + "ITA", + "LIE", + "DEU" + ], + "nativeName": "Schweiz", + "numericCode": "756", + "flags": { + "svg": "https://flagcdn.com/ch.svg", + "png": "https://flagcdn.com/w320/ch.png" + }, + "currencies": [ + { + "code": "CHF", + "name": "Swiss franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "de", + "iso639_2": "deu", + "name": "German", + "nativeName": "Deutsch" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + }, + { + "iso639_1": "it", + "iso639_2": "ita", + "name": "Italian", + "nativeName": "Italiano" + }, + { + "iso639_2": "roh", + "name": "Romansh" + } + ], + "translations": { + "br": "Suis", + "pt": "Suíça", + "nl": "Zwitserland", + "hr": "Švicarska", + "fa": "سوئیس", + "de": "Schweiz", + "es": "Suiza", + "fr": "Suisse", + "ja": "スイス", + "it": "Svizzera", + "hu": "Svájc" + }, + "flag": "https://flagcdn.com/ch.svg", + "regionalBlocs": [ + { + "acronym": "EFTA", + "name": "European Free Trade Association" + } + ], + "cioc": "SUI", + "independent": true + }, + { + "name": "Syrian Arab Republic", + "topLevelDomain": [ + ".sy" + ], + "alpha2Code": "SY", + "alpha3Code": "SYR", + "callingCodes": [ + "963" + ], + "capital": "Damascus", + "altSpellings": [ + "SY", + "Syrian Arab Republic", + "Al-Jumhūrīyah Al-ʻArabīyah As-Sūrīyah" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 17500657, + "latlng": [ + 35.0, + 38.0 + ], + "demonym": "Syrian", + "area": 185180.0, + "gini": 37.5, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "IRQ", + "ISR", + "JOR", + "LBN", + "TUR" + ], + "nativeName": "سوريا", + "numericCode": "760", + "flags": { + "svg": "https://flagcdn.com/sy.svg", + "png": "https://flagcdn.com/w320/sy.png" + }, + "currencies": [ + { + "code": "SYP", + "name": "Syrian pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Siria", + "pt": "Síria", + "nl": "Syrië", + "hr": "Sirija", + "fa": "سوریه", + "de": "Syrien", + "es": "Siria", + "fr": "Syrie", + "ja": "シリア・アラブ共和国", + "it": "Siria", + "hu": "Szíria" + }, + "flag": "https://flagcdn.com/sy.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "SYR", + "independent": true + }, + { + "name": "Taiwan", + "topLevelDomain": [ + ".tw" + ], + "alpha2Code": "TW", + "alpha3Code": "TWN", + "callingCodes": [ + "886" + ], + "capital": "Taipei", + "altSpellings": [ + "TW", + "Táiwān", + "Republic of China", + "中華民國", + "Zhōnghuá Mínguó" + ], + "subregion": "Eastern Asia", + "region": "Asia", + "population": 23503349, + "latlng": [ + 23.5, + 121.0 + ], + "demonym": "Taiwanese", + "area": 36193.0, + "timezones": [ + "UTC+08:00" + ], + "nativeName": "臺灣", + "numericCode": "158", + "flags": { + "svg": "https://flagcdn.com/tw.svg", + "png": "https://flagcdn.com/w320/tw.png" + }, + "currencies": [ + { + "code": "TWD", + "name": "New Taiwan dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "zh", + "iso639_2": "zho", + "name": "Chinese", + "nativeName": "中文 (Zhōngwén)" + } + ], + "translations": { + "br": "Taiwan", + "pt": "Taiwan", + "nl": "Taiwan", + "hr": "Tajvan", + "fa": "تایوان", + "de": "Taiwan", + "es": "Taiwán", + "fr": "Taïwan", + "ja": "台湾(中華民国)", + "it": "Taiwan", + "hu": "Tajvan" + }, + "flag": "https://flagcdn.com/tw.svg", + "cioc": "TPE", + "independent": true + }, + { + "name": "Tajikistan", + "topLevelDomain": [ + ".tj" + ], + "alpha2Code": "TJ", + "alpha3Code": "TJK", + "callingCodes": [ + "992" + ], + "capital": "Dushanbe", + "altSpellings": [ + "TJ", + "Toçikiston", + "Republic of Tajikistan", + "Ҷумҳурии Тоҷикистон", + "Çumhuriyi Toçikiston" + ], + "subregion": "Central Asia", + "region": "Asia", + "population": 9537642, + "latlng": [ + 39.0, + 71.0 + ], + "demonym": "Tadzhik", + "area": 143100.0, + "gini": 34.0, + "timezones": [ + "UTC+05:00" + ], + "borders": [ + "AFG", + "CHN", + "KGZ", + "UZB" + ], + "nativeName": "Тоҷикистон", + "numericCode": "762", + "flags": { + "svg": "https://flagcdn.com/tj.svg", + "png": "https://flagcdn.com/w320/tj.png" + }, + "currencies": [ + { + "code": "TJS", + "name": "Tajikistani somoni", + "symbol": "ЅМ" + } + ], + "languages": [ + { + "iso639_1": "tg", + "iso639_2": "tgk", + "name": "Tajik", + "nativeName": "тоҷикӣ" + }, + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Tadjikistan", + "pt": "Tajiquistão", + "nl": "Tadzjikistan", + "hr": "Tađikistan", + "fa": "تاجیکستان", + "de": "Tadschikistan", + "es": "Tayikistán", + "fr": "Tadjikistan", + "ja": "タジキスタン", + "it": "Tagikistan", + "hu": "Tádzsikisztán" + }, + "flag": "https://flagcdn.com/tj.svg", + "cioc": "TJK", + "independent": true + }, + { + "name": "Tanzania, United Republic of", + "topLevelDomain": [ + ".tz" + ], + "alpha2Code": "TZ", + "alpha3Code": "TZA", + "callingCodes": [ + "255" + ], + "capital": "Dodoma", + "altSpellings": [ + "TZ", + "United Republic of Tanzania", + "Jamhuri ya Muungano wa Tanzania" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 59734213, + "latlng": [ + -6.0, + 35.0 + ], + "demonym": "Tanzanian", + "area": 945087.0, + "gini": 40.5, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "BDI", + "COD", + "KEN", + "MWI", + "MOZ", + "RWA", + "UGA", + "ZMB" + ], + "nativeName": "Tanzania", + "numericCode": "834", + "flags": { + "svg": "https://flagcdn.com/tz.svg", + "png": "https://flagcdn.com/w320/tz.png" + }, + "currencies": [ + { + "code": "TZS", + "name": "Tanzanian shilling", + "symbol": "Sh" + } + ], + "languages": [ + { + "iso639_1": "sw", + "iso639_2": "swa", + "name": "Swahili", + "nativeName": "Kiswahili" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Tanzania", + "pt": "Tanzânia", + "nl": "Tanzania", + "hr": "Tanzanija", + "fa": "تانزانیا", + "de": "Tansania", + "es": "Tanzania", + "fr": "Tanzanie", + "ja": "タンザニア", + "it": "Tanzania", + "hu": "Tanzánia" + }, + "flag": "https://flagcdn.com/tz.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "TAN", + "independent": true + }, + { + "name": "Thailand", + "topLevelDomain": [ + ".th" + ], + "alpha2Code": "TH", + "alpha3Code": "THA", + "callingCodes": [ + "66" + ], + "capital": "Bangkok", + "altSpellings": [ + "TH", + "Prathet", + "Thai", + "Kingdom of Thailand", + "ราชอาณาจักรไทย", + "Ratcha Anachak Thai" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 69799978, + "latlng": [ + 15.0, + 100.0 + ], + "demonym": "Thai", + "area": 513120.0, + "gini": 34.9, + "timezones": [ + "UTC+07:00" + ], + "borders": [ + "MMR", + "KHM", + "LAO", + "MYS" + ], + "nativeName": "ประเทศไทย", + "numericCode": "764", + "flags": { + "svg": "https://flagcdn.com/th.svg", + "png": "https://flagcdn.com/w320/th.png" + }, + "currencies": [ + { + "code": "THB", + "name": "Thai baht", + "symbol": "฿" + } + ], + "languages": [ + { + "iso639_1": "th", + "iso639_2": "tha", + "name": "Thai", + "nativeName": "ไทย" + } + ], + "translations": { + "br": "Thailand", + "pt": "Tailândia", + "nl": "Thailand", + "hr": "Tajland", + "fa": "تایلند", + "de": "Thailand", + "es": "Tailandia", + "fr": "Thaïlande", + "ja": "タイ", + "it": "Tailandia", + "hu": "Thaiföld" + }, + "flag": "https://flagcdn.com/th.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "THA", + "independent": true + }, + { + "name": "Timor-Leste", + "topLevelDomain": [ + ".tl" + ], + "alpha2Code": "TL", + "alpha3Code": "TLS", + "callingCodes": [ + "670" + ], + "capital": "Dili", + "altSpellings": [ + "TL", + "East Timor", + "Democratic Republic of Timor-Leste", + "República Democrática de Timor-Leste", + "Repúblika Demokrátika Timór-Leste" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 1318442, + "latlng": [ + -8.83333333, + 125.91666666 + ], + "demonym": "East Timorese", + "area": 14874.0, + "gini": 28.7, + "timezones": [ + "UTC+09:00" + ], + "borders": [ + "IDN" + ], + "nativeName": "Timor-Leste", + "numericCode": "626", + "flags": { + "svg": "https://flagcdn.com/tl.svg", + "png": "https://flagcdn.com/w320/tl.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States Dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "pt", + "iso639_2": "por", + "name": "Portuguese", + "nativeName": "Português" + } + ], + "translations": { + "br": "Timor ar Reter", + "pt": "Timor Leste", + "nl": "Oost-Timor", + "hr": "Istočni Timor", + "fa": "تیمور شرقی", + "de": "Timor-Leste", + "es": "Timor Oriental", + "fr": "Timor oriental", + "ja": "東ティモール", + "it": "Timor Est", + "hu": "Kelet-Timor" + }, + "flag": "https://flagcdn.com/tl.svg", + "cioc": "TLS", + "independent": true + }, + { + "name": "Togo", + "topLevelDomain": [ + ".tg" + ], + "alpha2Code": "TG", + "alpha3Code": "TGO", + "callingCodes": [ + "228" + ], + "capital": "Lomé", + "altSpellings": [ + "TG", + "Togolese", + "Togolese Republic", + "République Togolaise" + ], + "subregion": "Western Africa", + "region": "Africa", + "population": 8278737, + "latlng": [ + 8.0, + 1.16666666 + ], + "demonym": "Togolese", + "area": 56785.0, + "gini": 43.1, + "timezones": [ + "UTC" + ], + "borders": [ + "BEN", + "BFA", + "GHA" + ], + "nativeName": "Togo", + "numericCode": "768", + "flags": { + "svg": "https://flagcdn.com/tg.svg", + "png": "https://flagcdn.com/w320/tg.png" + }, + "currencies": [ + { + "code": "XOF", + "name": "West African CFA franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Togo", + "pt": "Togo", + "nl": "Togo", + "hr": "Togo", + "fa": "توگو", + "de": "Togo", + "es": "Togo", + "fr": "Togo", + "ja": "トーゴ", + "it": "Togo", + "hu": "Togo" + }, + "flag": "https://flagcdn.com/tg.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "TOG", + "independent": true + }, + { + "name": "Tokelau", + "topLevelDomain": [ + ".tk" + ], + "alpha2Code": "TK", + "alpha3Code": "TKL", + "callingCodes": [ + "690" + ], + "capital": "Fakaofo", + "altSpellings": [ + "TK" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 1411, + "latlng": [ + -9.0, + -172.0 + ], + "demonym": "Tokelauan", + "area": 12.0, + "timezones": [ + "UTC+13:00" + ], + "nativeName": "Tokelau", + "numericCode": "772", + "flags": { + "svg": "https://flagcdn.com/tk.svg", + "png": "https://flagcdn.com/w320/tk.png" + }, + "currencies": [ + { + "code": "NZD", + "name": "New Zealand dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Tokelau", + "pt": "Toquelau", + "nl": "Tokelau", + "hr": "Tokelau", + "fa": "توکلائو", + "de": "Tokelau", + "es": "Islas Tokelau", + "fr": "Tokelau", + "ja": "トケラウ", + "it": "Isole Tokelau", + "hu": "Tokelau-szigetek" + }, + "flag": "https://flagcdn.com/tk.svg", + "independent": false + }, + { + "name": "Tonga", + "topLevelDomain": [ + ".to" + ], + "alpha2Code": "TO", + "alpha3Code": "TON", + "callingCodes": [ + "676" + ], + "capital": "Nuku'alofa", + "altSpellings": [ + "TO" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 105697, + "latlng": [ + -20.0, + -175.0 + ], + "demonym": "Tongan", + "area": 747.0, + "gini": 37.6, + "timezones": [ + "UTC+13:00" + ], + "nativeName": "Tonga", + "numericCode": "776", + "flags": { + "svg": "https://flagcdn.com/to.svg", + "png": "https://flagcdn.com/w320/to.png" + }, + "currencies": [ + { + "code": "TOP", + "name": "Tongan paʻanga", + "symbol": "T$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "to", + "iso639_2": "ton", + "name": "Tonga (Tonga Islands)", + "nativeName": "faka Tonga" + } + ], + "translations": { + "br": "Tonga", + "pt": "Tonga", + "nl": "Tonga", + "hr": "Tonga", + "fa": "تونگا", + "de": "Tonga", + "es": "Tonga", + "fr": "Tonga", + "ja": "トンガ", + "it": "Tonga", + "hu": "Tonga" + }, + "flag": "https://flagcdn.com/to.svg", + "cioc": "TGA", + "independent": true + }, + { + "name": "Trinidad and Tobago", + "topLevelDomain": [ + ".tt" + ], + "alpha2Code": "TT", + "alpha3Code": "TTO", + "callingCodes": [ + "1" + ], + "capital": "Port of Spain", + "altSpellings": [ + "TT", + "Republic of Trinidad and Tobago" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 1399491, + "latlng": [ + 11.0, + -61.0 + ], + "demonym": "Trinidadian", + "area": 5130.0, + "gini": 40.3, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Trinidad and Tobago", + "numericCode": "780", + "flags": { + "svg": "https://flagcdn.com/tt.svg", + "png": "https://flagcdn.com/w320/tt.png" + }, + "currencies": [ + { + "code": "TTD", + "name": "Trinidad and Tobago dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Trinidad ha Tobago", + "pt": "Trindade e Tobago", + "nl": "Trinidad en Tobago", + "hr": "Trinidad i Tobago", + "fa": "ترینیداد و توباگو", + "de": "Trinidad und Tobago", + "es": "Trinidad y Tobago", + "fr": "Trinité et Tobago", + "ja": "トリニダード・トバゴ", + "it": "Trinidad e Tobago", + "hu": "Trinidad és Tobago" + }, + "flag": "https://flagcdn.com/tt.svg", + "regionalBlocs": [ + { + "acronym": "CARICOM", + "name": "Caribbean Community", + "otherNames": [ + "Comunidad del Caribe", + "Communauté Caribéenne", + "Caribische Gemeenschap" + ] + } + ], + "cioc": "TTO", + "independent": true + }, + { + "name": "Tunisia", + "topLevelDomain": [ + ".tn" + ], + "alpha2Code": "TN", + "alpha3Code": "TUN", + "callingCodes": [ + "216" + ], + "capital": "Tunis", + "altSpellings": [ + "TN", + "Republic of Tunisia", + "al-Jumhūriyyah at-Tūnisiyyah" + ], + "subregion": "Northern Africa", + "region": "Africa", + "population": 11818618, + "latlng": [ + 34.0, + 9.0 + ], + "demonym": "Tunisian", + "area": 163610.0, + "gini": 32.8, + "timezones": [ + "UTC+01:00" + ], + "borders": [ + "DZA", + "LBY" + ], + "nativeName": "تونس", + "numericCode": "788", + "flags": { + "svg": "https://flagcdn.com/tn.svg", + "png": "https://flagcdn.com/w320/tn.png" + }, + "currencies": [ + { + "code": "TND", + "name": "Tunisian dinar", + "symbol": "د.ت" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Tunizia", + "pt": "Tunísia", + "nl": "Tunesië", + "hr": "Tunis", + "fa": "تونس", + "de": "Tunesien", + "es": "Túnez", + "fr": "Tunisie", + "ja": "チュニジア", + "it": "Tunisia", + "hu": "Tunézia" + }, + "flag": "https://flagcdn.com/tn.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + }, + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "TUN", + "independent": true + }, + { + "name": "Turkey", + "topLevelDomain": [ + ".tr" + ], + "alpha2Code": "TR", + "alpha3Code": "TUR", + "callingCodes": [ + "90" + ], + "capital": "Ankara", + "altSpellings": [ + "TR", + "Turkiye", + "Republic of Turkey", + "Türkiye Cumhuriyeti" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 84339067, + "latlng": [ + 39.0, + 35.0 + ], + "demonym": "Turkish", + "area": 783562.0, + "gini": 41.9, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "ARM", + "AZE", + "BGR", + "GEO", + "GRC", + "IRN", + "IRQ", + "SYR" + ], + "nativeName": "Türkiye", + "numericCode": "792", + "flags": { + "svg": "https://flagcdn.com/tr.svg", + "png": "https://flagcdn.com/w320/tr.png" + }, + "currencies": [ + { + "code": "TRY", + "name": "Turkish lira", + "symbol": "₺" + } + ], + "languages": [ + { + "iso639_1": "tr", + "iso639_2": "tur", + "name": "Turkish", + "nativeName": "Türkçe" + } + ], + "translations": { + "br": "Turkia", + "pt": "Turquia", + "nl": "Turkije", + "hr": "Turska", + "fa": "ترکیه", + "de": "Türkei", + "es": "Turquía", + "fr": "Turquie", + "ja": "トルコ", + "it": "Turchia", + "hu": "Törökország" + }, + "flag": "https://flagcdn.com/tr.svg", + "cioc": "TUR", + "independent": true + }, + { + "name": "Turkmenistan", + "topLevelDomain": [ + ".tm" + ], + "alpha2Code": "TM", + "alpha3Code": "TKM", + "callingCodes": [ + "993" + ], + "capital": "Ashgabat", + "altSpellings": [ + "TM" + ], + "subregion": "Central Asia", + "region": "Asia", + "population": 6031187, + "latlng": [ + 40.0, + 60.0 + ], + "demonym": "Turkmen", + "area": 488100.0, + "gini": 40.8, + "timezones": [ + "UTC+05:00" + ], + "borders": [ + "AFG", + "IRN", + "KAZ", + "UZB" + ], + "nativeName": "Türkmenistan", + "numericCode": "795", + "flags": { + "svg": "https://flagcdn.com/tm.svg", + "png": "https://flagcdn.com/w320/tm.png" + }, + "currencies": [ + { + "code": "TMT", + "name": "Turkmenistan manat", + "symbol": "m" + } + ], + "languages": [ + { + "iso639_1": "tk", + "iso639_2": "tuk", + "name": "Turkmen", + "nativeName": "Türkmen" + }, + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Turkmenistan", + "pt": "Turquemenistão", + "nl": "Turkmenistan", + "hr": "Turkmenistan", + "fa": "ترکمنستان", + "de": "Turkmenistan", + "es": "Turkmenistán", + "fr": "Turkménistan", + "ja": "トルクメニスタン", + "it": "Turkmenistan", + "hu": "Türkmenisztán" + }, + "flag": "https://flagcdn.com/tm.svg", + "cioc": "TKM", + "independent": true + }, + { + "name": "Turks and Caicos Islands", + "topLevelDomain": [ + ".tc" + ], + "alpha2Code": "TC", + "alpha3Code": "TCA", + "callingCodes": [ + "1" + ], + "capital": "Cockburn Town", + "altSpellings": [ + "TC" + ], + "subregion": "Caribbean", + "region": "Americas", + "population": 38718, + "latlng": [ + 21.75, + -71.58333333 + ], + "demonym": "Turks and Caicos Islander", + "area": 948.0, + "timezones": [ + "UTC-04:00" + ], + "nativeName": "Turks and Caicos Islands", + "numericCode": "796", + "flags": { + "svg": "https://flagcdn.com/tc.svg", + "png": "https://flagcdn.com/w320/tc.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Inizi Turks ha Caicos", + "pt": "Ilhas Turcas e Caicos", + "nl": "Turks- en Caicoseilanden", + "hr": "Otoci Turks i Caicos", + "fa": "جزایر تورکس و کایکوس", + "de": "Turks- und Caicosinseln", + "es": "Islas Turks y Caicos", + "fr": "Îles Turques-et-Caïques", + "ja": "タークス・カイコス諸島", + "it": "Isole Turks e Caicos", + "hu": "Turks- és Caicos-szigetek" + }, + "flag": "https://flagcdn.com/tc.svg", + "independent": false + }, + { + "name": "Tuvalu", + "topLevelDomain": [ + ".tv" + ], + "alpha2Code": "TV", + "alpha3Code": "TUV", + "callingCodes": [ + "688" + ], + "capital": "Funafuti", + "altSpellings": [ + "TV" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 11792, + "latlng": [ + -8.0, + 178.0 + ], + "demonym": "Tuvaluan", + "area": 26.0, + "gini": 39.1, + "timezones": [ + "UTC+12:00" + ], + "nativeName": "Tuvalu", + "numericCode": "798", + "flags": { + "svg": "https://flagcdn.com/tv.svg", + "png": "https://flagcdn.com/w320/tv.png" + }, + "currencies": [ + { + "code": "AUD", + "name": "Australian dollar", + "symbol": "$" + }, + { + "code": "TVD[G]", + "name": "Tuvaluan dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Tuvalu", + "pt": "Tuvalu", + "nl": "Tuvalu", + "hr": "Tuvalu", + "fa": "تووالو", + "de": "Tuvalu", + "es": "Tuvalu", + "fr": "Tuvalu", + "ja": "ツバル", + "it": "Tuvalu", + "hu": "Tuvalu" + }, + "flag": "https://flagcdn.com/tv.svg", + "cioc": "TUV", + "independent": true + }, + { + "name": "Uganda", + "topLevelDomain": [ + ".ug" + ], + "alpha2Code": "UG", + "alpha3Code": "UGA", + "callingCodes": [ + "256" + ], + "capital": "Kampala", + "altSpellings": [ + "UG", + "Republic of Uganda", + "Jamhuri ya Uganda" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 45741000, + "latlng": [ + 1.0, + 32.0 + ], + "demonym": "Ugandan", + "area": 241550.0, + "gini": 42.8, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "COD", + "KEN", + "RWA", + "SSD", + "TZA" + ], + "nativeName": "Uganda", + "numericCode": "800", + "flags": { + "svg": "https://flagcdn.com/ug.svg", + "png": "https://flagcdn.com/w320/ug.png" + }, + "currencies": [ + { + "code": "UGX", + "name": "Ugandan shilling", + "symbol": "Sh" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "sw", + "iso639_2": "swa", + "name": "Swahili", + "nativeName": "Kiswahili" + } + ], + "translations": { + "br": "Ouganda", + "pt": "Uganda", + "nl": "Oeganda", + "hr": "Uganda", + "fa": "اوگاندا", + "de": "Uganda", + "es": "Uganda", + "fr": "Uganda", + "ja": "ウガンダ", + "it": "Uganda", + "hu": "Uganda" + }, + "flag": "https://flagcdn.com/ug.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "UGA", + "independent": true + }, + { + "name": "Ukraine", + "topLevelDomain": [ + ".ua" + ], + "alpha2Code": "UA", + "alpha3Code": "UKR", + "callingCodes": [ + "380" + ], + "capital": "Kyiv", + "altSpellings": [ + "UA", + "Ukrayina" + ], + "subregion": "Eastern Europe", + "region": "Europe", + "population": 44134693, + "latlng": [ + 49.0, + 32.0 + ], + "demonym": "Ukrainian", + "area": 603700.0, + "gini": 26.6, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "BLR", + "HUN", + "MDA", + "POL", + "ROU", + "RUS", + "SVK" + ], + "nativeName": "Україна", + "numericCode": "804", + "flags": { + "svg": "https://flagcdn.com/ua.svg", + "png": "https://flagcdn.com/w320/ua.png" + }, + "currencies": [ + { + "code": "UAH", + "name": "Ukrainian hryvnia", + "symbol": "₴" + } + ], + "languages": [ + { + "iso639_1": "uk", + "iso639_2": "ukr", + "name": "Ukrainian", + "nativeName": "Українська" + } + ], + "translations": { + "br": "Ukraina", + "pt": "Ucrânia", + "nl": "Oekraïne", + "hr": "Ukrajina", + "fa": "وکراین", + "de": "Ukraine", + "es": "Ucrania", + "fr": "Ukraine", + "ja": "ウクライナ", + "it": "Ucraina", + "hu": "Ukrajna" + }, + "flag": "https://flagcdn.com/ua.svg", + "cioc": "UKR", + "independent": true + }, + { + "name": "United Arab Emirates", + "topLevelDomain": [ + ".ae" + ], + "alpha2Code": "AE", + "alpha3Code": "ARE", + "callingCodes": [ + "971" + ], + "capital": "Abu Dhabi", + "altSpellings": [ + "AE", + "UAE" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 9890400, + "latlng": [ + 24.0, + 54.0 + ], + "demonym": "Emirati", + "area": 83600.0, + "gini": 26.0, + "timezones": [ + "UTC+04:00" + ], + "borders": [ + "OMN", + "SAU" + ], + "nativeName": "دولة الإمارات العربية المتحدة", + "numericCode": "784", + "flags": { + "svg": "https://flagcdn.com/ae.svg", + "png": "https://flagcdn.com/w320/ae.png" + }, + "currencies": [ + { + "code": "AED", + "name": "United Arab Emirates dirham", + "symbol": "د.إ" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Emirelezhioù Arab Unanet", + "pt": "Emirados árabes Unidos", + "nl": "Verenigde Arabische Emiraten", + "hr": "Ujedinjeni Arapski Emirati", + "fa": "امارات متحده عربی", + "de": "Vereinigte Arabische Emirate", + "es": "Emiratos Árabes Unidos", + "fr": "Émirats arabes unis", + "ja": "アラブ首長国連邦", + "it": "Emirati Arabi Uniti", + "hu": "Egyesült Arab Emírségek" + }, + "flag": "https://flagcdn.com/ae.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "UAE", + "independent": true + }, + { + "name": "United Kingdom of Great Britain and Northern Ireland", + "topLevelDomain": [ + ".uk" + ], + "alpha2Code": "GB", + "alpha3Code": "GBR", + "callingCodes": [ + "44" + ], + "capital": "London", + "altSpellings": [ + "GB", + "UK", + "Great Britain" + ], + "subregion": "Northern Europe", + "region": "Europe", + "population": 67215293, + "latlng": [ + 54.0, + -2.0 + ], + "demonym": "British", + "area": 242900.0, + "gini": 35.1, + "timezones": [ + "UTC-08:00", + "UTC-05:00", + "UTC-04:00", + "UTC-03:00", + "UTC-02:00", + "UTC", + "UTC+01:00", + "UTC+02:00", + "UTC+06:00" + ], + "borders": [ + "IRL" + ], + "nativeName": "United Kingdom", + "numericCode": "826", + "flags": { + "svg": "https://flagcdn.com/gb.svg", + "png": "https://flagcdn.com/w320/gb.png" + }, + "currencies": [ + { + "code": "GBP", + "name": "British pound", + "symbol": "£" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Rouantelezh-Unanet", + "pt": "Reino Unido", + "nl": "Verenigd Koninkrijk", + "hr": "Ujedinjeno Kraljevstvo", + "fa": "بریتانیای کبیر و ایرلند شمالی", + "de": "Vereinigtes Königreich", + "es": "Reino Unido", + "fr": "Royaume-Uni", + "ja": "イギリス", + "it": "Regno Unito", + "hu": "Nagy-Britannia" + }, + "flag": "https://flagcdn.com/gb.svg", + "cioc": "GBR", + "independent": true + }, + { + "name": "United States of America", + "topLevelDomain": [ + ".us" + ], + "alpha2Code": "US", + "alpha3Code": "USA", + "callingCodes": [ + "1" + ], + "capital": "Washington, D.C.", + "altSpellings": [ + "US", + "USA", + "United States of America" + ], + "subregion": "Northern America", + "region": "Americas", + "population": 329484123, + "latlng": [ + 38.0, + -97.0 + ], + "demonym": "American", + "area": 9629091.0, + "gini": 41.4, + "timezones": [ + "UTC-12:00", + "UTC-11:00", + "UTC-10:00", + "UTC-09:00", + "UTC-08:00", + "UTC-07:00", + "UTC-06:00", + "UTC-05:00", + "UTC-04:00", + "UTC+10:00", + "UTC+12:00" + ], + "borders": [ + "CAN", + "MEX" + ], + "nativeName": "United States", + "numericCode": "840", + "flags": { + "svg": "https://flagcdn.com/us.svg", + "png": "https://flagcdn.com/w320/us.png" + }, + "currencies": [ + { + "code": "USD", + "name": "United States dollar", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Stadoù-Unanet", + "pt": "Estados Unidos", + "nl": "Verenigde Staten", + "hr": "Sjedinjene Američke Države", + "fa": "ایالات متحده آمریکا", + "de": "Vereinigte Staaten von Amerika", + "es": "Estados Unidos", + "fr": "États-Unis", + "ja": "アメリカ合衆国", + "it": "Stati Uniti D'America", + "hu": "Amerikai Egyesült Államok" + }, + "flag": "https://flagcdn.com/us.svg", + "regionalBlocs": [ + { + "acronym": "NAFTA", + "name": "North American Free Trade Agreement", + "otherNames": [ + "Tratado de Libre Comercio de América del Norte", + "Accord de Libre-échange Nord-Américain" + ] + } + ], + "cioc": "USA", + "independent": true + }, + { + "name": "Uruguay", + "topLevelDomain": [ + ".uy" + ], + "alpha2Code": "UY", + "alpha3Code": "URY", + "callingCodes": [ + "598" + ], + "capital": "Montevideo", + "altSpellings": [ + "UY", + "Oriental Republic of Uruguay", + "República Oriental del Uruguay" + ], + "subregion": "South America", + "region": "Americas", + "population": 3473727, + "latlng": [ + -33.0, + -56.0 + ], + "demonym": "Uruguayan", + "area": 181034.0, + "gini": 39.7, + "timezones": [ + "UTC-03:00" + ], + "borders": [ + "ARG", + "BRA" + ], + "nativeName": "Uruguay", + "numericCode": "858", + "flags": { + "svg": "https://flagcdn.com/uy.svg", + "png": "https://flagcdn.com/w320/uy.png" + }, + "currencies": [ + { + "code": "UYU", + "name": "Uruguayan peso", + "symbol": "$" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Uruguay", + "pt": "Uruguai", + "nl": "Uruguay", + "hr": "Urugvaj", + "fa": "اروگوئه", + "de": "Uruguay", + "es": "Uruguay", + "fr": "Uruguay", + "ja": "ウルグアイ", + "it": "Uruguay", + "hu": "Uruguay" + }, + "flag": "https://flagcdn.com/uy.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "URU", + "independent": true + }, + { + "name": "Uzbekistan", + "topLevelDomain": [ + ".uz" + ], + "alpha2Code": "UZ", + "alpha3Code": "UZB", + "callingCodes": [ + "998" + ], + "capital": "Tashkent", + "altSpellings": [ + "UZ", + "Republic of Uzbekistan", + "O‘zbekiston Respublikasi", + "Ўзбекистон Республикаси" + ], + "subregion": "Central Asia", + "region": "Asia", + "population": 34232050, + "latlng": [ + 41.0, + 64.0 + ], + "demonym": "Uzbekistani", + "area": 447400.0, + "gini": 35.3, + "timezones": [ + "UTC+05:00" + ], + "borders": [ + "AFG", + "KAZ", + "KGZ", + "TJK", + "TKM" + ], + "nativeName": "O‘zbekiston", + "numericCode": "860", + "flags": { + "svg": "https://flagcdn.com/uz.svg", + "png": "https://flagcdn.com/w320/uz.png" + }, + "currencies": [ + { + "code": "UZS", + "name": "Uzbekistani so'm", + "symbol": "so'm" + } + ], + "languages": [ + { + "iso639_1": "uz", + "iso639_2": "uzb", + "name": "Uzbek", + "nativeName": "Oʻzbek" + }, + { + "iso639_1": "ru", + "iso639_2": "rus", + "name": "Russian", + "nativeName": "Русский" + } + ], + "translations": { + "br": "Ouzbekistan", + "pt": "Usbequistão", + "nl": "Oezbekistan", + "hr": "Uzbekistan", + "fa": "ازبکستان", + "de": "Usbekistan", + "es": "Uzbekistán", + "fr": "Ouzbékistan", + "ja": "ウズベキスタン", + "it": "Uzbekistan", + "hu": "Üzbegisztán" + }, + "flag": "https://flagcdn.com/uz.svg", + "cioc": "UZB", + "independent": false + }, + { + "name": "Vanuatu", + "topLevelDomain": [ + ".vu" + ], + "alpha2Code": "VU", + "alpha3Code": "VUT", + "callingCodes": [ + "678" + ], + "capital": "Port Vila", + "altSpellings": [ + "VU", + "Republic of Vanuatu", + "Ripablik blong Vanuatu", + "République de Vanuatu" + ], + "subregion": "Melanesia", + "region": "Oceania", + "population": 307150, + "latlng": [ + -16.0, + 167.0 + ], + "demonym": "Ni-Vanuatu", + "area": 12189.0, + "gini": 37.6, + "timezones": [ + "UTC+11:00" + ], + "nativeName": "Vanuatu", + "numericCode": "548", + "flags": { + "svg": "https://flagcdn.com/vu.svg", + "png": "https://flagcdn.com/w320/vu.png" + }, + "currencies": [ + { + "code": "VUV", + "name": "Vanuatu vatu", + "symbol": "Vt" + } + ], + "languages": [ + { + "iso639_1": "bi", + "iso639_2": "bis", + "name": "Bislama", + "nativeName": "Bislama" + }, + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Vanuatu", + "pt": "Vanuatu", + "nl": "Vanuatu", + "hr": "Vanuatu", + "fa": "وانواتو", + "de": "Vanuatu", + "es": "Vanuatu", + "fr": "Vanuatu", + "ja": "バヌアツ", + "it": "Vanuatu", + "hu": "Vanuatu" + }, + "flag": "https://flagcdn.com/vu.svg", + "cioc": "VAN", + "independent": true + }, + { + "name": "Venezuela (Bolivarian Republic of)", + "topLevelDomain": [ + ".ve" + ], + "alpha2Code": "VE", + "alpha3Code": "VEN", + "callingCodes": [ + "58" + ], + "capital": "Caracas", + "altSpellings": [ + "VE", + "Bolivarian Republic of Venezuela", + "República Bolivariana de Venezuela" + ], + "subregion": "South America", + "region": "Americas", + "population": 28435943, + "latlng": [ + 8.0, + -66.0 + ], + "demonym": "Venezuelan", + "area": 916445.0, + "gini": 44.8, + "timezones": [ + "UTC-04:00" + ], + "borders": [ + "BRA", + "COL", + "GUY" + ], + "nativeName": "Venezuela", + "numericCode": "862", + "flags": { + "svg": "https://flagcdn.com/ve.svg", + "png": "https://flagcdn.com/w320/ve.png" + }, + "currencies": [ + { + "code": "VEF", + "name": "Venezuelan bolívar", + "symbol": "Bs S" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Venezuela", + "pt": "Venezuela", + "nl": "Venezuela", + "hr": "Venezuela", + "fa": "ونزوئلا", + "de": "Venezuela", + "es": "Venezuela", + "fr": "Venezuela", + "ja": "ベネズエラ・ボリバル共和国", + "it": "Venezuela", + "hu": "Venezuela" + }, + "flag": "https://flagcdn.com/ve.svg", + "regionalBlocs": [ + { + "acronym": "USAN", + "name": "Union of South American Nations", + "otherAcronyms": [ + "UNASUR", + "UNASUL", + "UZAN" + ], + "otherNames": [ + "Unión de Naciones Suramericanas", + "União de Nações Sul-Americanas", + "Unie van Zuid-Amerikaanse Naties", + "South American Union" + ] + } + ], + "cioc": "VEN", + "independent": true + }, + { + "name": "Vietnam", + "topLevelDomain": [ + ".vn" + ], + "alpha2Code": "VN", + "alpha3Code": "VNM", + "callingCodes": [ + "84" + ], + "capital": "Hanoi", + "altSpellings": [ + "VN", + "Socialist Republic of Vietnam", + "Cộng hòa Xã hội chủ nghĩa Việt Nam" + ], + "subregion": "South-Eastern Asia", + "region": "Asia", + "population": 97338583, + "latlng": [ + 16.16666666, + 107.83333333 + ], + "demonym": "Vietnamese", + "area": 331212.0, + "gini": 35.7, + "timezones": [ + "UTC+07:00" + ], + "borders": [ + "KHM", + "CHN", + "LAO" + ], + "nativeName": "Việt Nam", + "numericCode": "704", + "flags": { + "svg": "https://flagcdn.com/vn.svg", + "png": "https://flagcdn.com/w320/vn.png" + }, + "currencies": [ + { + "code": "VND", + "name": "Vietnamese đồng", + "symbol": "₫" + } + ], + "languages": [ + { + "iso639_1": "vi", + "iso639_2": "vie", + "name": "Vietnamese", + "nativeName": "Tiếng Việt" + } + ], + "translations": { + "br": "Viêt Nam", + "pt": "Vietname", + "nl": "Vietnam", + "hr": "Vijetnam", + "fa": "ویتنام", + "de": "Vietnam", + "es": "Vietnam", + "fr": "Viêt Nam", + "ja": "ベトナム", + "it": "Vietnam", + "hu": "Vietnám" + }, + "flag": "https://flagcdn.com/vn.svg", + "regionalBlocs": [ + { + "acronym": "ASEAN", + "name": "Association of Southeast Asian Nations" + } + ], + "cioc": "VIE", + "independent": true + }, + { + "name": "Wallis and Futuna", + "topLevelDomain": [ + ".wf" + ], + "alpha2Code": "WF", + "alpha3Code": "WLF", + "callingCodes": [ + "681" + ], + "capital": "Mata-Utu", + "altSpellings": [ + "WF", + "Territory of the Wallis and Futuna Islands", + "Territoire des îles Wallis et Futuna" + ], + "subregion": "Polynesia", + "region": "Oceania", + "population": 11750, + "latlng": [ + -13.3, + -176.2 + ], + "demonym": "Wallis and Futuna Islander", + "area": 142.0, + "timezones": [ + "UTC+12:00" + ], + "nativeName": "Wallis et Futuna", + "numericCode": "876", + "flags": { + "svg": "https://flagcdn.com/wf.svg", + "png": "https://flagcdn.com/w320/wf.png" + }, + "currencies": [ + { + "code": "XPF", + "name": "CFP franc", + "symbol": "Fr" + } + ], + "languages": [ + { + "iso639_1": "fr", + "iso639_2": "fra", + "name": "French", + "nativeName": "français" + } + ], + "translations": { + "br": "Wallis ha Futuna", + "pt": "Wallis e Futuna", + "nl": "Wallis en Futuna", + "hr": "Wallis i Fortuna", + "fa": "والیس و فوتونا", + "de": "Wallis und Futuna", + "es": "Wallis y Futuna", + "fr": "Wallis-et-Futuna", + "ja": "ウォリス・フツナ", + "it": "Wallis e Futuna", + "hu": "Wallis és Futuna" + }, + "flag": "https://flagcdn.com/wf.svg", + "independent": false + }, + { + "name": "Western Sahara", + "topLevelDomain": [ + ".eh" + ], + "alpha2Code": "EH", + "alpha3Code": "ESH", + "callingCodes": [ + "212" + ], + "capital": "El Aaiún", + "altSpellings": [ + "EH", + "Taneẓroft Tutrimt" + ], + "subregion": "Northern Africa", + "region": "Africa", + "population": 510713, + "latlng": [ + 24.5, + -13.0 + ], + "demonym": "Sahrawi", + "area": 266000.0, + "timezones": [ + "UTC+00:00" + ], + "borders": [ + "DZA", + "MRT", + "MAR" + ], + "nativeName": "الصحراء الغربية", + "numericCode": "732", + "flags": { + "svg": "https://flagcdn.com/eh.svg", + "png": "https://flagcdn.com/w320/eh.png" + }, + "currencies": [ + { + "code": "MAD", + "name": "Moroccan dirham", + "symbol": "د.م." + }, + { + "code": "DZD", + "name": "Algerian dinar", + "symbol": "د.ج" + } + ], + "languages": [ + { + "iso639_1": "es", + "iso639_2": "spa", + "name": "Spanish", + "nativeName": "Español" + } + ], + "translations": { + "br": "Sahara ar C'hornôg", + "pt": "Saara Ocidental", + "nl": "Westelijke Sahara", + "hr": "Zapadna Sahara", + "fa": "جمهوری دموکراتیک عربی صحرا", + "de": "Westsahara", + "es": "Sahara Occidental", + "fr": "Sahara Occidental", + "ja": "西サハラ", + "it": "Sahara Occidentale", + "hu": "Nyugat-Szahara" + }, + "flag": "https://flagcdn.com/eh.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "independent": false + }, + { + "name": "Yemen", + "topLevelDomain": [ + ".ye" + ], + "alpha2Code": "YE", + "alpha3Code": "YEM", + "callingCodes": [ + "967" + ], + "capital": "Sana'a", + "altSpellings": [ + "YE", + "Yemeni Republic", + "al-Jumhūriyyah al-Yamaniyyah" + ], + "subregion": "Western Asia", + "region": "Asia", + "population": 29825968, + "latlng": [ + 15.0, + 48.0 + ], + "demonym": "Yemeni", + "area": 527968.0, + "gini": 36.7, + "timezones": [ + "UTC+03:00" + ], + "borders": [ + "OMN", + "SAU" + ], + "nativeName": "اليَمَن", + "numericCode": "887", + "flags": { + "svg": "https://flagcdn.com/ye.svg", + "png": "https://flagcdn.com/w320/ye.png" + }, + "currencies": [ + { + "code": "YER", + "name": "Yemeni rial", + "symbol": "﷼" + } + ], + "languages": [ + { + "iso639_1": "ar", + "iso639_2": "ara", + "name": "Arabic", + "nativeName": "العربية" + } + ], + "translations": { + "br": "Yemen", + "pt": "Iémen", + "nl": "Jemen", + "hr": "Jemen", + "fa": "یمن", + "de": "Jemen", + "es": "Yemen", + "fr": "Yémen", + "ja": "イエメン", + "it": "Yemen", + "hu": "Jemen" + }, + "flag": "https://flagcdn.com/ye.svg", + "regionalBlocs": [ + { + "acronym": "AL", + "name": "Arab League", + "otherNames": [ + "جامعة الدول العربية", + "Jāmiʻat ad-Duwal al-ʻArabīyah", + "League of Arab States" + ] + } + ], + "cioc": "YEM", + "independent": true + }, + { + "name": "Zambia", + "topLevelDomain": [ + ".zm" + ], + "alpha2Code": "ZM", + "alpha3Code": "ZMB", + "callingCodes": [ + "260" + ], + "capital": "Lusaka", + "altSpellings": [ + "ZM", + "Republic of Zambia" + ], + "subregion": "Eastern Africa", + "region": "Africa", + "population": 18383956, + "latlng": [ + -15.0, + 30.0 + ], + "demonym": "Zambian", + "area": 752618.0, + "gini": 57.1, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "AGO", + "BWA", + "COD", + "MWI", + "MOZ", + "NAM", + "TZA", + "ZWE" + ], + "nativeName": "Zambia", + "numericCode": "894", + "flags": { + "svg": "https://flagcdn.com/zm.svg", + "png": "https://flagcdn.com/w320/zm.png" + }, + "currencies": [ + { + "code": "ZMW", + "name": "Zambian kwacha", + "symbol": "ZK" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + } + ], + "translations": { + "br": "Zambia", + "pt": "Zâmbia", + "nl": "Zambia", + "hr": "Zambija", + "fa": "زامبیا", + "de": "Sambia", + "es": "Zambia", + "fr": "Zambie", + "ja": "ザンビア", + "it": "Zambia", + "hu": "Zambia" + }, + "flag": "https://flagcdn.com/zm.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "ZAM", + "independent": true + }, + { + "name": "Zimbabwe", + "topLevelDomain": [ + ".zw" + ], + "alpha2Code": "ZW", + "alpha3Code": "ZWE", + "callingCodes": [ + "263" + ], + "capital": "Harare", + "altSpellings": [ + "ZW", + "Republic of Zimbabwe" + ], + "subregion": "Southern Africa", + "region": "Africa", + "population": 14862927, + "latlng": [ + -20.0, + 30.0 + ], + "demonym": "Zimbabwean", + "area": 390757.0, + "gini": 50.3, + "timezones": [ + "UTC+02:00" + ], + "borders": [ + "BWA", + "MOZ", + "ZAF", + "ZMB" + ], + "nativeName": "Zimbabwe", + "numericCode": "716", + "flags": { + "svg": "https://flagcdn.com/zw.svg", + "png": "https://flagcdn.com/w320/zw.png" + }, + "currencies": [ + { + "code": "ZMW", + "name": "Zambian kwacha", + "symbol": "K" + } + ], + "languages": [ + { + "iso639_1": "en", + "iso639_2": "eng", + "name": "English", + "nativeName": "English" + }, + { + "iso639_1": "sn", + "iso639_2": "sna", + "name": "Shona", + "nativeName": "chiShona" + }, + { + "iso639_1": "nd", + "iso639_2": "nde", + "name": "Northern Ndebele", + "nativeName": "isiNdebele" + } + ], + "translations": { + "br": "Zimbabwe", + "pt": "Zimbabué", + "nl": "Zimbabwe", + "hr": "Zimbabve", + "fa": "زیمباوه", + "de": "Simbabwe", + "es": "Zimbabue", + "fr": "Zimbabwe", + "ja": "ジンバブエ", + "it": "Zimbabwe", + "hu": "Zimbabwe" + }, + "flag": "https://flagcdn.com/zw.svg", + "regionalBlocs": [ + { + "acronym": "AU", + "name": "African Union", + "otherNames": [ + "الاتحاد الأفريقي", + "Union africaine", + "União Africana", + "Unión Africana", + "Umoja wa Afrika" + ] + } + ], + "cioc": "ZIM", + "independent": true + } +] \ No newline at end of file From b78270feb360e3eeae46cd46938c97254f86d918 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Sun, 9 Jul 2023 01:59:30 +0300 Subject: [PATCH 26/63] correction and minor fixes --- .../02_variables_builtin_functions.md | 2 +- 04_Day_Strings/04_strings.md | 16 ++-- 05_Day_Lists/05_lists.md | 4 +- 07_Day_Sets/07_sets.md | 10 +-- 10_Day_Loops/10_loops.md | 1 + .../17_exception_handling.md | 12 +-- .../18_regular_expressions.md | 83 ++++++++++--------- readme.md | 39 +++++---- 8 files changed, 84 insertions(+), 83 deletions(-) diff --git a/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md index d1927f2de..4646285e0 100644 --- a/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md +++ b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md @@ -63,7 +63,7 @@ Python Variable Name Rules - A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and \_ ) - Variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME) are different variables) -Let us se valid variable names +Here are some example of valid variable names: ```shell firstname diff --git a/04_Day_Strings/04_strings.md b/04_Day_Strings/04_strings.md index 699e7ca6c..5b5648ba0 100644 --- a/04_Day_Strings/04_strings.md +++ b/04_Day_Strings/04_strings.md @@ -102,10 +102,10 @@ Now, let us see the use of the above escape sequences with examples. ```py print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # line break print('Days\tTopics\tExercises') # adding tab space or 4 spaces -print('Day 1\t3\t5') -print('Day 2\t3\t5') -print('Day 3\t3\t5') -print('Day 4\t3\t5') +print('Day 1\t5\t5') +print('Day 2\t6\t20') +print('Day 3\t5\t23') +print('Day 4\t1\t35') print('This is a backslash symbol (\\)') # To write a backslash print('In every programming language it starts with \"Hello, World!\"') # to write a double quote inside a single quote @@ -328,16 +328,16 @@ print(challenge.expandtabs(10)) # 'thirty days of python' ```py challenge = 'thirty days of python' -print(challenge.find('y')) # 16 -print(challenge.find('th')) # 17 +print(challenge.find('y')) # 5 +print(challenge.find('th')) # 0 ``` - rfind(): Returns the index of the last occurrence of a substring, if not found returns -1 ```py challenge = 'thirty days of python' -print(challenge.rfind('y')) # 5 -print(challenge.rfind('th')) # 1 +print(challenge.rfind('y')) # 16 +print(challenge.rfind('th')) # 17 ``` - format(): formats string into a nicer output diff --git a/05_Day_Lists/05_lists.md b/05_Day_Lists/05_lists.md index b3fb49f6a..fea7f515c 100644 --- a/05_Day_Lists/05_lists.md +++ b/05_Day_Lists/05_lists.md @@ -163,7 +163,7 @@ print(second_last) # mango ### Unpacking List Items ```py -lst = ['item','item2','item3', 'item4', 'item5'] +lst = ['item1','item2','item3', 'item4', 'item5'] first_item, second_item, third_item, *rest = lst print(first_item) # item1 print(second_item) # item2 @@ -175,7 +175,7 @@ print(rest) # ['item4', 'item5'] ```py # First Example fruits = ['banana', 'orange', 'mango', 'lemon','lime','apple'] -first_fruit, second_fruit, third_fruit, *rest = lst +first_fruit, second_fruit, third_fruit, *rest = fruits print(first_fruit) # banana print(second_fruit) # orange print(third_fruit) # mango diff --git a/07_Day_Sets/07_sets.md b/07_Day_Sets/07_sets.md index d47a662a4..12bc2ca43 100644 --- a/07_Day_Sets/07_sets.md +++ b/07_Day_Sets/07_sets.md @@ -48,14 +48,12 @@ Set is a collection of items. Let me take you back to your elementary or high sc ### Creating a Set -We use curly brackets, {} to create a set or the *set()* built-in function. +We use the _set()_ built-in function. - Creating an empty set ```py # syntax -st = {} -# or st = set() ``` @@ -80,7 +78,7 @@ We use **len()** method to find the length of a set. ```py # syntax st = {'item1', 'item2', 'item3', 'item4'} -len(set) +len(st) ``` **Example:** @@ -131,7 +129,7 @@ fruits.add('lime') ``` - Add multiple items using _update()_ - The *update()* allows to add multiple items to a set. The *update()* takes a list argument. + The _update()_ allows to add multiple items to a set. The _update()_ takes a list argument. ```py # syntax @@ -174,7 +172,6 @@ fruits = {'banana', 'orange', 'mango', 'lemon'} removed_item = fruits.pop() ``` - ### Clearing Items in a Set If we want to clear or empty the set we use _clear_ method. @@ -427,7 +424,6 @@ age = [22, 19, 24, 25, 26, 24, 25, 24] 1. Explain the difference between the following data types: string, list, tuple and set 2. _I am a teacher and I love to inspire and teach people._ How many unique words have been used in the sentence? Use the split methods and set to get the unique words. - 🎉 CONGRATULATIONS ! 🎉 [<< Day 6](../06_Day_Tuples/06_tuples.md) | [Day 8 >>](../08_Day_Dictionaries/08_dictionaries.md) diff --git a/10_Day_Loops/10_loops.md b/10_Day_Loops/10_loops.md index e80a392d6..f03265a98 100644 --- a/10_Day_Loops/10_loops.md +++ b/10_Day_Loops/10_loops.md @@ -127,6 +127,7 @@ while condition: count = 0 while count < 5: if count == 3: + count = count + 1 continue print(count) count = count + 1 diff --git a/17_Day_Exception_handling/17_exception_handling.md b/17_Day_Exception_handling/17_exception_handling.md index b9378ed9d..b9d533509 100644 --- a/17_Day_Exception_handling/17_exception_handling.md +++ b/17_Day_Exception_handling/17_exception_handling.md @@ -16,6 +16,7 @@ [<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + - [📘 Day 17](#-day-17) - [Exception Handling](#exception-handling) - [Packing and Unpacking Arguments in Python](#packing-and-unpacking-arguments-in-python) @@ -128,6 +129,7 @@ I alway run. ``` It is also shorten the above code as follows: + ```py try: name = input('Enter your name:') @@ -223,9 +225,9 @@ print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28 def packing_person_info(**kwargs): # check the type of kwargs and it is a dict type # print(type(kwargs)) - # Printing dictionary items + # Printing dictionary items for key in kwargs: - print("{key} = {kwargs[key]}") + print(f"{key} = {kwargs[key]}") return kwargs print(packing_person_info(name="Asabeneh", @@ -247,7 +249,7 @@ Like in JavaScript, spreading is possible in Python. Let us check it in an examp ```py lst_one = [1, 2, 3] lst_two = [4, 5, 6, 7] -lst = [0, *list_one, *list_two] +lst = [0, *lst_one, *lst_two] print(lst) # [0, 1, 2, 3, 4, 5, 6, 7] country_lst_one = ['Finland', 'Sweden', 'Norway'] country_lst_two = ['Denmark', 'Iceland'] @@ -257,7 +259,7 @@ print(nordic_countries) # ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] ## Enumerate -If we are interested in an index of a list, we use *enumerate* built-in function to get the index of each item in the list. +If we are interested in an index of a list, we use _enumerate_ built-in function to get the index of each item in the list. ```py for index, item in enumerate([20, 30, 40]): @@ -301,4 +303,4 @@ print(fruits_and_veges) 🎉 CONGRATULATIONS ! 🎉 -[<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md) \ No newline at end of file +[<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md) diff --git a/18_Day_Regular_expressions/18_regular_expressions.md b/18_Day_Regular_expressions/18_regular_expressions.md index f8366d26c..4492c91b9 100644 --- a/18_Day_Regular_expressions/18_regular_expressions.md +++ b/18_Day_Regular_expressions/18_regular_expressions.md @@ -59,11 +59,11 @@ import re To find a pattern we use different set of *re* character sets that allows to search for a match in a string. -* *re.match()*: searches only in the beginning of the first line of the string and returns matched objects if found, else returns None. -* *re.search*: Returns a match object if there is one anywhere in the string, including multiline strings. -* *re.findall*: Returns a list containing all matches -* *re.split*: Takes a string, splits it at the match points, returns a list -* *re.sub*: Replaces one or many matches within a string +- *re.match()*: searches only in the beginning of the first line of the string and returns matched objects if found, else returns None. +- *re.search*: Returns a match object if there is one anywhere in the string, including multiline strings. +- *re.findall*: Returns a list containing all matches +- *re.split*: Takes a string, splits it at the match points, returns a list +- *re.sub*: Replaces one or many matches within a string #### Match @@ -129,7 +129,7 @@ substring = txt[start:end] print(substring) # first ``` -As you can see, search is much better than match because it can look for the pattern throughout the text. Search returns a match object with a first match that was found, otherwise it returns _None_. A much better *re* function is *findall*. This function checks for the pattern through the whole string and returns all the matches as a list. +As you can see, search is much better than match because it can look for the pattern throughout the text. Search returns a match object with a first match that was found, otherwise it returns *None*. A much better *re* function is *findall*. This function checks for the pattern through the whole string and returns all the matches as a list. #### Searching for All Matches Using *findall* @@ -240,38 +240,39 @@ matches = re.findall(regex_pattern, txt) print(matches) # ['Apple', 'apple'] ``` + * []: A set of characters - * [a-c] means, a or b or c - * [a-z] means, any letter from a to z - * [A-Z] means, any character from A to Z - * [0-3] means, 0 or 1 or 2 or 3 - * [0-9] means any number from 0 to 9 - * [A-Za-z0-9] any single character, that is a to z, A to Z or 0 to 9 -* \\: uses to escape special characters - * \d means: match where the string contains digits (numbers from 0-9) - * \D means: match where the string does not contain digits -* . : any character except new line character(\n) -* ^: starts with - * r'^substring' eg r'^love', a sentence that starts with a word love - * r'[^abc] means not a, not b, not c. -* $: ends with - * r'substring$' eg r'love$', sentence that ends with a word love -* *: zero or more times - * r'[a]*' means a optional or it can occur many times. -* +: one or more times - * r'[a]+' means at least once (or more) -* ?: zero or one time - * r'[a]?' means zero times or once -* {3}: Exactly 3 characters -* {3,}: At least 3 characters -* {3,8}: 3 to 8 characters -* |: Either or - * r'apple|banana' means either apple or a banana -* (): Capture and group + - [a-c] means, a or b or c + - [a-z] means, any letter from a to z + - [A-Z] means, any character from A to Z + - [0-3] means, 0 or 1 or 2 or 3 + - [0-9] means any number from 0 to 9 + - [A-Za-z0-9] any single character, that is a to z, A to Z or 0 to 9 +- \\: uses to escape special characters + - \d means: match where the string contains digits (numbers from 0-9) + - \D means: match where the string does not contain digits +- . : any character except new line character(\n) +- ^: starts with + - r'^substring' eg r'^love', a sentence that starts with a word love + - r'[^abc] means not a, not b, not c. +- $: ends with + - r'substring$' eg r'love$', sentence that ends with a word love +- *: zero or more times + - r'[a]*' means a optional or it can occur many times. +- +: one or more times + - r'[a]+' means at least once (or more) +- ?: zero or one time + - r'[a]?' means zero times or once +- {3}: Exactly 3 characters +- {3,}: At least 3 characters +- {3,8}: 3 to 8 characters +- |: Either or + - r'apple|banana' means either apple or a banana +- (): Capture and group ![Regular Expression cheat sheet](../images/regex.png) -Let us use examples to clarify the meta characters above +Let us use examples to clarify the meta characters above ### Square Bracket @@ -367,7 +368,7 @@ print(matches) # ['6', '2019', '8', '2021'] ### Cart ^ -* Starts with +- Starts with ```py txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' @@ -376,7 +377,7 @@ matches = re.findall(regex_pattern, txt) print(matches) # ['This'] ``` -* Negation +- Negation ```py txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' @@ -388,7 +389,9 @@ print(matches) # ['6,', '2019', '8', '2021'] ## 💻 Exercises: Day 18 ### Exercises: Level 1 + 1. What is the most frequent word in the following paragraph? + ```py paragraph = 'I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love. ``` @@ -423,9 +426,9 @@ print(matches) # ['6,', '2019', '8', '2021'] 2. The position of some particles on the horizontal x-axis are -12, -4, -3 and -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction. Extract these numbers from this whole text and find the distance between the two furthest particles. ```py -points = ['-1', '2', '-4', '-3', '-1', '0', '4', '8'] -sorted_points = [-4, -3, -1, -1, 0, 2, 4, 8] -distance = 8 -(-4) # 12 +points = ['-12', '-4', '-3', '-1', '0', '4', '8'] +sorted_points = [-12, -4, -3, -1, -1, 0, 2, 4, 8] +distance = 8 -(-12) # 20 ``` ### Exercises: Level 2 @@ -453,4 +456,4 @@ distance = 8 -(-4) # 12 🎉 CONGRATULATIONS ! 🎉 -[<< Day 17](../17_Day_Exception_handling/17_exception_handling.md) | [Day 19>>](../19_Day_File_handling/19_file_handling.md) \ No newline at end of file +[<< Day 17](../17_Day_Exception_handling/17_exception_handling.md) | [Day 19>>](../19_Day_File_handling/19_file_handling.md) diff --git a/readme.md b/readme.md index 8af2c85ee..5bd0eb887 100644 --- a/readme.md +++ b/readme.md @@ -1,4 +1,4 @@ -# 🐍 30 Days Of Python +# 🐍 30 Days Of Python |# Day | Topics | |------|:---------------------------------------------------------:| @@ -15,11 +15,11 @@ | 11 | [Functions](./11_Day_Functions/11_functions.md)| | 12 | [Modules](./12_Day_Modules/12_modules.md)| | 13 | [List Comprehension](./13_Day_List_comprehension/13_list_comprehension.md)| -| 14 | [Higher Order Functions](./14_Day_Higher_order_functions/14_higher_order_functions.md)| -| 15 | [Python Type Errors](./15_Day_Python_type_errors/15_python_type_errors.md)| -| 16 | [Python Date time](./16_Day_Python_date_time/16_python_datetime.md) | -| 17 | [Exception Handling](./17_Day_Exception_handling/17_exception_handling.md)| -| 18 | [Regular Expressions](./18_Day_Regular_expressions/18_regular_expressions.md)| +| 14 | [Higher Order Functions](./14_Day_Higher_order_functions/14_higher_order_functions.md)| +| 15 | [Python Type Errors](./15_Day_Python_type_errors/15_python_type_errors.md)| +| 16 | [Python Date time](./16_Day_Python_date_time/16_python_datetime.md) | +| 17 | [Exception Handling](./17_Day_Exception_handling/17_exception_handling.md)| +| 18 | [Regular Expressions](./18_Day_Regular_expressions/18_regular_expressions.md)| | 19 | [File Handling](./19_Day_File_handling/19_file_handling.md)| | 20 | [Python Package Manager](./20_Day_Python_package_manager/20_python_package_manager.md)| | 21 | [Classes and Objects](./21_Day_Classes_and_objects/21_classes_and_objects.md)| @@ -55,7 +55,6 @@
- [Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) ![30DaysOfPython](./images/30DaysOfPython_banner3@2x.png) @@ -99,11 +98,11 @@ If you would like to actively engage in the challenge, you may join the [30DaysO ## Introduction -Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of Python programming language was derived from a British sketch comedy series, *Month Python's Flying Circus*. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, many hands on exercises and projects. +Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of Python programming language was derived from a British sketch comedy series, _Monty Python's Flying Circus_. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, many hands on exercises and projects. This challenge is designed for beginners and professionals who want to learn python programming language. It may take 30 to 100 days to complete the challenge, people who actively participate on the telegram group have a high probability of completing the challenge. -This challenge is easy to read, written in conversational English, engaging, motivating and at the same time, it is very demanding. You need to allocate much time to finish this challenge. If you are a visual learner, you may get the video lesson on Washera YouTube channel. You may start from [Python for Absolute Beginners video](https://youtu.be/OCCWZheOesI). Subscribe the channel, comment and ask questions on YouTube vidoes and be proactive, the author will eventually notice you. +This challenge is easy to read, written in conversational English, engaging, motivating and at the same time, it is very demanding. You need to allocate much time to finish this challenge. If you are a visual learner, you may get the video lesson on Washera YouTube channel. You may start from [Python for Absolute Beginners video](https://youtu.be/OCCWZheOesI). Subscribe the channel, comment and ask questions on YouTube vidoes and be proactive, the author will eventually notice you. The author likes to hear your opinion about the challenge, share the author by expressing your thoughts about the 30DaysOfPython challenge. You can leave your testimonial on this [link](https://testimonial-vdzd.onrender.com/) @@ -166,11 +165,11 @@ Python will give you results if you write scripts that Python understands, if no As you can see from the returned error, Python is so clever that it knows the mistake we made and which was _Syntax Error: invalid syntax_. Using x as multiplication in Python is a syntax error because (x) is not a valid syntax in Python. Instead of (**x**) we use asterisk (*) for multiplication. The returned error clearly shows what to fix. -The process of identifying and removing errors from a program is called *debugging*. Let us debug it by putting * in place of **x**. +The process of identifying and removing errors from a program is called _debugging_. Let us debug it by putting * in place of **x**. ![Fixing Syntax Error](./images/fixing_syntax_error.png) -Our bug was fixed, the code ran and we got a result we were expecting. As a programmer you will see such kind of errors on daily basis. It is good to know how to debug. To be good at debugging you should understand what kind of errors you are facing. Some of the Python errors you may encounter are *SyntaxError*, *IndexError*, *NameError*, *ModuleNotFoundError*, *KeyError*, *ImportError*, *AttributeError*, *TypeError*, *ValueError*, *ZeroDivisionError* etc. We will see more about different Python **_error types_** in later sections. +Our bug was fixed, the code ran and we got a result we were expecting. As a programmer you will see such kind of errors on daily basis. It is good to know how to debug. To be good at debugging you should understand what kind of errors you are facing. Some of the Python errors you may encounter are _SyntaxError_, _IndexError_, _NameError_, _ModuleNotFoundError_, _KeyError_, _ImportError_, _AttributeError_, _TypeError_, _ValueError_, _ZeroDivisionError_ etc. We will see more about different Python **_error types_** in later sections. Let us practice more how to use Python interactive shell. Go to your terminal or command prompt and write the word **python**. @@ -180,11 +179,11 @@ The Python interactive shell is opened. Let us do some basic mathematical operat Let us do some maths first before we write any Python code: -- 2 + 3 = 5 -- 3 - 2 = 1 -- 3 \* 2 = 6 -- 3 / 2 = 1.5 -- 3 ^ 2 = 3 x 3 = 9 +- 2 + 3 is 5 +- 3 - 2 is 1 +- 3 \* 2 is 6 +- 3 / 2 is 1.5 +- 3 ** 2 is the same as 3 * 3 In python we have the following additional operations: @@ -330,7 +329,7 @@ Python list is an ordered collection which allows to store different data type i #### Dictionary -A Python dictionary object is an unordered collection of data in a key value pair format. +A Python dictionary object is an unordered collection of data in a key value pair format. **Example:** @@ -382,7 +381,7 @@ To check the data type of certain data/variable we use the **type** function. In First open your project folder, 30DaysOfPython. If you don't have this folder, create a folder name called 30DaysOfPython. Inside this folder, create a file called helloworld.py. Now, let's do what we did on python interactive shell using visual studio code. -The Python interactive shell was printing without using **print** but on visual studio code to see our result we should use a built in function *print(). The *print()* built-in function takes one or more arguments as follows *print('arument1', 'argument2', 'argument3')*. See the examples below. +The Python interactive shell was printing without using **print** but on visual studio code to see our result we should use a built in function _print(). The _print()_ built-in function takes one or more arguments as follows _print('arument1', 'argument2', 'argument3')_. See the examples below. **Example:** @@ -410,7 +409,7 @@ print(type({9.8, 3.14, 2.7})) # Set print(type((9.8, 3.14, 2.7))) # Tuple ``` -To run the python file check the image below. You can run the python file either by running the green button on Visual Studio Code or by typing *python helloworld.py* in the terminal . +To run the python file check the image below. You can run the python file either by running the green button on Visual Studio Code or by typing _python helloworld.py_ in the terminal . ![Running python script](./images/running_python_script.png) @@ -455,4 +454,4 @@ To run the python file check the image below. You can run the python file either 🎉 CONGRATULATIONS ! 🎉 -[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) \ No newline at end of file +[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) From 113018c7c353d0493748d891807b2cff8f1c4186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Fri, 5 Jul 2024 16:45:07 -0300 Subject: [PATCH 27/63] Creating a Portuguese translation session --- Portuguese/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 Portuguese/README.md diff --git a/Portuguese/README.md b/Portuguese/README.md new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/Portuguese/README.md @@ -0,0 +1 @@ + From a41e03829ecb194044e8ffe06b9ac03ab7d8e0e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Fri, 5 Jul 2024 19:17:35 -0300 Subject: [PATCH 28/63] Translating into Portuguese Day #1 --- Portuguese/README.md | 455 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 455 insertions(+) diff --git a/Portuguese/README.md b/Portuguese/README.md index 8b1378917..d6c3f0338 100644 --- a/Portuguese/README.md +++ b/Portuguese/README.md @@ -1 +1,456 @@ +# 🐍 30 Dias de python +|# Day | Topics | +|------|:---------------------------------------------------------:| +| 01 | [Introdução](./readme.md)| +| 02 | [Variaveis, Built-in Functions](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| +| 03 | [Operadores](./03_Day_Operators/03_operators.md)| +| 04 | [Strings](./04_Day_Strings/04_strings.md)| +| 05 | [Listas](./05_Day_Lists/05_lists.md)| +| 06 | [Tuplas](./06_Day_Tuples/06_tuples.md)| +| 07 | [Conjuntos](./07_Day_Sets/07_sets.md)| +| 08 | [Dicionários](./08_Day_Dictionaries/08_dictionaries.md)| +| 09 | [Condicionais](./09_Day_Conditionals/09_conditionals.md)| +| 10 | [Loops](./10_Day_Loops/10_loops.md)| +| 11 | [Funções](./11_Day_Functions/11_functions.md)| +| 12 | [Modulos](./12_Day_Modules/12_modules.md)| +| 13 | [Compreensão de Listas](./13_Day_List_comprehension/13_list_comprehension.md)| +| 14 | [Higher Order Functions](./14_Day_Higher_order_functions/14_higher_order_functions.md)| +| 15 | [Tripos de Erros](./15_Day_Python_type_errors/15_python_type_errors.md)| +| 16 | [Python Date time](./16_Day_Python_date_time/16_python_datetime.md) | +| 17 | [Manipulação de Excessão](./17_Day_Exception_handling/17_exception_handling.md)| +| 18 | [Regex (Expressões Regulares)](./18_Day_Regular_expressions/18_regular_expressions.md)| +| 19 | [Manipulação De Arquivos](./19_Day_File_handling/19_file_handling.md)| +| 20 | [Gerenciador De Pacotes](./20_Day_Python_package_manager/20_python_package_manager.md)| +| 21 | [Classes e Objetos](./21_Day_Classes_and_objects/21_classes_and_objects.md)| +| 22 | [Web Scraping](./22_Day_Web_scraping/22_web_scraping.md)| +| 23 | [Ambiente Virtual](./23_Day_Virtual_environment/23_virtual_environment.md)| +| 24 | [Estatisticas](./24_Day_Statistics/24_statistics.md)| +| 25 | [Pandas](./25_Day_Pandas/25_pandas.md)| +| 26 | [Python web](./26_Day_Python_web/26_python_web.md)| +| 27 | [Python com MongoDB](./27_Day_Python_with_mongodb/27_python_with_mongodb.md)| +| 28 | [API](./28_Day_API/28_API.md)| +| 29 | [Construindo API's](./29_Day_Building_API/29_building_API.md)| +| 30 | [Conclusão](./30_Day_Conclusions/30_conclusions.md)| + +🧡🧡🧡 CODANDO FELIZ 🧡🧡🧡 + +
+Ajudem o autor a criar mais materiais educacionais
+Paypal Logo +
+ +
+

30 Dias De Python: Dia 1 - Introdução

+ + + + + Twitter Follow + + + Autor: + Asabeneh Yetayeh
+ Segunda Edição: July, 2021 +
+
+ +[Dia 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) + +![30DaysOfPython](.././images/30DaysOfPython_banner3@2x.png) + +- [🐍 30 Dias De Python](#-30-dias-de-python) +- [📘 Dia 1](#Dia-1) + - [Bem Vindo](#welcome) + - [Introdução](#introdução) + - [Por quê Python ?](#Por-quê-python) + - [Setup do ambiente](#Setup-do-ambiente) + - [Instalando o Python](#instalando-o-python) + - [Python Shell](#python-shell) + - [Instalando o Visual Studio Code](#instalando-o-visual-studio-code) + - [Como usar o visual studio code](#como-usar-o-visual-studio-code) + - [Basico de Python](#basico-de-python) + - [Sintaxe do Python](#Sintaxe-do-python) + - [Indentação do Python](#indentaçao-do-python) + - [Comentários](#comentarios) + - [Tipos de dados](#tipos-de-dados) + - [Numeros](#numeros) + - [Strings](#strings) + - [Booleanos](#booleanos) + - [Listas](#listas) + - [Dicionários](#dicionarios) + - [Tuplas](#tupla) + - [Set](#set) + - [Checando tipos de dados](#checando-tipos-de-dados) + - [Arquivo Python](#arquivo-python) + - [💻 Exercicios - Dia 1](#-exercicios-dia-1) + - [Exercicio: Level 1](#exercicio-level-1) + - [Exercicio: Level 2](#exercicio-level-2) + - [Exercicio: Level 3](#exercicio-level-3) + +# 📘 Dia 1 + +## Bem Vindo! + +**Parabéns** por decidir participar do desafio de programação _30 dias de Python_ . E nesse desafio você vai aprender tudo o que você precisa para se tornar um programador python e todo o conceito de programação. No final do desafio você receberá o certificado do desafio de programação _30DiasDePython_. + +Se você quiser se envolver ativamente no desafio, você pode se juntar ao grupo do telegram [30DaysOfPython challenge](https://t.me/ThirtyDaysOfPython). + +## Introdução + +Python é uma linguagem de programação de alto nível para programação de uso geral. É uma linguagem de programação de código aberto, interpretada e orientada a objetos. Python foi criado por um programador holandês, Guido van Rossum. O nome da linguagem de programação Python foi derivado de uma série de comédia britânica, _Monty Python's Flying Circus_. A primeira versão foi lançada em 20 de fevereiro de 1991. Este desafio de 30 dias de Python irá ajudá-lo a aprender a versão mais recente do Python, Python 3, passo a passo. Os tópicos são divididos em 30 dias, onde cada dia contém diversos tópicos com explicações fáceis de entender, exemplos do mundo real, muitos exercícios práticos e projetos. + +Este desafio foi desenvolvido para iniciantes e profissionais que desejam aprender a linguagem de programação python. Pode levar de 30 a 100 dias para completar o desafio, as pessoas que participam ativamente do grupo de telegramas têm grande probabilidade de completar o desafio. + +Este desafio é fácil de ler, escrito originalmente em inglês coloquial e traduzido para um português, envolvente, motivador e ao mesmo tempo muito exigente. Você precisa destinar muito tempo para terminar este desafio. Se você é um dos que aprendem melhor vendo, você pode assistir às vídeo-aulas em +Canal do Youtube do Washera Você pode começar pelo [Video de Python para iniciantes absolutos](https://youtu.be/OCCWZheOesI). Se inscreva no canal, comente suas dúvidas nos vídeos do YouTube e seja proativo, o autor eventualmente notará você. + +O autor gosta de ouvir sua opinião sobre o desafio, compartilhe o artigo do autor dando um feedback com sua opinião sobre o desafio 30DiasDePython. E você pode deixar seu feedback sobre o artigo em: [link](https://testimonial-vdzd.onrender.com/) + +## Por quê Python? + +É uma linguagem de programação muito próxima da linguagem humana, com uma sintaxe simples! e por isso fácil de aprender e usar. +Python é usado por vários setores e empresas (incluindo o Google). Ele tem sido usado para desenvolver aplicações web, aplicativos de desktop, administração de sistemas e bibliotecas de machine learning. Python é uma linguagem altamente adotada na comunidade de data science e machine learning. Espero que isso seja suficiente para convencê-lo a começar a aprender Python. + +## Setup do ambiente + +### Instalando o Python +Para executar um script escrito em Python, você precisa instalar o Python. Vamos para a página [download](https://www.python.org/) python. +Se você for um usuario de windows. Clique no botão circulado em vermelho. + +[![instalando no Windows](.././images/installing_on_windows.png)](https://www.python.org/) + +Se você for um usuário de MacOs. Clique no botão circulado em vermelho. + +[![instalando no MacOs](.././images/installing_on_macOS.png)](https://www.python.org/) + +Para verificar se o python está instalado, digite o seguinte comando no terminal do seu dispositivo. +```shell +python --version +``` + +![Versão do Python](.././images/python_versio.png) + +Como você pode ver no terminal, estou usando a versão _Python 3.7.5_ no momento. Sua versão do Python pode ser diferente da minha, mas deve ser 3.6 ou superior. Se você conseguir ver a versão python, muito bem. Python foi instalado em sua máquina. Continue para a próxima seção. + +### Python Shell + +Python é uma linguagem de script interpretada, portanto não precisa ser compilada. Isso significa que executa o código linha por linha. O Python vem com um _Python Shell (Shell Interativo do Python)_, também conhecido como REPL (Read Eval Print Loop). E é usado para executar um único comando python e obter o resultado. + +O Python Shell aguarda o código Python do usuário. Ao inserir o código, ele o interpreta e mostra o resultado na próxima linha. +Abra seu terminal ou prompt de comando (cmd) e escreva: + +```shell +python +``` + +![Python Scripting Shell](.././images/opening_python_shell.png) + +O shell interativo do Python é aberto e aguarda que você escreva o código em Python (script Python). E você escreverá seu script Python próximo a este símbolo >>> e clique em Enter. +Vamos escrever nosso primeiro scripts no shell de script Python. + +![Python script on Python shell](.././images/adding_on_python_shell.png) + +Muito bem, você escreveu seu primeiro script Python no shell interativo Python. Como fechamos o shell interativo do Python? +Para fechar o shell, próximo a este símbolo >> escreva o comando **exit()** e pressione Enter. + +![Exit from python shell](.././images/exit_from_shell.png) + +Agora você sabe como abrir o shell interativo do Python e como sair dele. + +Python fornecerá resultados se você escrever scripts que Python entenda; caso contrário, retornará erros. Vamos cometer um erro proposital e ver o que o Python retornará. + +![Invalid Syntax Error](.././images/invalid_syntax_error.png) + +Como você pode ver no erro retornado, Python é tão inteligente que sabe o erro que cometemos e que foi _Syntax Error: Invalid Syntax_. Usar x como multiplicação em Python é um erro de sintaxe porque (x) não é uma sintaxe válida em Python. Em vez de (**x**) usamos asterisco (*) para multiplicação. O erro retornado mostra claramente o que corrigir. + +O processo de identificação e remoção de erros de um programa é chamado de _depuração_. Vamos depurá-lo colocando * no lugar de **x**. + +![Fixing Syntax Error](.././images/fixing_syntax_error.png) + +Nosso bug foi corrigido, o código foi executado e obtivemos o resultado que esperávamos. Como programador, você verá esse tipo de erro diariamente. É bom saber como depurar. Para ser bom em depuração, você deve entender que tipo de erros está enfrentando. Alguns dos erros do Python que você pode encontrar são _SyntaxError_, _IndexError_, _NameError_, _ModuleNotFoundError_, _KeyError_, _ImportError_, _AttributeError_, _TypeError_, _ValueError_, _ZeroDivisionError_ etc. Veremos mais sobre diferentes tipos de erros no Python mais tarde, em outras seções! + +Vamos praticar mais como usar o shell interativo Python. Vá para o seu terminal ou prompt de comando e escreva a palavra **python**. + +![Python Scripting Shell](.././images/opening_python_shell.png) + +O shell interativo do Python é aberto. Vamos fazer algumas operações matemáticas básicas (adição, subtração, multiplicação, divisão, módulo, exponencial). + +Vamos fazer algumas contas antes de escrever qualquer código Python: + +- 2 + 3 is 5 +- 3 - 2 is 1 +- 3 \* 2 is 6 +- 3 / 2 is 1.5 +- 3 ** 2 is the same as 3 * 3 + +Em python temos as seguintes operações adicionais: + +- 3 % 2 = 1 => que significa encontrar o resto ou (módulo da divisão) +- 3 // 2 = 1 => que significa remover o resto da divisão + +Vamos mudar as expressões matemáticas acima para código Python. O shell Python foi aberto e vamos escrever um comentário logo no início do shell. + +Um _comentário_ é uma parte do código que não é executada por python o comentário é ignorado pelo interpretador Python. Portanto, podemos deixar algum texto em nosso código para torná-lo mais legível. Python não executa a parte de comentários. Um comentário em python começa com o símbolo hash(#). +É assim que você escreve um comentário em python: + +```shell + # comment starts with hash + # this is a python comment, because it starts with a (#) symbol +``` + +![Maths on python shell](.././images/maths_on_python_shell.png) + +Antes de passarmos para a próxima seção, vamos praticar mais no shell interativo do Python. Feche o shell aberto escrevendo _exit()_ no shell e abra-o novamente e vamos praticar como escrever um texto no shell Python. + +![Writing String on python shell](.././images/writing_string_on_shell.png) + +### Instalando o Visual Studio Code + +O shell interativo Python é bom para testar pequenos códigos de script, mas não será para um grande projeto. No ambiente de trabalho real, os desenvolvedores usam diferentes editores de código para escrever códigos. Neste desafio de programação de 30 dias De Python usaremos código do visual studio. O Visual Studio Code é um editor de texto de código aberto muito popular. Sou fã do vscode e recomendo [download](https://code.visualstudio.com/) visual studio code, mas se você é a adépito a outros editores, fique à vontade para seguir com o que tiver. + +[![Visual Studio Code](.././images/vscode.png)](https://code.visualstudio.com/) + +Se você instalou o Visual Studio Code, vamos ver como usá-lo. +Se preferir um vídeo, você pode seguir este tutorial da instalação e configuração do Visual Studio Code para Python [Video tutorial](https://www.youtube.com/watch?v=bn7Cx4z-vSo) + +#### Como usar o Visual Studio Code + +Abra o visual studio code clicando duas vezes no ícone do visual studio. Ao abri-lo, você obterá esse tipo de interface. Tente interagir com os ícones rotulados. + +![Visual studio Code](.././images/vscode_ui.png) + +Crie uma pasta chamada 30DiasDePython no seu desktop. Em seguida, abra-a usando o visual studio code. + +![Opening Project on Visual studio](.././images/how_to_open_project_on_vscode.png) + +![Opening a project](.././images/opening_project.png) + +Após abri-lo você verá atalhos para criação de arquivos e pastas dentro do diretório do projeto 30DiasDePython. Como você pode ver abaixo, criei o primeiro arquivo, helloworld.py. Você pode fazer o mesmo. + +![Creating a python file](.././images/helloworld.png) + +Depois de um longo dia codando, você deseja fechar seu editor de código fonte, certo? É assim que você fechará o projeto aberto. + +![Closing project](.././images/closing_opened_project.png) + +Parabéns, você concluiu a configuração do ambiente de desenvolvimento. Vamos começar a codar. + +## Basico de Python + +### Sintaxe do Python + +Um script Python pode ser escrito no shell interativo Python ou no editor de código. Um arquivo Python possui uma extensão .py. + +### Identação do Python + +Uma identação é um espaço em branco em um texto. A identação em muitas linguagens é usada para aumentar a legibilidade do código, mas o Python usa a identação para criar blocos de códigos. Em outras linguagens de programação, chaves são usadas para criar blocos de códigos em vez de a identação. Um dos bugs comuns ao escrever código um python é o erro de identação. + +![Indentation Error](.././images/indentation.png) + +### Comentários + +Os comentários são muito importantes para tornar o código mais legível e para deixar comentários em nosso código. Python não executa partes de comentários do nosso código. +Qualquer texto que comece com hash(#) em Python é um comentário. + +**Exemplo: de um comentário de uma linha** + +```shell + # This is the first comment + # This is the second comment + # Python is eating the world +``` + +**Exemplo: de um Comentário de multiplas linhas conhecido como docstring** + +Aspas triplas podem ser usadas para comentários de múltiplas linhas se não estiverem atribuídas a uma variável + +```shell +"""This is multiline comment +multiline comment takes multiple lines. +python is eating the world +""" +``` + +### Tipos de dados + +Em Python existem vários tipos de dados. Vamos começar com os mais comuns. Diferentes tipos de dados serão abordados em detalhes em outras seções. Por enquanto, vamos examinar os diferentes tipos de dados e nos familiarizar com eles. Você não precisa ter um entendimento claro agora. + +#### Números + +- Inteiro: É considerado Inteiro(números negativos, zero e positivos) + Exemplo: + ... -3, -2, -1, 0, 1, 2, 3 ... +- Float: Números decimais + Exemplo: + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... +- Complexos + Exemplo: + 1 + j, 2 + 4j + +#### Strings + +Uma coleção de um ou mais caracteres entre aspas simples ou duplas são considerados strings. Se uma string tiver mais de uma frase, usamos aspas triplas. + +**Exemplo:** + +```py +'Asabeneh' +'Finland' +'Python' +'I love teaching' +'I hope you are enjoying the first day of 30DaysOfPython Challenge' +``` + +#### Booleanos + +Um tipo de dado booleano é um valor True ou False. T e F devem estar sempre maiúsculos. + +**Exemplo:** + +```python + True # Is the light on? If it is on, then the value is True + False # Is the light on? If it is off, then the value is False +``` + +#### Listas + +A lista em Python é uma coleção ordenada que permite armazenar itens de diferentes tipos de dados. Uma lista é semelhante a um array em JavaScript. + +**Exemplo:** + +```py +[0, 1, 2, 3, 4, 5] # all are the same data types - a list of numbers +['Banana', 'Orange', 'Mango', 'Avocado'] # all the same data types - a list of strings (fruits) +['Finland','Estonia', 'Sweden','Norway'] # all the same data types - a list of strings (countries) +['Banana', 10, False, 9.81] # different data types in the list - string, integer, boolean and float +``` + +#### Dicionário + +Um objeto de dicionário Python é uma coleção não ordenada de dados em um formato de par de valores-chave. + +**Exemplo:** + +```py +{ +'first_name':'Asabeneh', +'last_name':'Yetayeh', +'country':'Finland', +'age':250, +'is_married':True, +'skills':['JS', 'React', 'Node', 'Python'] +} +``` + +#### Tupla + +Uma tupla é uma coleção ordenada de diferentes tipos de dados, como uma lista, mas as tuplas não podem ser modificadas (são imutáveis) depois de criadas. Eles são imutáveis. + +**Exemplo:** + +```py +('Asabeneh', 'Pawel', 'Brook', 'Abraham', 'Lidiya') # Names +``` + +```py +('Earth', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Saturn', 'Uranus', 'Mercury') # planets +``` + +#### Set + +O set é uma coleção de tipos de dados semelhantes a uma lista e uma tupla. Ao contrário da lista e da tupla, set não é uma coleção ordenada de itens. Como na matemática, o conjunto em Python armazena apenas itens exclusivos. + +Nas seções posteriores, entraremos em detalhes sobre cada tipo de dados Python. + +**Exemplo:** + +```py +{2, 4, 3, 5} +{3.14, 9.81, 2.7} # order is not important in set +``` + +### Checando Tipos de Dados + +Para checar um determinado tipo de dado dados/variáveis, usamos a função **type**. No terminal a seguir você verá diferentes tipos de dados python: + +![Checking Data types](.././images/checking_data_types.png) + +### Arquivo Python + +Primeiro abra a pasta do seu projeto, 30DiasDePython. Se você não tiver essa pasta, crie um nome de pasta chamada 30DiasDePython. Dentro desta pasta, crie um arquivo chamado helloworld.py. Agora, vamos fazer o que fizemos no shell interativo python usando o visual studio code. + +O shell interativo do Python estava imprimindo sem usar **print** mas no visual studio code para ver nosso resultado deveríamos usar uma função integrada _print(). A função interna _print()_ recebe um ou mais argumentos da seguinte maneira _print('arument1', 'argument2', 'argument3')_. Veja os exemplos abaixo. + +**Exemplo:** + +O nome do arquivo é helloworld.py + +```py +# Day 1 - 30DaysOfPython Challenge + +print(2 + 3) # addition(+) +print(3 - 1) # subtraction(-) +print(2 * 3) # multiplication(*) +print(3 / 2) # division(/) +print(3 ** 2) # exponential(**) +print(3 % 2) # modulus(%) +print(3 // 2) # Floor division operator(//) + +# Checking data types +print(type(10)) # Int +print(type(3.14)) # Float +print(type(1 + 3j)) # Complex number +print(type('Asabeneh')) # String +print(type([1, 2, 3])) # List +print(type({'name':'Asabeneh'})) # Dictionary +print(type({9.8, 3.14, 2.7})) # Set +print(type((9.8, 3.14, 2.7))) # Tuple +``` + +Para executar o arquivo python verifique a imagem abaixo. Você pode executar o arquivo python executando o botão verde em Visual Studio Code ou digitando _python helloworld.py_ no seu terminal. + +![Running python script](.././images/running_python_script.png) + +🌕 Você é incrível. Você acabou de completar o desafio do primeiro dia e está a caminho da grandeza. Agora faça alguns exercícios para o cérebro e os músculos. + +## 💻 Exercicios - Dia 1 + +### Exercicio: Level 1 + +1. Cheque a versão do python que você esta usando +2. Abra o shell interativo python e execute as seguintes operações. Os operandos são 3 e 4. + - adição(+) + - subtração(-) + - multiplicação(\*) + - modulo(%) + - divisão(/) + - exponencial(\*\*) + - Divisão inteira(//) +3. Escreva strings no shell interativo python. As strings são as seguintes: + - Seu nome + - Seu sobrenome + - Seu país + - Eu estou aproveitando o 30 dias de python +4. Verifique os tipos de dados dos seguintes dados: + - 10 + - 9.8 + - 3.14 + - 4 - 4j + - ['Asabeneh', 'Python', 'Finland'] + - Seu nome + - O seu sobrenome + - Seu país + +### Exercicio: Level 2 + +1. Crie uma pasta chamada dia_1 dentro da pasta 30DiasDePython. Dentro da pasta day_1, crie um arquivo python helloworld.py e repita as perguntas 1, 2, 3 e 4. Lembre-se de usar _print()_ quando estiver trabalhando em um arquivo python. Navegue até o diretório onde você salvou seu arquivo e execute-o. + +### Exercicio: Level 3 + +1. Escreva um exemplo para diferentes tipos de dados Python, como Número (Inteiro, Flutuante, Complex), Strings, Booleanos, Listas, Tuplas, Set e Dicionário. +2. Ache em [Euclidian distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) entre (2, 3) e (10, 8) + +🎉 PARABÉNS ! 🎉 + +[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) From 7af6ba4cb0957e90cb5bc3986d66cbcccad24337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Fri, 5 Jul 2024 19:24:55 -0300 Subject: [PATCH 29/63] Linking to the translated readme --- readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/readme.md b/readme.md index 5bd0eb887..954dd7a7c 100644 --- a/readme.md +++ b/readme.md @@ -33,6 +33,7 @@ | 29 | [Building API](./29_Day_Building_API/29_building_API.md)| | 30 | [Conclusions](./30_Day_Conclusions/30_conclusions.md)| + 🧡🧡🧡 HAPPY CODING 🧡🧡🧡
@@ -55,6 +56,7 @@
+🇧🇷 [Portuguese](./Portuguese/README.md) [Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) ![30DaysOfPython](./images/30DaysOfPython_banner3@2x.png) From be1ee883a93cdfd429d143ecab8feddcfbc4497b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Fri, 5 Jul 2024 19:25:25 -0300 Subject: [PATCH 30/63] Fixxing --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index 954dd7a7c..bb1e88902 100644 --- a/readme.md +++ b/readme.md @@ -57,6 +57,7 @@
🇧🇷 [Portuguese](./Portuguese/README.md) + [Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) ![30DaysOfPython](./images/30DaysOfPython_banner3@2x.png) From 01af6b2bfa5b61c40af5beed2c8f7dfa6fb51bbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Fri, 5 Jul 2024 23:05:26 -0300 Subject: [PATCH 31/63] Adding the unrevised version of the translation --- .../README.md | 300 ++++++++++++++++++ 1 file changed, 300 insertions(+) create mode 100644 Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md diff --git a/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md new file mode 100644 index 000000000..f7eb8b48e --- /dev/null +++ b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md @@ -0,0 +1,300 @@ +
+

30 Dias de Python: Dia 2 - Variaveis, Builtin Functions

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ Segunda edição: July, 2021 +
+ +
+ +[<< Day 1](../README.md) | [Day 3 >>](../03_Day_Operators/03_operators.md) + +![30DaysOfPython](../.././images/30DaysOfPython_banner3@2x.png) + +- [📘 Dia 2](#-dia-2) + - [Built in functions](#built-in-functions) + - [Variaveis](#variables) + - [Declarando múltiplas váriaveis em uma linha](#declaring-multiple-variable-in-a-line) + - [Tipos de dados](#data-types) + - [Checando tipos de dados e type Casting](#checking-data-types-and-casting) + - [Numeros](#numbers) + - [💻 Exercicios - Dia 2](#-exercises---day-2) + - [Exercicios: Level 1](#exercises-level-1) + - [Exercicios: Level 2](#exercises-level-2) + +# 📘 Day 2 + +## Built in functions + +Em Python, temos muitas built-in functions. As built-in functions estão disponíveis globalmente para seu uso, o que significa que você pode fazer uso das built-in functions sem importar ou configurar. Algumas das built-in functions do Python mais comumente usadas são as seguintes: _print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_ e _dir()_ . Na tabela a seguir, você verá uma lista exaustiva de funções do Python retiradas da [documentação do python](https://docs.python.org/3.9/library/functions.html). +![Built-in Functions](../.././images/builtin-functions.png) + +Vamos abrir o shell do Python e começar a usar algumas built-in functions. + +![Built-in functions](../.././images/builtin-functions_practice.png) + +Vamos praticar mais usando diferentes built-in functions + +![Help and Dir Built in Functions](../.././images/help_and_dir_builtin.png) + +Como você pode ver no terminal acima, Python possui palavras reservadas. Não usamos palavras reservadas para declarar variáveis ​​ou funções. Abordaremos as variáveis ​​na próxima seção. + +Acredito que agora você já esteja familiarizado com as built-in functions. Vamos fazer mais uma prática de built-in functions e passaremos para a próxima seção. + +![Min Max Sum](../.././images/builtin-functional-final.png) + +## Variaveis + +As variáveis ​​armazenam dados na memória do computador. Variáveis ​​mnemônicas são recomendadas para uso em muitas linguagens de programação. Uma variável mnemônica é um nome de variável que pode ser facilmente lembrado e associado. Uma variável refere-se a um endereço de memória no qual os dados são armazenados. +Número no início, caractere especial e hífen não são permitidos ao nomear uma variável. Uma variável pode ter um nome curto (como x, y, z), mas um nome mais descritivo (nome, sobrenome, idade, país) é altamente recomendado. + +Regras da nomeclatura de variáveis no ​​​​Python + +- O nome de uma variável deve começar com uma letra ou sublinhado +- O nome de uma variável não pode começar com um número +- Um nome de variável só pode conter caracteres alfanuméricos e sublinhados (A-z, 0-9 e \_ ) +- O interpretador Python ​​diferencia maiúsculas de minúsculas (nome, nome, nome e PRIMEIRO NOME) são variáveis ​​diferentes) então tome cuidado com isso. + +Aqui estão alguns exemplos de nomes de variáveis ​​válidos: + +```shell +firstname +lastname +age +country +city +first_name +last_name +capital_city +_if # if we want to use reserved word as a variable +year_2021 +year2021 +current_year_2021 +birth_year +num1 +num2 +``` + +Nomes invalidos de variaveis + +```shell +first-name +first@name +first$name +num-1 +1num +``` + +Usaremos o estilo de nomenclatura de variáveis ​​Python padrão que foi adotado por muitos desenvolvedores Python. Os desenvolvedores Python usam a convenção de nomenclatura de variáveis ​​​​snake case (snake_case). Usamos underline após cada palavra para uma variável contendo mais de uma palavra (por exemplo, primeiro_nome, sobrenome, velocidade_de_rotação_do_motor). O exemplo abaixo é um exemplo de nomenclatura padrão de variáveis, o underline é necessário quando o nome da variável tem mais de uma palavra (isso é uma boa prática). + +Quando atribuímos um determinado tipo de dado a uma variável, isso é chamado de declaração de variável. Por exemplo, no exemplo abaixo, meu primeiro nome é atribuído a uma variável first_name. O sinal de igual é um operador de atribuição. Atribuir significa armazenar dados na variável (dar um valor a uma variavel). O sinal de igual em Python não é igualdade como em Matemática. + +_Exemplo:_ + +```py +# Variables in Python +first_name = 'Asabeneh' +last_name = 'Yetayeh' +country = 'Finland' +city = 'Helsinki' +age = 250 +is_married = True +skills = ['HTML', 'CSS', 'JS', 'React', 'Python'] +person_info = { + 'firstname':'Asabeneh', + 'lastname':'Yetayeh', + 'country':'Finland', + 'city':'Helsinki' + } +``` + +Vamos usar as funções _print()_ e _len()_. A função de impressão aceita um número ilimitado de argumentos. Um argumento é um valor que podemos passar ou colocar entre parênteses de função, veja o exemplo abaixo. + +**Exemplo:** + +```py +print('Hello, World!') # The text Hello, World! is an argument +print('Hello',',', 'World','!') # it can take multiple arguments, four arguments have been passed +print(len('Hello, World!')) # it takes only one argument +``` + +Vamos imprimir e também encontrar o comprimento das variáveis ​​declaradas no topo: + +**Exemplo:** + +```py +# Printing the values stored in the variables + +print('First name:', first_name) +print('First name length:', len(first_name)) +print('Last name: ', last_name) +print('Last name length: ', len(last_name)) +print('Country: ', country) +print('City: ', city) +print('Age: ', age) +print('Married: ', is_married) +print('Skills: ', skills) +print('Person information: ', person_info) +``` + +### Declarando múltiplas variaveis em uma linha + +Múltiplas variáveis ​​também podem ser declaradas em uma linha: + +**Exemplo:** + +```py +first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True + +print(first_name, last_name, country, age, is_married) +print('First name:', first_name) +print('Last name: ', last_name) +print('Country: ', country) +print('Age: ', age) +print('Married: ', is_married) +``` + +Podemos obter a entrada do usuário usando a função integrada _input()_. Vamos atribuir os dados que obtemos de um usuário às variáveis ​​first_name e age. + +**Exemplo:** + +```py +first_name = input('What is your name: ') +age = input('How old are you? ') + +print(first_name) +print(age) +``` + +## Tipos de Dados + +Existem vários tipos de dados no Python. Para identificar o tipo de dados, usamos a função integrada _type_. Gostaria de pedir que você se concentrasse em compreender muito bem os diferentes tipos de dados. Quando se trata de programação, tudo se resume a tipos de dados. Introduzi os tipos de dados logo no início e depois veremos de novo, porque cada tópico está relacionado aos tipos de dados. Abordaremos os tipos de dados com mais detalhes em suas respectivas seções. + +## Checando tipos de dados e Casting + +- Checando tipos de dados: Para verificar o tipo de dados de determinados dados/variáveis, usamos o _type_ + **Exemplo:** + +```py +# Different python data types +# Let's declare variables with various data types + +first_name = 'Asabeneh' # str +last_name = 'Yetayeh' # str +country = 'Finland' # str +city= 'Helsinki' # str +age = 250 # int, it is not my real age, don't worry about it + +# Printing out types +print(type('Asabeneh')) # str +print(type(first_name)) # str +print(type(10)) # int +print(type(3.14)) # float +print(type(1 + 1j)) # complex +print(type(True)) # bool +print(type([1, 2, 3, 4])) # list +print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict +print(type((1,2))) # tuple +print(type(zip([1,2],[3,4]))) # set +``` + +- Type Casting: Podemos converter um tipo de dado em outro tipo de dado. Nós podemos usar esses tipos para fazer o casting _int()_, _float()_, _str()_, _list_, _set_ + Quando fazemos operações aritméticas, os números das strings devem ser primeiro convertidos para int ou float, caso contrário, retornará um erro. Se concatenarmos um número com uma string, o número deverá primeiro ser convertido em uma string. Falaremos sobre concatenação na seção String. + + **Exemplo:** + +```py +# int to float +num_int = 10 +print('num_int',num_int) # 10 +num_float = float(num_int) +print('num_float:', num_float) # 10.0 + +# float to int +gravity = 9.81 +print(int(gravity)) # 9 + +# int to str +num_int = 10 +print(num_int) # 10 +num_str = str(num_int) +print(num_str) # '10' + +# str to int or float +num_str = '10.6' +print('num_int', int(num_str)) # 10 +print('num_float', float(num_str)) # 10.6 + +# str to list +first_name = 'Asabeneh' +print(first_name) # 'Asabeneh' +first_name_to_list = list(first_name) +print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h'] +``` + +## Numeros + +Numeros e tipos de dados em python: + +1. Inteiros: Inteiros são considerados os(negativos, zero números positivos) + Exemplo: + ... -3, -2, -1, 0, 1, 2, 3 ... + +2. Float(Números Decimais) + Exemplo: + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... + +3. Números Complexos + Exemplo: + 1 + j, 2 + 4j, 1 - 1j + +🌕 Você é incrível. Você acabou de completar os desafios do dia 2 e está dois passos à frente no caminho para a grandeza. Agora faça alguns exercícios para o cérebro e os músculos. + +## 💻 Exercicios - Dia 2 + +### Exercicios: Level 1 + +1. Dentro de 30DiasDePython crie uma pasta chamada day_2. Dentro desta pasta crie um arquivo chamado variáveis.py +2. Escreva um comentário em python dizendo: 'Dia 2/30 dias de programação em python' +3. Declare uma variável de primeiro nome e atribua um valor a ela +4. Declare uma variavel de sobrenome e atribua um valor a ela +5. Declare uma variavel de nome completo e atribua um valor a ela +6. Declare uma variavel do seu país e atribua um valor a ela +7. Declare uma variavel da sua cidade e atribua um valor a ela +8. Declare uma variavel da sua idade e atribua um valor a ela +9. Declare uma variavel ano e atribua um valor a ela +10. Declare uma variavel is_married e atribua um valor a ela +11. Declare uma variavel is_true e atribua um valor a ela +12. Declare uma variavel is_light_on e atribua um valor a ela +13. Declare multiplas variaveis em uma linha + +### Exercicios: Level 2 + +1. Verifique o tipo de dados de todas as suas variáveis ​​usando a função integrada type() +1. Usando a função integrada _len()_, encontre o comprimento do seu primeiro nome +1. Compare o comprimento do seu nome e do seu sobrenome +1. Declare 5 como num_one e 4 como num_two + 1. Adicione num_one e num_two e atribua o valor a uma variável total + 2. Subtraia num_two de num_one e atribua o valor a uma variável diff + 3. Multiplique num_dois e num_um e atribua o valor a um produto variável + 4. Divida num_one por num_two e atribua o valor a uma divisão variável + 5. Use a divisão de módulo para encontrar num_dois dividido por num_um e atribua o valor a uma variável restante + 6. Calcule num_one elevado a num_two e atribua o valor a uma variável exp + 7. Encontre a divisão mínima de num_one por num_two e atribua o valor a uma variável floor_division +2. O raio de um círculo é de 30 metros. + 1. Calcule a área de um círculo e atribua o valor a um nome de variável de _area_of_circle_ + 2. Calcule a circunferência de um círculo e atribua o valor a um nome de variável _circum_of_circle_ + 3. Pegue o raio como entrada do usuário e calcule a área. +1. Use a função de entrada integrada para obter nome, sobrenome, país e idade de um usuário e armazenar o valor em seus nomes de variáveis ​​correspondentes +1. Execute help('keywords') no Python shell ou em seu arquivo para verificar as palavras ou palavras-chave reservadas do Python + +🎉 PARABÉNS ! 🎉 + +[<< Day 1](../README.md) | [Day 3 >>](../03_Day_Operators/03_operators.md) From 98c325bcfff91edbd145451384ac8c9dfa8437c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Fri, 5 Jul 2024 23:09:48 -0300 Subject: [PATCH 32/63] Fixing path of readme files --- Portuguese/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Portuguese/README.md b/Portuguese/README.md index d6c3f0338..09feb4a88 100644 --- a/Portuguese/README.md +++ b/Portuguese/README.md @@ -3,7 +3,7 @@ |# Day | Topics | |------|:---------------------------------------------------------:| | 01 | [Introdução](./readme.md)| -| 02 | [Variaveis, Built-in Functions](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)| +| 02 | [Variaveis, Built-in Functions](./02_Dia_Variaveis_BuiltIn_Functions/README.md)| | 03 | [Operadores](./03_Day_Operators/03_operators.md)| | 04 | [Strings](./04_Day_Strings/04_strings.md)| | 05 | [Listas](./05_Day_Lists/05_lists.md)| @@ -55,7 +55,7 @@ -[Dia 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) +[Dia 2 >>](./02_Dia_Variaveis_BuiltIn_Functions/README.md) ![30DaysOfPython](.././images/30DaysOfPython_banner3@2x.png) @@ -449,8 +449,8 @@ Para executar o arquivo python verifique a imagem abaixo. Você pode executar o ### Exercicio: Level 3 1. Escreva um exemplo para diferentes tipos de dados Python, como Número (Inteiro, Flutuante, Complex), Strings, Booleanos, Listas, Tuplas, Set e Dicionário. -2. Ache em [Euclidian distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) entre (2, 3) e (10, 8) +2. Ache a [Distancia Euclidiana](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) entre (2, 3) e (10, 8) 🎉 PARABÉNS ! 🎉 -[Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) +[Day 2 >>](./02_Dia_Variaveis_BuiltIn_Functions/README.md) From ece16187e218e750d0feddbfc3b8e14b672bb8d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Sat, 6 Jul 2024 14:29:18 -0300 Subject: [PATCH 33/63] Spelling corrections --- .../README.md | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md index f7eb8b48e..7928f5c7a 100644 --- a/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md +++ b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md @@ -14,26 +14,26 @@ -[<< Day 1](../README.md) | [Day 3 >>](../03_Day_Operators/03_operators.md) +[<< Dia 1](../README.md) | [Dia 3 >>](../03_Day_Operators/03_operators.md) -![30DaysOfPython](../.././images/30DaysOfPython_banner3@2x.png) +![30DiasDePython](../.././images/30DaysOfPython_banner3@2x.png) - [📘 Dia 2](#-dia-2) - [Built in functions](#built-in-functions) - - [Variaveis](#variables) - - [Declarando múltiplas váriaveis em uma linha](#declaring-multiple-variable-in-a-line) - - [Tipos de dados](#data-types) - - [Checando tipos de dados e type Casting](#checking-data-types-and-casting) - - [Numeros](#numbers) - - [💻 Exercicios - Dia 2](#-exercises---day-2) - - [Exercicios: Level 1](#exercises-level-1) - - [Exercicios: Level 2](#exercises-level-2) + - [Variaveis](#Variaveis) + - [Declarando múltiplas váriaveis em uma linha](#Declarando-múltiplas-variaveis-em-uma-linha) + - [Tipos de dados](#Tipos-de-Dados) + - [Checando tipos de dados e type Casting](#Checando-tipos-de-dados-e-Casting) + - [Numeros](#Numeros) + - [💻 Exercicios - Dia 2](#-Exercicios---Dia-2) + - [Exercicios: Level 1](#Exercicios-level-1) + - [Exercicios: Level 2](#Exercicios-level-2) # 📘 Day 2 ## Built in functions -Em Python, temos muitas built-in functions. As built-in functions estão disponíveis globalmente para seu uso, o que significa que você pode fazer uso das built-in functions sem importar ou configurar. Algumas das built-in functions do Python mais comumente usadas são as seguintes: _print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_ e _dir()_ . Na tabela a seguir, você verá uma lista exaustiva de funções do Python retiradas da [documentação do python](https://docs.python.org/3.9/library/functions.html). +Em Python, temos muitas built-in functions. As built-in functions estão disponíveis globalmente para seu uso, o que significa que você pode fazer uso das built-in functions sem importar ou configurar. Algumas das built-in functions do Python mais usadas são as seguintes: _print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_ e _dir()_ . Na tabela a seguir, você verá uma lista gigantesca de funções do Python retiradas da [documentação do python](https://docs.python.org/3.9/library/functions.html). ![Built-in Functions](../.././images/builtin-functions.png) Vamos abrir o shell do Python e começar a usar algumas built-in functions. @@ -44,7 +44,7 @@ Vamos praticar mais usando diferentes built-in functions ![Help and Dir Built in Functions](../.././images/help_and_dir_builtin.png) -Como você pode ver no terminal acima, Python possui palavras reservadas. Não usamos palavras reservadas para declarar variáveis ​​ou funções. Abordaremos as variáveis ​​na próxima seção. +Como você pode ver no terminal acima, O Python possui palavras reservadas. Não usamos palavras reservadas para declarar variáveis ​​ou funções. Abordaremos as variáveis ​​na próxima seção. Acredito que agora você já esteja familiarizado com as built-in functions. Vamos fazer mais uma prática de built-in functions e passaremos para a próxima seção. @@ -53,13 +53,13 @@ Acredito que agora você já esteja familiarizado com as built-in functions. Vam ## Variaveis As variáveis ​​armazenam dados na memória do computador. Variáveis ​​mnemônicas são recomendadas para uso em muitas linguagens de programação. Uma variável mnemônica é um nome de variável que pode ser facilmente lembrado e associado. Uma variável refere-se a um endereço de memória no qual os dados são armazenados. -Número no início, caractere especial e hífen não são permitidos ao nomear uma variável. Uma variável pode ter um nome curto (como x, y, z), mas um nome mais descritivo (nome, sobrenome, idade, país) é altamente recomendado. +Número no início, caractere especial e hífen não são permitidos ao nomear uma variável. Uma variável pode ter um nome curto (como x, y, z), mas um nome mais descritivo tipo (nome, sobrenome, idade, país) é altamente recomendado. Regras da nomeclatura de variáveis no ​​​​Python -- O nome de uma variável deve começar com uma letra ou sublinhado +- O nome de uma variável deve começar com uma letra ou underline - O nome de uma variável não pode começar com um número -- Um nome de variável só pode conter caracteres alfanuméricos e sublinhados (A-z, 0-9 e \_ ) +- Um nome de variável só pode conter caracteres alfanuméricos e underlines (A-z, 0-9 e \_ ) - O interpretador Python ​​diferencia maiúsculas de minúsculas (nome, nome, nome e PRIMEIRO NOME) são variáveis ​​diferentes) então tome cuidado com isso. Aqui estão alguns exemplos de nomes de variáveis ​​válidos: @@ -115,7 +115,7 @@ person_info = { } ``` -Vamos usar as funções _print()_ e _len()_. A função de impressão aceita um número ilimitado de argumentos. Um argumento é um valor que podemos passar ou colocar entre parênteses de função, veja o exemplo abaixo. +Vamos usar as funções _print()_ e _len()_. A função de impressão aceita um número ilimitado de argumentos. Um argumento é um valor que podemos passar ou colocar entre parênteses, veja o exemplo abaixo. **Exemplo:** @@ -161,7 +161,7 @@ print('Age: ', age) print('Married: ', is_married) ``` -Podemos obter a entrada do usuário usando a função integrada _input()_. Vamos atribuir os dados que obtemos de um usuário às variáveis ​​first_name e age. +Podemos obter a entrada do usuário usando a função _input()_. Vamos atribuir os dados que obtemos de um usuário às variáveis ​​first_name e age. **Exemplo:** @@ -175,7 +175,7 @@ print(age) ## Tipos de Dados -Existem vários tipos de dados no Python. Para identificar o tipo de dados, usamos a função integrada _type_. Gostaria de pedir que você se concentrasse em compreender muito bem os diferentes tipos de dados. Quando se trata de programação, tudo se resume a tipos de dados. Introduzi os tipos de dados logo no início e depois veremos de novo, porque cada tópico está relacionado aos tipos de dados. Abordaremos os tipos de dados com mais detalhes em suas respectivas seções. +Existem vários tipos de dados no Python. Para identificar o tipo de dados, usamos a função _type_. Gostaria de pedir que você se concentrasse em compreender muito bem os diferentes tipos de dados. Quando se trata de programação, tudo se resume a tipos de dados. Introduzi os tipos de dados logo no início e depois veremos de novo, porque cada tópico está relacionado aos tipos de dados. Abordaremos os tipos de dados com mais detalhes em suas respectivas seções. ## Checando tipos de dados e Casting @@ -261,7 +261,7 @@ Numeros e tipos de dados em python: ### Exercicios: Level 1 -1. Dentro de 30DiasDePython crie uma pasta chamada day_2. Dentro desta pasta crie um arquivo chamado variáveis.py +1. Dentro de 30DiasDePython crie uma pasta chamada dia_2. Dentro desta pasta crie um arquivo chamado variáveis.py 2. Escreva um comentário em python dizendo: 'Dia 2/30 dias de programação em python' 3. Declare uma variável de primeiro nome e atribua um valor a ela 4. Declare uma variavel de sobrenome e atribua um valor a ela From 3fef5c268e75b9994d84dc656a48000fe3c10657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Sat, 6 Jul 2024 14:29:52 -0300 Subject: [PATCH 34/63] fixxing #1 --- Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md index 7928f5c7a..a9a40e945 100644 --- a/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md +++ b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md @@ -29,7 +29,7 @@ - [Exercicios: Level 1](#Exercicios-level-1) - [Exercicios: Level 2](#Exercicios-level-2) -# 📘 Day 2 +# 📘 Dia 2 ## Built in functions From d0add087b9f1848fcf1b88d0fa011288cdbafaec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Ciccarino=20=CE=BB?= <82242552+BrunoCiccarino@users.noreply.github.com> Date: Sat, 6 Jul 2024 15:23:26 -0300 Subject: [PATCH 35/63] Fixx #2 --- Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md index a9a40e945..93aa7a8a7 100644 --- a/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md +++ b/Portuguese/02_Dia_Variaveis_BuiltIn_Functions/README.md @@ -283,7 +283,7 @@ Numeros e tipos de dados em python: 1. Declare 5 como num_one e 4 como num_two 1. Adicione num_one e num_two e atribua o valor a uma variável total 2. Subtraia num_two de num_one e atribua o valor a uma variável diff - 3. Multiplique num_dois e num_um e atribua o valor a um produto variável + 3. Multiplique num_two e num_one e atribua o valor a um produto variável 4. Divida num_one por num_two e atribua o valor a uma divisão variável 5. Use a divisão de módulo para encontrar num_dois dividido por num_um e atribua o valor a uma variável restante 6. Calcule num_one elevado a num_two e atribua o valor a uma variável exp From 52c83e0e217cddb8b36978b85f007a85dd09de0a Mon Sep 17 00:00:00 2001 From: Archie Date: Tue, 9 Jul 2024 23:22:04 +0100 Subject: [PATCH 36/63] Translated into Chinese --- Chinese/README.md | 460 ++++++++++++++++++++++++++++++++++++++++++++++ readme.md | 1 + 2 files changed, 461 insertions(+) create mode 100644 Chinese/README.md diff --git a/Chinese/README.md b/Chinese/README.md new file mode 100644 index 000000000..4f7aedcb3 --- /dev/null +++ b/Chinese/README.md @@ -0,0 +1,460 @@ +# 🐍 30 天 Python + +| # 天数 | 主题 | +| ------ | :--------------------------------------------------------------------------------------: | +| 01 | [介绍](./readme.md) | +| 02 | [变量,内置函数](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | +| 03 | [运算符](./03_Day_Operators/03_operators.md) | +| 04 | [字符串](./04_Day_Strings/04_strings.md) | +| 05 | [列表](./05_Day_Lists/05_lists.md) | +| 06 | [元组](./06_Day_Tuples/06_tuples.md) | +| 07 | [集合](./07_Day_Sets/07_sets.md) | +| 08 | [字典](./08_Day_Dictionaries/08_dictionaries.md) | +| 09 | [条件](./09_Day_Conditionals/09_conditionals.md) | +| 10 | [循环](./10_Day_Loops/10_loops.md) | +| 11 | [函数](./11_Day_Functions/11_functions.md) | +| 12 | [模块](./12_Day_Modules/12_modules.md) | +| 13 | [列表解析](./13_Day_List_comprehension/13_list_comprehension.md) | +| 14 | [高阶函数](./14_Day_Higher_order_functions/14_higher_order_functions.md) | +| 15 | [类型错误](./15_Day_Python_type_errors/15_python_type_errors.md) | +| 16 | [Python 日期时间](./16_Day_Python_date_time/16_python_datetime.md) | +| 17 | [异常处理](./17_Day_Exception_handling/17_exception_handling.md) | +| 18 | [正则表达式](./18_Day_Regular_expressions/18_regular_expressions.md) | +| 19 | [文件处理](./19_Day_File_handling/19_file_handling.md) | +| 20 | [包管理器](./20_Day_Python_package_manager/20_python_package_manager.md) | +| 21 | [类和对象](./21_Day_Classes_and_objects/21_classes_and_objects.md) | +| 22 | [网页抓取](./22_Day_Web_scraping/22_web_scraping.md) | +| 23 | [虚拟环境](./23_Day_Virtual_environment/23_virtual_environment.md) | +| 24 | [统计](./24_Day_Statistics/24_statistics.md) | +| 25 | [Pandas](./25_Day_Pandas/25_pandas.md) | +| 26 | [Python 网页](./26_Day_Python_web/26_python_web.md) | +| 27 | [Python 与 MongoDB](./27_Day_Python_with_mongodb/27_python_with_mongodb.md) | +| 28 | [API](./28_Day_API/28_API.md) | +| 29 | [构建 API](./29_Day_Building_API/29_building_API.md) | +| 30 | [结论](./30_Day_Conclusions/30_conclusions.md) | + +🧡🧡🧡 快乐编码 🧡🧡🧡 + +
+帮助 作者 创作更多教育材料
+Paypal Logo +
+ +
+

30 天 Python:第 1 天 - 介绍

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[第 2 天 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) + +![30DaysOfPython](.././images/30DaysOfPython_banner3@2x.png) + +- [🐍 30 天 Python](#-30-天-python) +- [📘 第 1 天](#第-1-天) + - [欢迎](#欢迎) + - [介绍](#介绍) + - [为什么选择 Python?](#为什么选择-python) + - [环境设置](#环境设置) + - [安装 Python](#安装-python) + - [Python Shell](#python-shell) + - [安装 Visual Studio Code](#安装-visual-studio-code) + - [如何使用 Visual Studio Code](#如何使用-visual-studio-code) + - [Python 基础](#python-基础) + - [Python 语法](#python-语法) + - [Python 缩进](#python-缩进) + - [注释](#注释) + - [数据类型](#数据类型) + - [数字](#数字) + - [字符串](#字符串) + - [布尔值](#布尔值) + - [列表](#列表) + - [字典](#字典) + - [元组](#元组) + - [集合](#集合) + - [检查数据类型](#检查数据类型) + - [Python 文件](#python-文件) + - [💻 练习 - 第 1 天](#-练习-第-1-天) + - [练习:等级 1](#练习等级-1) + - [练习:等级 2](#练习等级-2) + - [练习:等级 3](#练习等级-3) + +# 📘 第 1 天 + +## 欢迎! + +**恭喜** 你决定参加 _30 天 Python_ 编程挑战。在这个挑战中,你将学习成为一名 Python 程序员所需的一切以及所有编程概念。挑战结束时,你将获得 _30DaysOfPython_ 编程挑战证书。 + +如果你想积极参与挑战,可以加入 Telegram 群组 [30DaysOfPython challenge](https://t.me/ThirtyDaysOfPython)。 + +## 介绍 + +Python 是一种高级编程语言,适用于通用编程。它是一种开源、解释性和面向对象的编程语言。Python 由荷兰程序员 Guido van Rossum 创建。编程语言 Python 的名称来源于英国喜剧系列 _Monty Python's Flying Circus_。第一个版本于 1991 年 2 月 20 日发布。这个 30 天的 Python 挑战将帮助你逐步学习最新版本的 Python,Python 3。每一天都有不同的主题,包含易于理解的解释、现实世界的示例、大量的实际练习和项目。 + +本挑战适合初学者和希望学习 Python 编程语言的专业人士。完成挑战可能需要 30 到 100 天,积极参与 Telegram 群组的成员更有可能完成挑战。 + +本挑战易于阅读,最初以通俗英语编写,并翻译成中文,既具有吸引力、激励性,又具有很高的挑战性。你需要投入大量时间来完成这个挑战。如果你是通过观看学习效果更好的人,可以观看视频教程,访问 +Washera YouTube 频道 你可以从 [Python 对绝对初学者的视频](https://youtu.be/OCCWZheOesI) 开始。订阅频道,在 YouTube 视频中评论你的问题,并积极主动,作者最终会注意到你。 + +作者喜欢听取你对挑战的意见,分享文章并反馈你对 30DaysOfPython 挑战的看法。你可以在此处留下对文章的反馈:[link](https://testimonial-vdzd.onrender.com/) + +## 为什么选择 Python? + +它是一种非常接近人类语言的编程语言,语法简单,因此易于学习和使用。 +Python 被各行各业和公司(包括 Google)使用。它被用于开发 Web 应用程序、桌面应用程序、系统管理和机器学习库。Python 在数据科学和机器学习社区中被广泛采用。希望这足以说服你开始学习 Python。 + +## 环境设置 + +### 安装 Python + +要运行用 Python 编写的脚本,你需要安装 Python。访问 [Python 下载页面](https://www.python.org/)。 + +如果你是 Windows 用户。点击红色圈出的按钮。 + +[![在 Windows 上安装](.././images/installing_on_windows.png)](https://www.python.org/) + +如果你是 MacOS 用户。点击红色圈出的按钮。 + +[![在 MacOS 上安装](.././images/installing_on_macOS.png)](https://www.python.org/) + +要检查是否安装了 Python,请在设备的终端中输入以下命令。 + +```shell +python --version +``` + +![Python Version](./images/python_versio.png) + +如你所见,在终端中,我当前使用的版本是 Python 3.7.5。你的 Python 版本可能与我的不同,但应为 3.6 或更高版本。如果你能看到 Python 版本,很好。Python 已安装在你的机器上。继续下一部分。 + +### Python Shell + +Python 是一种解释型脚本语言,因此不需要编译。这意味着它逐行执行代码。Python 附带一个 Python Shell (Python 交互式 Shell),也称为 REPL (Read Eval Print Loop)。它用于执行单个 Python 命令并获得结果。 + +Python Shell 等待用户的 Python 代码。当输入代码时,它会解释并显示结果。 +打开终端或命令提示符 (cmd) 并输入: + +```shell +python +``` + +![Python Scripting Shell](./images/opening_python_shell.png) + +Python 交互式 Shell 已打开,等待你在该符号 >>> 旁边编写 Python 代码(Python 脚本)。编写第一个脚本并点击 Enter。 +让我们在 Python 脚本 Shell 中编写第一个脚本。 + +![Python script on Python shell](./images/adding_on_python_shell.png) + +非常好,你已经在 Python 交互式 Shell 中编写了第一个 Python 脚本。如何关闭 Python 交互式 Shell? +要关闭 Shell,请在该符号 >>> 旁边输入命令 **exit()** 并按 Enter。 + +![Exit from python shell](./images/exit_from_shell.png) + +现在你知道如何打开 Python 交互式 Shell 以及如何退出它。 + +Python 将在你编写 Python 可理解的脚本时提供结果;否则,它将返回错误。让我们故意犯一个错误,看看 Python 返回什么。 + +![Invalid Syntax Error](./images/invalid_syntax_error.png) + +如你所见,返回的错误表明 Python 非常智能,它知道我们犯了语法错误:Syntax Error: Invalid Syntax。在 Python 中使用 x 作为乘法是语法错误,因为 (x) 不是 Python 中的有效语法。我们用星号 (\*) 来表示乘法而不是 (x)。返回的错误明确显示了需要修正的地方。 + +识别和删除程序中的错误的过程称为调试。让我们通过将 \* 替换为 x 来调试它。 + +![Fixing Syntax Error](./images/fixing_syntax_error.png) + +我们的错误已修复,代码已执行,并得到了我们期望的结果。作为程序员,你每天都会看到这种类型的错误。了解如何调试是很重要的。为了擅长调试,你必须了解所遇到的错误类型。你可能会遇到的 Python 错误类型有 _SyntaxError_, _IndexError_, _NameError_, _ModuleNotFoundError_, _KeyError_, _ImportError_, _AttributeError_, _TypeError_, _ValueError_, _ZeroDivisionError_ 等等。我们将在后面的部分详细了解不同类型的 Python 错误! + +让我们更多地练习如何使用 Python 交互式 Shell。转到终端或命令提示符并输入单词 python。 + +![Python Scripting Shell](./images/opening_python_shell.png) + +Python 交互式 Shell 已打开。让我们做一些基本的数学运算(加法、减法、乘法、除法、取模、指数运算)。 + +在编写任何 Python 代码之前,让我们做一些数学运算: + +- 2 + 3 是 5 +- 3 - 2 是 1 +- 3 \* 2 是 6 +- 3 / 2 是 1.5 +- 3 \*_ 2 相当于 3 _ 3 + +在 Python 中,我们有以下附加运算: + +- 3 % 2 = 1 => 这意味着找到余数或(除法的模数) +- 3 // 2 = 1 => 这意味着删除除法的余数 + +让我们将上述数学表达式转换为 Python 代码。已打开 Python Shell,让我们在 Shell 的开头编写一个注释。 + +A _comment_ 是代码中未被 Python 执行的一部分,注释被 Python 解释器忽略。因此,我们可以在代码中留下某些文本以提高其可读性。Python 不执行注释部分。Python 中的注释以井号 (#) 符号开头。 +这就是你在 Python 中编写注释的方式: + +```python +# 注释以井号开头 +# 这是一个python注释,因为它以(#)符号开头 +``` + +![Maths on python shell](./images/maths_on_python_shell.png) + +在进入下一部分之前,让我们更多地练习 Python 交互式 Shell。通过在 Shell 中输入 _exit()_ 关闭已打开的 Shell,然后再次打开它,让我们练习如何在 Python Shell 中编写文本。 + +![Writing String on python shell](./images/writing_string_on_shell.png) + +### 安装 Visual Studio Code + +Python 交互式 Shell 非常适合测试小的脚本代码,但对于大型项目来说并不适用。在实际的工作环境中,开发人员使用不同的代码编辑器来编写代码。在这个 30 天的 Python 编程挑战中,我们将使用 Visual Studio Code。Visual Studio Code 是一个非常流行的开源文本编辑器。我是 vscode 的粉丝,并推荐下载 Visual Studio Code,但如果你喜欢其他编辑器,可以随意使用。 + +[![Visual Studio Code](./images/vscode.png)](https://code.visualstudio.com/) + +如果你已安装 Visual Studio Code,让我们看看如何使用它。 +如果你喜欢视频教程,你可以观看安装和配置 Visual Studio Code 以用于 Python 的[视频教程](https://www.youtube.com/watch?v=bn7Cx4z-vSo) + +#### 如何使用 Visual Studio Code + +通过双击 Visual Studio 图标打开 Visual Studio Code。打开后,你会看到类似的界面。尝试与标注的图标进行交互。 + +![Visual studio Code](./images/vscode_ui.png) + +在桌面上创建一个名为 30DaysOfPython 的文件夹。然后使用 Visual Studio Code 打开它。 + +![Opening Project on Visual studio](./images/how_to_open_project_on_vscode.png) + +![Opening a project](./images/opening_project.png) + +打开后,你会看到在 30DaysOfPython 项目目录中创建文件和文件夹的快捷方式。如下所示,我创建了第一个文件 helloworld.py。你也可以这样做。 + +![Creating a python file](./images/helloworld.png) + +经过长时间的编码,你想关闭你的代码编辑器,对吗?这是你关闭已打开项目的方法。 + +![Closing project](./images/closing_opened_project.png) + +恭喜你,完成了开发环境的设置。让我们开始编码。 + +## Python 基础 + +### Python 语法 + +Python 脚本可以在 Python 交互式 Shell 或代码编辑器中编写。Python 文件的扩展名为 .py。 + +### Python 缩进 + +缩进是文本中的空白。在许多语言中,缩进用于提高代码的可读性,但 Python 使用缩进来创建代码块。在其他编程语言中,使用大括号来创建代码块,而不是缩进。在 Python 中编写代码时,一个常见的错误是缩进错误。 + +![Indentation Error](./images/indentation.png) + +### 注释 + +注释对于提高代码的可读性和在代码中留下注释非常重要。Python 不执行代码中的注释部分。 +在 Python 中,任何以井号 (#) 开头的文本都是注释。 + +# 示例:单行注释 + +```shell +# 这是第一个注释 +# 这是第二个注释 +# Python 正在吞噬世界 +``` + +# 示例:多行注释,称为文档字符串 + +三重引号可以用于多行注释,如果它没有被分配给变量。 + +```shell +"""这是多行注释 +多行注释占用多行。 +Python 正在吞噬世界 +""" +``` + +### 数据类型 + +Python 中有多种数据类型。让我们从最常见的开始。不同的数据类型将在其他部分详细讨论。现在,让我们浏览一下不同的数据类型并熟悉它们。你现在不需要有明确的理解。 + +#### 数字 + +- 整数:它被认为是整数(负数、零和正数) + 示例: + ... -3, -2, -1, 0, 1, 2, 3 ... +- 浮点数:小数 + 示例: + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... +- 复数 + 示例: + 1 + j, 2 + 4j + +#### 字符串 + +一串字符组成的文本,使用单引号或双引号表示。如果字符串超过一行,可以使用三引号。 + +**例子:** + +```py +'Asabeneh' +'Finland' +'Python' +'I love teaching' +'I hope you are enjoying the first day of 30DaysOfPython Challenge' +``` + +#### 布尔值 + +布尔值是 True 或 False。T 和 F 必须大写。 + +**例子:** + +```python +True # 灯是开的吗?如果是开着的,那么值是 True +False # 灯是开的吗?如果是关着的,那么值是 False +``` + +#### 列表 + +列表是一个有序的集合,可以存储不同类型的数据。类似于 JavaScript 中的数组。 + +**例子:** + +```py +[0, 1, 2, 3, 4, 5] # 所有都是相同数据类型 - 数字列表 +['Banana', 'Orange', 'Mango', 'Avocado'] # 所有都是相同数据类型 - 字符串列表(水果) +['Finland','Estonia', 'Sweden','Norway'] # 所有都是相同数据类型 - 字符串列表(国家) +['Banana', 10, False, 9.81] # 列表中的不同数据类型 - 字符串、整数、布尔值和浮点数 +``` + +#### 字典 + +Python 字典对象是以键值对格式存储的无序集合。 + +**例子:** + +```py +{ +'first_name':'Asabeneh', +'last_name':'Yetayeh', +'country':'Finland', +'age':250, +'is_married':True, +'skills':['JS', 'React', 'Node', 'Python'] +} +``` + +#### 元组 + +元组是一个有序的集合,类似于列表,但元组一旦创建就不能修改。它们是不可变的。 + +**例子:** + +```py +('Asabeneh', 'Pawel', 'Brook', 'Abraham', 'Lidiya') # 名字 +``` + +```py +('Earth', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Saturn', 'Uranus', 'Mercury') # 行星 +``` + +#### 集合 + +集合是类似于列表和元组的集合数据类型。与列表和元组不同,集合不是一个有序的集合。就像在数学中一样,Python 中的集合只存储唯一的项目。 + +在后面的部分,我们将详细介绍每种 Python 数据类型。 + +**例子:** + +```py +{2, 4, 3, 5} +{3.14, 9.81, 2.7} # 集合中的顺序不重要 +``` + +### 检查数据类型 + +要检查某个数据/变量的数据类型,我们使用 **type** 函数。在以下终端中,你将看到不同的 Python 数据类型: + +![Checking Data types](./images/checking_data_types.png) + +### Python 文件 + +首先打开你的项目文件夹,30DaysOfPython。如果你没有这个文件夹,创建一个名为 30DaysOfPython 的文件夹。在这个文件夹内,创建一个名为 helloworld.py 的文件。现在,让我们在 Visual Studio Code 中做我们在 Python 交互式 Shell 中所做的事情。 + +Python 交互式 Shell 在不使用 **print** 的情况下打印,但在 Visual Studio Code 中,为了查看我们的结果,我们应该使用内置函数 _print()_。_print()_ 内置函数接受一个或多个参数,如下所示 _print('arument1', 'argument2', 'argument3')_。请参见以下示例。 + +**例子:** + +​ 文件名是 helloworld.py + +```py +# 第 1 天 - 30DaysOfPython 挑战 + +print(2 + 3) # 加法(+) +print(3 - 1) # 减法(-) +print(2 * 3) # 乘法(*) +print(3 / 2) # 除法(/) +print(3 ** 2) # 指数(**) +print(3 % 2) # 取模(%) +print(3 // 2) # 整除(//) + +# 检查数据类型 +print(type(10)) # 整数 +print(type(3.14)) # 浮点数 +print(type(1 + 3j)) # 复数 +print(type('Asabeneh')) # 字符串 +print(type([1, 2, 3])) # 列表 +print(type({'name':'Asabeneh'})) # 字典 +print(type({9.8, 3.14, 2.7})) # 集合 +print(type((9.8, 3.14, 2.7))) # 元组 +``` + +要运行 Python 文件,请查看下图。你可以通过在 Visual Studio Code 中点击绿色按钮或在终端中输入 _python helloworld.py_ 来运行 Python 文件。 + +![Running python script](./images/running_python_script.png) + +🌕 你很棒。你刚刚完成了第 1 天的挑战,你正在迈向伟大。现在做一些练习来锻练你的大脑和肌肉。 + +## 💻 练习 - 第 1 天 + +### 练习:等级 1 + +1. 检查你使用的 Python 版本 +2. 打开 Python 交互式 Shell 并执行以下操作。操作数是 3 和 4。 + - 加法(+) + - 减法(-) + - 乘法(\*) + - 取模(%) + - 除法(/) + - 指数(\*\*) + - 整除(//) +3. 在 Python 交互式 Shell 中编写字符串。字符串如下: + - 你的名字 + - 你的姓氏 + - 你的国家 + - 我正在享受 30 天的 Python +4. 检查以下数据的数据类型: + - 10 + - 9.8 + - 3.14 + - 4 - 4j + - ['Asabeneh', 'Python', 'Finland'] + - 你的名字 + - 你的姓氏 + - 你的国家 + +### 练习:等级 2 + +1. 在 30DaysOfPython 文件夹中创建一个名为 day*1 的文件夹。在 day_1 文件夹中,创建一个名为 helloworld.py 的 Python 文件,并重复问题 1、2、3 和 4。记住在处理 Python 文件时使用 \_print()*。导航到你保存文件的目录,并运行它。 + +### 练习:等级 3 + +1. 为不同的 Python 数据类型编写一个示例,如数字(整数、浮点数、复数)、字符串、布尔值、列表、元组、集合和字典。 +2. 找到 (2, 3) 和 (10, 8) 之间的 [欧几里得距离](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance)。 + +🎉 恭喜 ! 🎉 + +[第 2 天 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) diff --git a/readme.md b/readme.md index bb1e88902..4a10d3b1f 100644 --- a/readme.md +++ b/readme.md @@ -57,6 +57,7 @@ 🇧🇷 [Portuguese](./Portuguese/README.md) +🇨🇳 [中文](./Chinese/README.md) [Day 2 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) From 3f6ac87432a7ac17306343c44c43b19fd3892d12 Mon Sep 17 00:00:00 2001 From: Taki-Ta Date: Thu, 11 Jul 2024 20:56:34 +0800 Subject: [PATCH 37/63] feature: add 02,03,04,05 chinese translation --- Chinese/02_variables_builtin_functions.md | 307 +++++++++++ Chinese/03_operators.md | 321 ++++++++++++ Chinese/04_strings.md | 609 ++++++++++++++++++++++ Chinese/05_lists.md | 596 +++++++++++++++++++++ Chinese/README.md | 44 +- 5 files changed, 1855 insertions(+), 22 deletions(-) create mode 100644 Chinese/02_variables_builtin_functions.md create mode 100644 Chinese/03_operators.md create mode 100644 Chinese/04_strings.md create mode 100644 Chinese/05_lists.md diff --git a/Chinese/02_variables_builtin_functions.md b/Chinese/02_variables_builtin_functions.md new file mode 100644 index 000000000..36ba68bb4 --- /dev/null +++ b/Chinese/02_variables_builtin_functions.md @@ -0,0 +1,307 @@ +
+

30 天 Python:第二天 - 变量, 内置函数

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[<< 第一天](./readme.md) | [第三天 >>](./03_operators.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +_阅读大约需要:12m_ + +- [📘 第二天](#-第二天) + - [内置函数](#内置函数) + - [变量](#变量) + - [在一行中声明多个变量](#在一行中声明多个变量) + - [数据类型](#数据类型) + - [数据类型转换](#数据类型转换) + - [Numbers](#numbers) + - [💻 练习 - 第二天](#-练习---第二天) + - [练习: 1级](#练习-1级) + - [练习: 2级](#练习-2级) + +# 📘 第二天 + +## 内置函数 + +Python 提供了很多内置函数。内置函数是全局可用的,这意味着您可以在不导入或配置的情况下使用内置函数。以下是几种最常用的 Python 内置函数:_print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_, _dir()_。在下表中,您将看到从 [Python 文档](https://docs.python.org/3.9/library/functions.html)中获取的详尽的 Python 内置函数列表。 + +![Built-in Functions](../images/builtin-functions.png) + +让我们打开 Python shell 并开始使用一些最常见的内置函数。 + +![Built-in functions](../images/builtin-functions_practice.png) + +使用不同的内置函数进行更多练习 + +![Help and Dir Built in Functions](../images/help_and_dir_builtin.png) + +如上所示,Python 有保留字。我们不能使用保留字来声明变量或函数。我们将在下一节中介绍变量。 + +我相信,现在您已经熟悉了内置函数。让我们再练习一下内置函数,然后我们继续下一节。 + +![Min Max Sum](../images/builtin-functional-final.png) + +## 变量 + +变量将数据存储在计算机内存中。在许多编程语言中,建议使用助记符变量。助记符变量是一个易于记忆和关联的变量名。变量指的是存储数据的内存地址。 + +命名变量时,不允许以数字开头、使用特殊字符和连字符。变量可以有一个简短的名称(如 x、y、z),但强烈建议使用更具描述性的名称(名字、姓氏、年龄、国家/地区)。 + +Python 变量名规则 + +- 变量名必须以字母或下划线字符开头 +- 变量名不能以数字开头 +- 变量名只能包含字母数字字符和下划线(A-z、0-9 和 \_ ) +- 变量名区分大小写(firstname、Firstname、FirstName 和 FIRSTNAME 是不同的变量) + +以下是一些有效变量名的示例: + +```shell +firstname +lastname +age +country +city +first_name +last_name +capital_city +_if # 如果我们想使用保留字作为变量 +year_2021 +year2021 +current_year_2021 +birth_year +num1 +num2 +``` + +无效的变量名 + +```shell +first-name +first@name +first$name +num-1 +1num +``` +我们将使用许多 Python 开发人员采用的标准 Python 变量命名样式。Python 开发人员使用蛇形命名法 (snake_case) 变量命名约定。对于包含多个单词的变量,我们在每个单词后使用下划线(例如 first_name、last_name、engine_rotation_speed)。下面的示例是变量的标准命名示例,当变量名称超过一个单词时,需要使用下划线。 + +当我们将某种数据类型分配给变量时,这称为变量声明。例如,在下面的例子中,我的名字被分配给变量 first_name。等号是赋值运算符。赋值意味着将数据存储在变量中。Python 中的等号与数学中的等号不同。 + +_示例:_ + +```py +# Python 中的变量 +first_name = 'Asabeneh' +last_name = 'Yetayeh' +country = 'Finland' +city = 'Helsinki' +age = 250 +is_married = True +skills = ['HTML', 'CSS', 'JS', 'React', 'Python'] +person_info = { + 'firstname':'Asabeneh', + 'lastname':'Yetayeh', + 'country':'Finland', + 'city':'Helsinki' + } +``` + +让我们使用 _print()_ 和 _len()_ 内置函数。打印函数可以接受无限数量的参数。参数是一个值,我们可以将其传递或放在函数括号内,请参见下面的示例。 + +**示例:** + +```py +print('Hello, World!') # The text Hello, World! is an argument +print('Hello',',', 'World','!') # it can take multiple arguments, four arguments have been passed +print(len('Hello, World!')) # it takes only one argument +``` + +让我们打印并算出在上面声明的变量的长度: + + +**示例:** + +```py +# 打印变量的值 + +print('First name:', first_name) +print('First name length:', len(first_name)) +print('Last name: ', last_name) +print('Last name length: ', len(last_name)) +print('Country: ', country) +print('City: ', city) +print('Age: ', age) +print('Married: ', is_married) +print('Skills: ', skills) +print('Person information: ', person_info) +``` + +### 在一行中声明多个变量 + +多个变量也可以在同一行中声明: + +**示例:** + +```py +first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True + +print(first_name, last_name, country, age, is_married) +print('First name:', first_name) +print('Last name: ', last_name) +print('Country: ', country) +print('Age: ', age) +print('Married: ', is_married) +``` + +使用内置函数 _input()_ 获取用户输入。让我们从用户那里得到的数据并赋值给 first_name 和 age 变量。 +. +**示例:** + +```py +first_name = input('What is your name: ') +age = input('How old are you? ') + +print(first_name) +print(age) +``` + +## 数据类型 + +Python 中有多种数据类型。为了识别数据类型,我们使用 _type_ 内置函数。我想请您熟练掌握不同的数据类型。当涉及到编程时,一切都与数据类型有关。我在一开始就介绍了数据类型,现在又提到了,因为每个主题都与数据类型有关。我们将在数据类型各自的章节中做更详细的介绍。 + +## 数据类型转换 + +- 检查数据类型:为了检查某些数据/变量的数据类型,我们使用 _type_ 函数 + + **示例:** + +```py +# python 中不同的数据类型 +# 声明一些有各种数据类型的变量 + +first_name = 'Asabeneh' # str +last_name = 'Yetayeh' # str +country = 'Finland' # str +city= 'Helsinki' # str +age = 250 # int, 不用担心,这并不是我真实的年龄 :) + +# Printing out types +print(type('Asabeneh')) # str +print(type(first_name)) # str +print(type(10)) # int +print(type(3.14)) # float +print(type(1 + 1j)) # complex +print(type(True)) # bool +print(type([1, 2, 3, 4])) # list +print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict +print(type((1,2))) # tuple +print(type(zip([1,2],[3,4]))) # set +``` + +- 数据类型转换:将一种数据类型转换为另一种数据类型。我们使用 _int()_、_float()_、_str()_、_list_、_set_ +当我们进行算术运算时,字符串数字应首先转换为 int 或 float,否则将返回错误。如果我们将数字与字符串连接起来,则应首先将数字转换为字符串。我们将在字符串部分讨论连接。 + + + **示例:** + +```py +# 整型 到 浮点型 +num_int = 10 +print('num_int',num_int) # 10 +num_float = float(num_int) +print('num_float:', num_float) # 10.0 + +# 浮点型 到 整型 +gravity = 9.81 +print(int(gravity)) # 9 + +# 整型 到 字符串 +num_int = 10 +print(num_int) # 10 +num_str = str(num_int) +print(num_str) # '10' + +# 字符串 到 整型或浮点型 +num_str = '10.6' +print('num_int', int(num_str)) # 10 +print('num_float', float(num_str)) # 10.6 + +# 字符串 到 列表 +first_name = 'Asabeneh' +print(first_name) # 'Asabeneh' +first_name_to_list = list(first_name) +print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h'] +``` + +## Number + +Python 中不同的数字类型 + +- Integer:整型数字(负数, 0 以及 正数) + 示例: + ... -3, -2, -1, 0, 1, 2, 3 ... +- Float:浮点数 + 示例 + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... +- Complex:复数 + 示例 + 1 + j, 2 + 4j, 1 - 1j + +🌕 你太棒了。你刚刚完成了第 2 天的挑战,在通往成功的路上又前进了一步。现在做一些练习来锻练你的大脑和肌肉。 + + +## 💻 练习 - 第二天 + +### 练习: 1级 + +1. 在 30DaysOfPython 文件夹内创建一个 day_2 文件夹。在这个文件夹里创建一个 variables.py 文件 +2. 输入注释 '第二天: 30 Days of python programming' +3. 声明一个 first name 变量,并为它赋值 +4. 声明一个 last name 变量,并为它赋值 +5. 声明一个 full name 变量,并为它赋值 +6. 声明一个 country 变量,并为它赋值 +7. 声明一个 city 变量,并为它赋值 +8. 声明一个 age 变量,并为它赋值 +9. 声明一个 year 变量,并为它赋值 +10. 声明一个 is_married 变量,并为它赋值 +11. 声明一个 is_true 变量,并为它赋值 +12. 声明一个 is_light_on 变量,并为它赋值 +13. 在一行中声明多个变量 + +### 练习: 2级 + +1. 使用 _type()_ 内置函数检查你声明变量的数据类型 +1. 使用 _len()_ 内置函数,算出你 first name 变量的长度 +1. 比较你 first name 和 last name 变量的长度 +1. 声明变量 num_one 为5,num_two 为4 + 1. 将 num_one 和 num_two 相加,并赋值给 total 变量 + 2. 将 num_one 和 num_two 相减,并赋值给 diff 变量 + 3. 将 num_one 和 num_two 相乘,并赋值给 product 变量 + 4. 将 num_one 和 num_two 相乘,并赋值给 division 变量 + 5. 使用模数除法求出 num_two 除以 num_one 的结果,并将结果赋给变量 remainder + 6. 计算 num_one 的 num_two 次方并将值赋给变量 exp + 7. 计算 num_one 除以 num_two 商的整数部分(整除操作),并将结果赋给变量 floor_division +1. 圆的半径为 30 米。 + 1. 计算圆的面积并将值赋给名为 _area_of_circle_ 的变量 + 2. 计算圆的周长并将值赋给名为 _circum_of_circle_ 的变量 + 3. 将半径作为用户输入并计算面积。 +1. 使用内置输入函数从用户那里获取名字、姓氏、国家和年龄,并将值存储到相应的变量名中 +1. 在 Python shell 或文件中运行 help('keywords') 检查 Python 保留字或关键字 + + + +🎉 恭喜 ! 🎉 + +[<< 第一天](./readme.md) | [第三天 >>](./03_operators.md) diff --git a/Chinese/03_operators.md b/Chinese/03_operators.md new file mode 100644 index 000000000..85abc9a02 --- /dev/null +++ b/Chinese/03_operators.md @@ -0,0 +1,321 @@ +
+

30 天 Python:第三天 - 运算符

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+
+ +[<< 第二天](./02_variables_builtin_functions.md) | [第四天 >>](./04_strings.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +阅读大约需要:12m +- [📘 第三天](#-第三天) + - [Boolean](#boolean) + - [运算符](#运算符) + - [赋值运算符](#赋值运算符) + - [算术运算符](#算术运算符) + - [比较运算符](#比较运算符) + - [逻辑运算符](#逻辑运算符) + - [💻 练习 - 第三天](#-练习---第三天) + +# 📘 第三天 + +## Boolean + +布尔类型表示两个值之一:_True_ 或 _False_。一旦我们开始使用比较运算符,这些数据类型的使用将变得清晰。第一个字母 **T** 表示 True,**F** 表示 False,与 JavaScript 不同,Python 的布尔类型的首字母应该是大写。 + +**示例: 布尔类型的值** + +```py +print(True) +print(False) +``` + +## 运算符 + +Python 语言支持多种类型的运算符。在本节中,我们将重点介绍其中的一些。 + +### 赋值运算符 + +赋值运算符用于将值赋值给变量。让我们以 = 为例。在数学中,等号表示两个值相等,但在 Python 中,它表示我们正在将一个值存储在某个变量中,我们称之为赋值或将值分配给变量。下表显示了不同类型的 Python 赋值运算符,摘自 [w3school](https://www.w3schools.com/python/python_operators.asp)。 + +![Assignment Operators](../images/assignment_operators.png) + +### 算术运算符: + +- 加(+): a + b +- 减(-): a - b +- 乘(*): a * b +- 除(/): a / b +- 模运算(%): a % b +- 整除(//): a // b +- 指数运算(**): a ** b + +![Arithmetic Operators](../images/arithmetic_operators.png) + +**示例:整型** + +```py +# Python 中的算术运算符 +# 整型 + +print('Addition: ', 1 + 2) # 3 +print('Subtraction: ', 2 - 1) # 1 +print('Multiplication: ', 2 * 3) # 6 +print ('Division: ', 4 / 2) # 2.0 Python 中的除法运算符返回浮点数 +print('Division: ', 6 / 2) # 3.0 +print('Division: ', 7 / 2) # 3.5 +print('Division without the remainder: ', 7 // 2) # 3, 返回商的整数部分 +print ('Division without the remainder: ',7 // 3) # 2 +print('Modulus: ', 3 % 2) # 1, 返回余数 +print('Exponentiation: ', 2 ** 3) # 8 代表 2 * 2 * 2 +``` + +**示例:浮点数** + +```py +# 浮点数 +print('Floating Point Number, PI', 3.14) +print('Floating Point Number, gravity', 9.81) +``` + +**示例:复数** + +```py +# 复数 +print('Complex number: ', 1 + 1j) +print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j)) +``` + +让我们声明一个变量并分配一个数字类型。我下面使用单个字符变量,但请不要养成这样命名变量的习惯。变量名应始终便于记忆。 + +**示例:** + +```python +# 首先声明变量 + +a = 3 # a 是一个变量名,3 是一个整型值 +b = 2 # b 是一个变量名,2 是一个整型值 + +# 进行算术运算,并将结果赋值给变量 +total = a + b +diff = a - b +product = a * b +division = a / b +remainder = a % b +floor_division = a // b +exponential = a ** b + +# 应该使用 sum 而不是 total,但 sum 是一个内置函数 - 尽量避免覆盖内置函数 +print(total) # 如果不打印标签字符串,就不知道值是怎么计算出来的 +print('a + b = ', total) +print('a - b = ', diff) +print('a * b = ', product) +print('a / b = ', division) +print('a % b = ', remainder) +print('a // b = ', floor_division) +print('a ** b = ', exponentiation) +``` + +**示例:** + +```py +print('== Addition, Subtraction, Multiplication, Division, Modulus ==') + +# 声明变量,并把声明语句放在一起 +num_one = 3 +num_two = 4 + +# 算术运算 +total = num_one + num_two +diff = num_two - num_one +product = num_one * num_two +div = num_two / num_one +remainder = num_two % num_one + +# 使用标签打印值 +print('total: ', total) +print('difference: ', diff) +print('product: ', product) +print('division: ', div) +print('remainder: ', remainder) +``` + +让我们开始使用小数点并开始利用我们已经知道的知识来计算(面积、体积、密度、重量、周长、距离、力)。 + +**示例:** + +```py +# 计算圆的面积 +radius = 10 # 圆的半径 +area_of_circle = 3.14 * radius ** 2 # 两个 * 符号表示指数或幂 +print('Area of a circle:', area_of_circle) + +# 计算矩形面积 +length = 10 +width = 20 +area_of_rectangle = length * width +print('Area of rectangle:', area_of_rectangle) + +# 计算物体重量 +mass = 75 +gravity = 9.81 +weight = mass * gravity +print(weight, 'N') # 为重量添加单位 + +# 计算液体密度 +mass = 75 # 单位是 Kg +volume = 0.075 # 单位是 m³ +density = mass / volume # 1000 Kg/m³ + +``` + +### 比较运算符 + +在编程中,我们使用比较运算符来比较两个值。我们检查一个值是否大于或小于或等于另一个值。下表显示了 Python 比较运算符,摘自 [w3shool](https://www.w3schools.com/python/python_operators.asp)。 + +![Comparison Operators](../images/comparison_operators.png) +**示例:比较运算符** + +```py +print(3 > 2) # True, 因为3大于2 +print(3 >= 2) # True, 因为3大于2 +print(3 < 2) # False, 因为3大于2 +print(2 < 3) # True, 因为2小于3 +print(2 <= 3) # True, 因为2小于3 +print(3 == 2) # False, 因为3不等于2 +print(3 != 2) # True, 因为3不等于2 +print(len('mango') == len('avocado')) # False +print(len('mango') != len('avocado')) # True +print(len('mango') < len('avocado')) # True +print(len('milk') != len('meat')) # False +print(len('milk') == len('meat')) # True +print(len('tomato') == len('potato')) # True +print(len('python') > len('dragon')) # False + + +# 比较得到 True 或者 False + +print('True == True: ', True == True) +print('True == False: ', True == False) +print('False == False:', False == False) +``` + +除了上述比较运算符之外,Python 还使用: + +- _is_: 如果变量相等,返回 True(x is y) +- _is not_: 如果变量不相等,返回 True(x is not y) +- _in_: 如果列表包含某变量,返回 True(x in y) +- _not in_: 如果列表不包含某变量(x in y) + +```py +print('1 is 1', 1 is 1) # True - 因为值相等 +print('1 is not 2', 1 is not 2) # True - 因为值不相等 +print('A in Asabeneh', 'A' in 'Asabeneh') # True - 字符串中含有元素 A +print('B in Asabeneh', 'B' in 'Asabeneh') # False - 没有大写字母 B +print('coding' in 'coding for all') # True - 因为 coding 都在 'coding for all' 中 +print('a in an:', 'a' in 'an') # True +print('4 is 2 ** 2:', 4 is 2 ** 2) # True +``` + +### 逻辑运算符 + +不像其他的编程语言,Python 使用关键字 _and_、_or_ 和 _not_ 作为逻辑运算符。逻辑运算符用于组合条件语句: + +![Logical Operators](../images/logical_operators.png) + +```py +print(3 > 2 and 4 > 3) # True - 因为两个语句都是 True +print(3 > 2 and 4 < 3) # False - 因为其中一个语句是 False +print(3 < 2 and 4 < 3) # False - 因为两个语句都是 False +print('True and True: ', True and True) +print(3 > 2 or 4 > 3) # True - 因为两个语句都是 True +print(3 > 2 or 4 < 3) # True - 因为其中一个语句是 True +print(3 < 2 or 4 < 3) # False - 因为两个语句都是 False +print('True or False:', True or False) +print(not 3 > 2) # False - 因为 3 > 2 是 True, not True 得到 False +print(not True) # False - not 运算符把 True 改为 False +print(not False) # True +print(not not True) # True +print(not not False) # False + +``` + +🌕 精力充沛!你刚刚完成了第 3 天的挑战,在通往伟大的道路上又前进了三步。现在做一些练习来锻练你的大脑和肌肉。 + + +## 💻 练习 - 第三天 + +1. 声明一个值是你年龄的整型变量 +2. 声明一个值是你身高的浮点型变量 +3. 声明一个值是复数变量 +4. 编写一个脚本,提示用户输入三角形的底和高,并计算这个三角形的面积(面积 = 0.5 x b x h)。 + +```py + 输入底: 20 + 输入高: 10 + 三角形的面积是 100 +``` + +5. 编写一个脚本,提示用户输入三角形的边 a、边 b 和边 c。计算三角形的周长(周长 = a + b + c)。 + +```py + 输入边 a: 5 + 输入边 b: 4 + 输入边 c: 3 + 三角形的周长是 12 +``` +6. 提示用户输入矩形的长度和宽度。计算其面积(面积 = 长 x 宽)和周长(周长 = 2 x (长 + 宽)) +7. 提示用户输入圆的半径。计算面积(面积 = pi x r x r)和周长(周长 = 2 x pi x r),其中 pi = 3.14。 +8. 计算 y = 2x -2 的斜率、x 截距和 y 截距 +9. 斜率是 (m = y2-y1/x2-x1)。找到点 (2, 2) 和点 (6,10) 之间的斜率和[欧几里得距离](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.)。 +10. 比较练习 8 和练习 9 中的斜率。 +11. 计算 y 的值(y = x^2 + 6x + 9)。尝试使用不同的 x 值,并找出 y 何时为 0。 +12. 求出 'python' 和 'dragon' 的长度,并进行一个假的比较语句。 +13. 使用 _and_ 运算符检查 'python' 和 'dragon' 中是否都有 'on'。 +14. _I hope this course is not full of jargon_。使用 _in_ 运算符检查句子中是否有 _jargon_。 +15. 'dragon' 和 'python' 中都没有 'on'。 +16. 找到文本 _python_ 的长度,并将该值转换为浮点数,然后将其转换为字符串。 +17. 偶数可以被 2 整除,余数为零。如何使用 Python 检查一个数字是偶数还是奇数? +18. 检查 7 除以 3 的Floor除法是否等于 2.7 的整数转换值。 +19. 检查 '10' 的类型是否等于 10 的类型。 +20. 检查 int('9.8') 是否等于 10。 +21. 编写一个脚本,提示用户输入工时和时薪。计算用户的工资。 + +```py +输入工时: 40 +输入时薪: 28 +你每周的薪资是 1120 +``` + + +22. 编写一个脚本,提示用户输入年数。计算一个人可以活多少秒。假设一个人可以活一百年 + +```py +输入你已经活了多少年: 100 +你已经活了 3153600000 秒. +``` + +23. 编写一个 Python 脚本,显示以下表格 + + +```py +1 1 1 1 1 +2 1 2 4 8 +3 1 3 9 27 +4 1 4 16 64 +5 1 5 25 125 +``` + +🎉 恭喜 ! 🎉 + +[<< 第二天](./02_variables_builtin_functions.md) | [第四天 >>](./04_strings.md) diff --git a/Chinese/04_strings.md b/Chinese/04_strings.md new file mode 100644 index 000000000..aa2c83f59 --- /dev/null +++ b/Chinese/04_strings.md @@ -0,0 +1,609 @@ +
+

30 天 Python:第四天 - Strings

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[<< 第三天](./03_operators.md) | [第五天 >>](./05_lists.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +阅读大约需要:20m + +- [第四天](#第四天) + - [字符串](#字符串) + - [创建字符串](#创建字符串) + - [字符串串联](#字符串串联) + - [字符串中的转译序列](#字符串中的转译序列) + - [字符串格式化](#字符串格式化) + - [传统风格字符串格式化 (% 操作符)](#传统风格字符串格式化--操作符) + - [新式字符串格式化 (str.format)](#新式字符串格式化-strformat) + - [字符串插值 / f-Strings (Python 3.6+)](#字符串插值--f-strings-python-36) + - [Python 字符串是字符序列](#python-字符串是字符序列) + - [拆解字符](#拆解字符) + - [通过索引获取字符串中的字符](#通过索引获取字符串中的字符) + - [字符串切片](#字符串切片) + - [字符串反转](#字符串反转) + - [切片时跳过字符](#切片时跳过字符) + - [字符串方法](#字符串方法) + - [💻 练习 - 第四天](#-练习---第四天) + +# 第四天 + +## 字符串 + +文本是一种字符串数据类型。任何以文本形式书写的数据类型都是字符串。任何用单引号、双引号或三引号括起来的数据都是字符串。有很多方法和内置函数来处理字符串类型的数据。使用 len() 方法获取字符串的长度。 + +### 创建字符串 + +```py +letter = 'P' # 字符串可以是一个字符,也可以是一堆文字 +print(letter) # P +print(len(letter)) # 1 +greeting = 'Hello, World!' # 字符串使用单引号或双引号构建,"Hello, World!" +print(greeting) # Hello, World! +print(len(greeting)) # 13 +sentence = "I hope you are enjoying 30 days of Python Challenge" +print(sentence) +``` + +多行字符串使用三个单引号 (''') 或者三个双引号 (""") 创建。 以下为示例: + +```py +multiline_string = '''I am a teacher and enjoy teaching. +I didn't find anything as rewarding as empowering people. +That is why I created 30 days of python.''' +print(multiline_string) + +# 换种方式 +multiline_string = """I am a teacher and enjoy teaching. +I didn't find anything as rewarding as empowering people. +That is why I created 30 days of python.""" +print(multiline_string) +``` + +### 字符串串联 + +我们可以将字符串连接在一起。合并或连接字符串称为串联。请看下面的示例: + +```py + +first_name = 'Asabeneh' +last_name = 'Yetayeh' +space = ' ' +full_name = first_name + space + last_name +print(full_name) # Asabeneh Yetayeh +# 使用 len() 内置函数获取字符串的长度 +print(len(first_name)) # 8 +print(len(last_name)) # 7 +print(len(first_name) > len(last_name)) # True +print(len(full_name)) # 16 +``` + +### 字符串中的转译序列 + +在 Python 和其他编程语言中,\ 后跟一个字符是转义序列。以下是一些常见的转义序列: + +- \n: 换行 +- \t: 制表符(4个空格) +- \\\\: 反斜杠 +- \\': 单引号 +- \\": 双引号 + +现在,让我们看看上面的转义序列的用法和示例。 + +```py +print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # 换行 +print('Days\tTopics\tExercises') # 增加一个制表符 +print('Day 1\t5\t5') +print('Day 2\t6\t20') +print('Day 3\t5\t23') +print('Day 4\t1\t35') +print('This is a backslash symbol (\\)') # 输出反斜杠 +print('In every programming language it starts with \"Hello, World!\"') # 在单引号里写双引号 + +# 输出 +I hope every one is enjoying the Python Challenge. +Are you ? +Days Topics Exercises +Day 1 5 5 +Day 2 6 20 +Day 3 5 23 +Day 4 1 35 +This is a backslash symbol (\) +In every programming language it starts with "Hello, World!" +``` + +### 字符串格式化 + +#### 传统风格字符串格式化 (% 操作符) + + +在 Python 中有许多格式化字符串的方法。本节,我们将介绍其中一些方法。 +“%”运算符用于格式化包含在“元组”(固定大小列表)中的一组变量,以及格式字符串,其中包含普通文本以及“参数说明符”、特殊符号如“%s”、“%d”、“%f”、“%.数字f”。 + +- %s - 字符串 (或者任何可以用字符串表述的对象,例如数字) +- %d - 整型 +- %f - 浮点型 +- "%.小数位数f" - 固定精度的浮点数 + +```py +# 仅字符串 +first_name = 'Asabeneh' +last_name = 'Yetayeh' +language = 'Python' +formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language) +print(formated_string) + +# 字符串和数字 +radius = 10 +pi = 3.14 +area = pi * radius ** 2 +formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 表示小数点后的 2 位有效数字 + +python_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas'] +formated_string = 'The following are python libraries:%s' % (python_libraries) +print(formated_string) # 输出 "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']" +``` + +#### 新式字符串格式化 (str.format) + +这种格式化方式是在 Python 3 中引入的。 + +```py + +first_name = 'Asabeneh' +last_name = 'Yetayeh' +language = 'Python' +formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language) +print(formated_string) +a = 4 +b = 3 + +print('{} + {} = {}'.format(a, b, a + b)) +print('{} - {} = {}'.format(a, b, a - b)) +print('{} * {} = {}'.format(a, b, a * b)) +print('{} / {} = {:.2f}'.format(a, b, a / b)) # 限制保留两位小数 +print('{} % {} = {}'.format(a, b, a % b)) +print('{} // {} = {}'.format(a, b, a // b)) +print('{} ** {} = {}'.format(a, b, a ** b)) + +# 输出 +4 + 3 = 7 +4 - 3 = 1 +4 * 3 = 12 +4 / 3 = 1.33 +4 % 3 = 1 +4 // 3 = 1 +4 ** 3 = 64 + +# 字符串和数字 +radius = 10 +pi = 3.14 +area = pi * radius ** 2 +formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 保留两位小数 +print(formated_string) + +``` + +#### 字符串插值 / f-Strings (Python 3.6+) + +另一种新的字符串格式化是字符串插值,f-strings。字符串以 f 开头,我们可以在相应的位置注入数据。 + +```py +a = 4 +b = 3 +print(f'{a} + {b} = {a +b}') +print(f'{a} - {b} = {a - b}') +print(f'{a} * {b} = {a * b}') +print(f'{a} / {b} = {a / b:.2f}') +print(f'{a} % {b} = {a % b}') +print(f'{a} // {b} = {a // b}') +print(f'{a} ** {b} = {a ** b}') +``` + +### Python 字符串是字符序列 + +Python 字符串是字符序列,与其他 Python 有序对象 - 列表和元组 - 共享基本访问方法。从字符串中提取单个字符的最简单方法(以及从任何序列中提取单个成员的方法)是将它们解压缩到相应的变量中。 + +#### 拆解字符 + +``` +language = 'Python' +a,b,c,d,e,f = language # 拆解字符串中的字符并赋值给变量 +print(a) # P +print(b) # y +print(c) # t +print(d) # h +print(e) # o +print(f) # n +``` + +#### 通过索引获取字符串中的字符 + +在编程中,计数从零开始。因此,字符串的第一个字母位于零索引处,字符串的最后一个字母位于字符串长度减一处。 + +![String index](../images/string_index.png) + +```py +language = 'Python' +first_letter = language[0] +print(first_letter) # P +second_letter = language[1] +print(second_letter) # y +last_index = len(language) - 1 +last_letter = language[last_index] +print(last_letter) # n +``` + +如果我们想从右边开始,我们可以使用负索引。-1 是最后一个索引。 + +```py +language = 'Python' +last_letter = language[-1] +print(last_letter) # n +second_last = language[-2] +print(second_last) # o +``` + +#### 字符串切片 + +在 Python 中,我们可以将字符串切片为子字符串。 + +```py +language = 'Python' +first_three = language[0:3] # 从零索引开始,直到 3 但不包括 3 +print(first_three) #Pyt +last_three = language[3:6] +print(last_three) # hon +# 另一种方式 +last_three = language[-3:] +print(last_three) # hon +last_three = language[3:] +print(last_three) # hon +``` + +#### 字符串反转 + +我们可以轻松地反转字符串。 + +```py +greeting = 'Hello, World!' +print(greeting[::-1]) # !dlroW ,olleH +``` + +#### 切片时跳过字符 + +通过将步长参数传递给切片方法,可以在切片时跳过字符。 + + +```py +language = 'Python' +pto = language[0:6:2] # +print(pto) # Pto +``` + +### 字符串方法 + +有许多字符串方法可以让我们格式化字符串。在下面的示例中,我们使用其中一些: + +- capitalize(): 将字符串中的第一个字符转换为大写字母 + +```py +challenge = 'thirty days of python' +print(challenge.capitalize()) # 'Thirty days of python' +``` + +- count(): 返回字符串中子字符串的出现次数,count(子字符串,start=..,end=..)。start 是计数的起始索引,end 是计数的最后一个索引。 + +```py +challenge = 'thirty days of python' +print(challenge.count('y')) # 3 +print(challenge.count('y', 7, 14)) # 1, +print(challenge.count('th')) # 2` +``` + +- endswith(): 判断字符串是否以特定的子字符串结尾,返回 True 或 False + +```py +challenge = 'thirty days of python' +print(challenge.endswith('on')) # True +print(challenge.endswith('tion')) # False +``` + +- expandtabs(): 用空格替换制表符,默认制表符大小为 8。它接受制表符大小参数 + +```py +challenge = 'thirty\tdays\tof\tpython' +print(challenge.expandtabs()) # 'thirty days of python' +print(challenge.expandtabs(10)) # 'thirty days of python' +``` + +- find(): 返回子字符串第一次出现的索引,如果未找到则返回 -1 + +```py +challenge = 'thirty days of python' +print(challenge.find('y')) # 5 +print(challenge.find('th')) # 0 +``` + +- rfind(): 返回子字符串最后一次出现的索引,如果未找到则返回 -1 + +```py +challenge = 'thirty days of python' +print(challenge.rfind('y')) # 16 +print(challenge.rfind('th')) # 17 +``` + +- format(): 将字符串格式化为更美观的输出 +有关字符串格式化的更多信息,请查看此[链接](https://www.programiz.com/python-programming/methods/string/format) + +```py +first_name = 'Asabeneh' +last_name = 'Yetayeh' +age = 250 +job = 'teacher' +country = 'Finland' +sentence = 'I am {} {}. I am a {}. I am {} years old. I live in {}.'.format(first_name, last_name, age, job, country) +print(sentence) # I am Asabeneh Yetayeh. I am 250 years old. I am a teacher. I live in Finland. + +radius = 10 +pi = 3.14 +area = pi * radius ** 2 +result = 'The area of a circle with radius {} is {}'.format(str(radius), str(area)) +print(result) # The area of a circle with radius 10 is 314 +``` + +- index(): 返回子字符串的最小索引,附加参数表示起始和结束索引(默认为 0,字符串长度为 - 1)。如果未找到子字符串,则会引发 valueError。 + +```py +challenge = 'thirty days of python' +sub_string = 'da' +print(challenge.index(sub_string)) # 7 +print(challenge.index(sub_string, 9)) # error +``` + +- rindex(): 返回子字符串的最大索引,附加参数表示起始和结束索引(默认为 0,字符串长度为 - 1)。 + +```py +challenge = 'thirty days of python' +sub_string = 'da' +print(challenge.rindex(sub_string)) # 8 +print(challenge.rindex(sub_string, 9)) # error +``` + +- isalnum(): 判断字符串字符是否都是字母数字字符 + +```py +challenge = 'ThirtyDaysPython' +print(challenge.isalnum()) # True + +challenge = '30DaysPython' +print(challenge.isalnum()) # True + +challenge = 'thirty days of python' +print(challenge.isalnum()) # False, 空格不是字母字符 + +challenge = 'thirty days of python 2019' +print(challenge.isalnum()) # False +``` + +- isalpha(): 判断字符串字符是否都是字母字符 (a-z and A-Z) + +```py +challenge = 'thirty days of python' +print(challenge.isalpha()) # False, 空格不是字母字符 +challenge = 'ThirtyDaysPython' +print(challenge.isalpha()) # True +num = '123' +print(num.isalpha()) # False +``` + +- isdecimal(): 判断符串中的所有字符是否都是十进制 (0-9) + +```py +challenge = 'thirty days of python' +print(challenge.isdecimal()) # False +challenge = '123' +print(challenge.isdecimal()) # True +challenge = '\u00B2' +print(challenge.isdigit()) # False +challenge = '12 3' +print(challenge.isdecimal()) # False, 含有空格 +``` + +- isdigit(): 判断字符串中的所有字符是否都是数字(0-9 和一些其他表示数字的 Unicode 字符) + +```py +challenge = 'Thirty' +print(challenge.isdigit()) # False +challenge = '30' +print(challenge.isdigit()) # True +challenge = '\u00B2' +print(challenge.isdigit()) # True +``` + +- isnumeric(): 判断字符串中的所有字符是否都是数字或与数字相关(就像 isdigit(),只是接受更多符号,如 ½) + +```py +num = '10' +print(num.isnumeric()) # True +num = '\u00BD' # ½ +print(num.isnumeric()) # True +num = '10.5' +print(num.isnumeric()) # False +``` + +- isidentifier(): 判断有效的标识符 - 检查字符串是否是有效的变量名 + +```py +challenge = '30DaysOfPython' +print(challenge.isidentifier()) # False, 因为以数字开头 +challenge = 'thirty_days_of_python' +print(challenge.isidentifier()) # True +``` + +- islower(): 判断字符串中的所有字母是否都是小写 + +```py +challenge = 'thirty days of python' +print(challenge.islower()) # True +challenge = 'Thirty days of python' +print(challenge.islower()) # False +``` + +- isupper(): 判断字符串中的所有字母是否都是大写 + +```py +challenge = 'thirty days of python' +print(challenge.isupper()) # False +challenge = 'THIRTY DAYS OF PYTHON' +print(challenge.isupper()) # True +``` + +- join(): 返回连接后的字符串 + +```py +web_tech = ['HTML', 'CSS', 'JavaScript', 'React'] +result = ' '.join(web_tech) +print(result) # 'HTML CSS JavaScript React' +``` + +```py +web_tech = ['HTML', 'CSS', 'JavaScript', 'React'] +result = '# '.join(web_tech) +print(result) # 'HTML# CSS# JavaScript# React' +``` + +- strip(): 删除从字符串开头到结尾的所有给定字符 + +```py +challenge = 'thirty days of pythoonnn' +print(challenge.strip('noth')) # 'irty days of py' +``` + +- replace(): 用给定的字符串替换子字符串 + +```py +challenge = 'thirty days of python' +print(challenge.replace('python', 'coding')) # 'thirty days of coding' +``` + +- split(): 使用给定的字符串或空格作为分隔符来拆分字符串 + +```py +challenge = 'thirty days of python' +print(challenge.split()) # ['thirty', 'days', 'of', 'python'] +challenge = 'thirty, days, of, python' +print(challenge.split(', ')) # ['thirty', 'days', 'of', 'python'] +``` + +- title(): 返回标题大小写的字符串 + +```py +challenge = 'thirty days of python' +print(challenge.title()) # Thirty Days Of Python +``` + +- swapcase(): 将所有大写字符转换为小写字符,将所有小写字符转换为大写字符 + +```py +challenge = 'thirty days of python' +print(challenge.swapcase()) # THIRTY DAYS OF PYTHON +challenge = 'Thirty Days Of Python' +print(challenge.swapcase()) # tHIRTY dAYS oF pYTHON +``` + +- startswith(): 判断字符串是否以指定字符串开头 + +```py +challenge = 'thirty days of python' +print(challenge.startswith('thirty')) # True + +challenge = '30 days of python' +print(challenge.startswith('thirty')) # False +``` + +🌕 你是一个非凡的人,你拥有非凡的潜力。你刚刚完成了第 4 天的挑战,你在成为伟人的路上已经迈出四步。现在做一些练习来锻练你的大脑和肌肉。 + +## 💻 练习 - 第四天 + +1. 将字符串 'Thirty', 'Days', 'Of', 'Python' 连接为一个字符串 'Thirty Days Of Python'。 +2. 将字符串 'Coding', 'For', 'All' 连接为一个字符串 'Coding For All'。 +3. 声明一个名为 company 的变量,并将其赋值为初始值 "Coding For All"。 +4. 使用 _print()_ 打印变量 company。 +5. 使用 _len()_ 方法和 _print()_ 打印 company 字符串的长度。 +6. 使用 _upper()_ 方法将所有字符更改为大写字母。 +7. 使用 _lower()_ 方法将所有字符更改为小写字母。 +8. 使用 _capitalize()_、_title()_ 和 _swapcase()_ 方法格式化字符串 _Coding For All_。 +9. 切片出 _Coding For All_ 字符串的第一个单词。 +10. 使用 index、find 或其他方法检查 _Coding For All_ 字符串是否包含单词 Coding。 +11. 将字符串 'Coding For All' 中的单词 coding 替换为 Python。 +12. 使用 replace 方法或其他方法将 Python for Everyone 替换为 Python for All。 +13. 使用空格作为分隔符拆分字符串 'Coding For All'。 +14. 在逗号处拆分字符串 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon'。 +15. 字符串 _Coding For All_ 中索引 0 处的字符是什么。 +16. 字符串 _Coding For All_ 的最后一个索引是什么。 +17. 字符串 _Coding For All_ 中索引 10 处的字符是什么。 +18. 为字符串 'Python For Everyone' 创建首字母缩略词或缩写 +19. 为名称 'Coding For All' 创建首字母缩略词或缩写。 +20. 使用索引确定 'Coding For All' 中 C 第一次出现的位置。 +21. 使用索引确定 'Coding For All' 中 F 第一次出现的位置。 +22. 使用 rfind 确定 'Coding For All People' 中 l 最后一次出现的位置。 +23. 使用 index 或 find 查找以下句子中单词 'because' 第一次出现的位置:'You cannot end a sentence with because because because is a conjunction' +24. 使用 rindex 查找以下句子中单词 because 最后一次出现的位置:'You cannot end a sentence with because because because is a conjunction' +25. 删除以下句子中短语 'because because because':'You cannot end a sentence with because because because is a conjunction' +26. 查找以下句子中单词 'because' 第一次出现的位置:'You cannot end a sentence with because because because is a conjunction' +27. 删除以下句子中短语 'because 因为 because':'You cannot end a sentence with because because because is a conjunction' +28. '\'Coding For All' 是否以子字符串 _Coding_ 开头? +29. 'Coding For All' 是否以子字符串 _coding_ 结尾? +30. '   Coding For All      '  , 删除给定字符串中左右空格。 +31. 当我们使用方法 isidentifier() 时,下列哪一个变量返回 True: + - 30DaysOfPython + - thirty_days_of_python +32. 以下列表包含一些 Python 库的名称:['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']。使用空格连接字符串。 +33. 使用换行转义序列分隔以下句子。 + ```py + I am enjoying this challenge. + I just wonder what is next. + ``` +34. 使用制表符专业序列输出以下内容。 + ```py + Name Age Country City + Asabeneh 250 Finland Helsinki + ``` +35. 使用字符串格式化方法输出以下内容: + +```sh +radius = 10 +area = 3.14 * radius ** 2 +The area of a circle with radius 10 is 314 meters square. +``` + +36. 使用字符串格式化方法输出以下内容: + +```sh +8 + 6 = 14 +8 - 6 = 2 +8 * 6 = 48 +8 / 6 = 1.33 +8 % 6 = 2 +8 // 6 = 1 +8 ** 6 = 262144 +``` + +🎉 恭喜 ! 🎉 + +[<< 第三天](./03_operators.md) | [第五天 >>](./05_lists.md) + + diff --git a/Chinese/05_lists.md b/Chinese/05_lists.md new file mode 100644 index 000000000..e9842e781 --- /dev/null +++ b/Chinese/05_lists.md @@ -0,0 +1,596 @@ +
+

30 天 Python:第五天 - Lists

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[<< 第四天](./04_strings.md) | [第六天 >>](../06_Day_Tuples/06_tuples.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [第五天](#第五天) + - [列表](#列表) + - [如何创建列表](#如何创建列表) + - [使用正索引访问列表项](#使用正索引访问列表项) + - [使用负索引访问列表项](#使用负索引访问列表项) + - [拆解列表项](#拆解列表项) + - [列表切分](#列表切分) + - [修改列表](#修改列表) + - [检索列表项](#检索列表项) + - [添加列表项](#添加列表项) + - [插入列表项](#插入列表项) + - [移除列表项](#移除列表项) + - [使用 Pop 删除列表项](#使用-pop-删除列表项) + - [使用 Del 删除列表项](#使用-del-删除列表项) + - [清空列表项](#清空列表项) + - [列表复制](#列表复制) + - [连接列表](#连接列表) + - [统计列表项](#统计列表项) + - [查找项的索引](#查找项的索引) + - [列表反转](#列表反转) + - [列表排序](#列表排序) + - [💻 练习 - 第五天](#-练习---第五天) + - [练习: 1级](#练习-1级) + - [练习: 2级](#练习-2级) + +# 第五天 + +## 列表 + +Python 中有四种集合数据类型: + +- List:有序且可变的集合。允许重复的成员。 +- Tuple:有序且不可变的集合。允许重复的成员。 +- Set:无序、不可索引且不可变的集合,但我们可以向集合中添加新项。不允许重复的成员。 +- Dictionary:无序、可变且可索引的集合。不允许重复的成员。 + + +列表是不同数据类型的集合,有序且可修改(可变)。列表可以为空,也可以包含不同数据类型的项。 + +### 如何创建列表 + +在 Python 中,我们可以通过两种方式创建列表: + +- 使用内置函数 list() + +```py +# 语法 +lst = list() +``` + +```py +empty_list = list() # 这是一个空列表 +print(len(empty_list)) # 0 +``` +- 使用方括号,[] + +```py +# 语法 +lst = [] +``` + +```py +empty_list = [] # 这是一个空列表 +print(len(empty_list)) # 0 +``` + +具有初始值的列表。我们使用 _len()_ 来检查列表的长度。 + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] # list of fruits +vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # list of vegetables +animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products +web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # list of web technologies +countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] + +# 打印列表及其长度 +print('Fruits:', fruits) +print('Number of fruits:', len(fruits)) +print('Vegetables:', vegetables) +print('Number of vegetables:', len(vegetables)) +print('Animal products:',animal_products) +print('Number of animal products:', len(animal_products)) +print('Web technologies:', web_techs) +print('Number of web technologies:', len(web_techs)) +print('Countries:', countries) +print('Number of countries:', len(countries)) +``` + +```sh +输出 +Fruits: ['banana', 'orange', 'mango', 'lemon'] +Number of fruits: 4 +Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +Number of vegetables: 5 +Animal products: ['milk', 'meat', 'butter', 'yoghurt'] +Number of animal products: 4 +Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] +Number of web technologies: 7 +Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] +Number of countries: 5 +``` + +- 列表可以包含不同数据类型的项 + +```py + lst = ['Asabeneh', 250, True, {'country':'Finland', 'city':'Helsinki'}] # 包含不同数据类型的列表 +``` + + +### 使用正索引访问列表项 + +我们使用索引访问列表中的每个项。列表索引从 0 开始。下图清楚地显示了索引从哪里开始。 + +![List index](../images/list_index.png) + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +first_fruit = fruits[0] # 我们正在使用其索引访问第一项 +print(first_fruit) # banana +second_fruit = fruits[1] +print(second_fruit) # orange +last_fruit = fruits[3] +print(last_fruit) # lemon +# Last index +last_index = len(fruits) - 1 +last_fruit = fruits[last_index] +``` + +### 使用负索引访问列表项 + +负索引意味着从末尾开始,-1 指的是最后一项,-2 指的是倒数第二项。 + +![List negative indexing](../images/list_negative_indexing.png) + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +first_fruit = fruits[-4] +last_fruit = fruits[-1] +second_last = fruits[-2] +print(first_fruit) # banana +print(last_fruit) # lemon +print(second_last) # mango +``` + +### 拆解列表项 + +```py +lst = ['item1','item2','item3', 'item4', 'item5'] +first_item, second_item, third_item, *rest = lst +print(first_item) # item1 +print(second_item) # item2 +print(third_item) # item3 +print(rest) # ['item4', 'item5'] + +``` + +```py +# 示例一 +fruits = ['banana', 'orange', 'mango', 'lemon','lime','apple'] +first_fruit, second_fruit, third_fruit, *rest = fruits +print(first_fruit) # banana +print(second_fruit) # orange +print(third_fruit) # mango +print(rest) # ['lemon','lime','apple'] +# 示例二 +first, second, third,*rest, tenth = [1,2,3,4,5,6,7,8,9,10] +print(first) # 1 +print(second) # 2 +print(third) # 3 +print(rest) # [4,5,6,7,8,9] +print(tenth) # 10 +# 示例三 +countries = ['Germany', 'France','Belgium','Sweden','Denmark','Finland','Norway','Iceland','Estonia'] +gr, fr, bg, sw, *scandic, es = countries +print(gr) +print(fr) +print(bg) +print(sw) +print(scandic) +print(es) +``` + +### 列表切分 + +- 正索引:我们可以通过指定开始、结束和步长来指定一系列正索引,返回值将是一个新列表。 (开始默认值为 0,结束默认值为 len(lst) - 1(最后一项),步长默认值为 1) + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +all_fruits = fruits[0:4] # 返回所有项 +#与上面返回值相同 +all_fruits = fruits[0:] # 如果不指定结束索引,将返回从开始到最后一项的所有项 +orange_and_mango = fruits[1:3] # 不包含第一项 +orange_mango_lemon = fruits[1:] +orange_and_lemon = fruits[::2] # 我们使用了第三个参数,步长。 每两项取一条 - ['banana', 'mango'] +``` + +- 负索引:我们可以通过指定开始、结束和步长来指定一系列负索引,返回值将是一个新列表。 + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +all_fruits = fruits[-4:] # 返回所有项 +orange_and_mango = fruits[-3:-1] # 不包含最后一项,['orange', 'mango'] +orange_mango_lemon = fruits[-3:] # 返回从-3到末尾的项,['orange', 'mango', 'lemon'] +reverse_fruits = fruits[::-1] # 负步长将按相反顺序排列列表,['lemon', 'mango', 'orange', 'banana'] +``` + +### 修改列表 + +列表是一个可变或可修改的有序集合。下面我们修改 fruit 列表。 + + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits[0] = 'avocado' +print(fruits) # ['avocado', 'orange', 'mango', 'lemon'] +fruits[1] = 'apple' +print(fruits) # ['avocado', 'apple', 'mango', 'lemon'] +last_index = len(fruits) - 1 +fruits[last_index] = 'lime' +print(fruits) # ['avocado', 'apple', 'mango', 'lime'] +``` + +### 检索列表项 + +使用 *in* 运算符检查列表项是否为列表的成员。请参阅下面的示例。 + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +does_exist = 'banana' in fruits +print(does_exist) # True +does_exist = 'lime' in fruits +print(does_exist) # False +``` + +### 添加列表项 + +要将项添加到现有列表的末尾,我们使用 *append()* 方法。 + +```py +# 语法 +lst = list() +lst.append(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.append('apple') +print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple'] +fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime'] +print(fruits) +``` + +### 插入列表项 + +我们可以使用 *insert()* 方法在列表中的指定索引处插入单个项。请注意,其他项将向右移动。*insert()* 方法接受两个参数:索引和要插入的项。 + + +```py +# 语法 +lst = ['item1', 'item2'] +lst.insert(index, item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.insert(2, 'apple') # 在 orange 。 mango 中插入 apple +print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon'] +fruits.insert(3, 'lime') # ['banana', 'orange', 'apple', 'lime', 'mango', 'lemon'] +print(fruits) +``` + +### 移除列表项 + +- 使用 *remove()* 方法从列表中删除指定的项 + +```py +# 语法 +lst = ['item1', 'item2'] +lst.remove(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon', 'banana'] +fruits.remove('banana') +print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - 此方法删除列表中第一次出现的项 +fruits.remove('lemon') +print(fruits) # ['orange', 'mango', 'banana'] +``` + +### 使用 Pop 删除列表项 + +使用 *pop()* 方法删除指定索引(如果未指定索引,则删除最后一项): + +```py +# 语法 +lst = ['item1', 'item2'] +lst.pop() # 最后一项 +lst.pop(index) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.pop() +print(fruits) # ['banana', 'orange', 'mango'] + +fruits.pop(0) +print(fruits) # ['orange', 'mango'] +``` + +### 使用 Del 删除列表项 + +使用 *del* 关键字删除指定索引,也可以用于删除索引范围内的项。它还可以完全删除列表 + + +```py +# 语法 +lst = ['item1', 'item2'] +del lst[index] # 只删除一项 +del lst # 删除整个列表 +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon', 'kiwi', 'lime'] +del fruits[0] +print(fruits) # ['orange', 'mango', 'lemon', 'kiwi', 'lime'] +del fruits[1] +print(fruits) # ['orange', 'lemon', 'kiwi', 'lime'] +del fruits[1:3] # 这将删除给定索引之间的项,因此不会删除索引为 3 的项! +print(fruits) # ['orange', 'lime'] +del fruits +print(fruits) # 这里会提示: NameError: name 'fruits' is not defined +``` + +### 清空列表项 + +使用 *clear()* 方法清空列表: + +```py +# 语法 +lst = ['item1', 'item2'] +lst.clear() +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.clear() +print(fruits) # [] +``` + +### 列表复制 + +可以通过将其重新分配给新变量来复制列表: list2 = list1。现在,list2 是 list1 的引用,我们对 list2 进行的任何更改也将修改原始的 list1。但是有很多时候我们不想修改原始的列表,而是想要一个不同的副本。为了避免这个问题,我们使用 *copy()*。 + +```py +# 语法 +lst = ['item1', 'item2'] +lst_copy = lst.copy() +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits_copy = fruits.copy() +print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon'] +``` + +### 连接列表 + +有几种方法可以连接或连接两个或多个列表。 + +- 加号 (+) + +```py +# 语法 +list3 = list1 + list2 +``` + +```py +positive_numbers = [1, 2, 3, 4, 5] +zero = [0] +negative_numbers = [-5,-4,-3,-2,-1] +integers = negative_numbers + zero + positive_numbers +print(integers) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] +fruits = ['banana', 'orange', 'mango', 'lemon'] +vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +fruits_and_vegetables = fruits + vegetables +print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +``` + +- 使用 *extend()* 方法 +*extend()* 方法可以将列表附加到列表中。请参阅下面的示例。 + +```py +# 语法 +list1 = ['item1', 'item2'] +list2 = ['item3', 'item4', 'item5'] +list1.extend(list2) +``` + +```py +num1 = [0, 1, 2, 3] +num2= [4, 5, 6] +num1.extend(num2) +print('Numbers:', num1) # Numbers: [0, 1, 2, 3, 4, 5, 6] +negative_numbers = [-5,-4,-3,-2,-1] +positive_numbers = [1, 2, 3,4,5] +zero = [0] + +negative_numbers.extend(zero) +negative_numbers.extend(positive_numbers) +print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] +fruits = ['banana', 'orange', 'mango', 'lemon'] +vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +fruits.extend(vegetables) +print('Fruits and vegetables:', fruits ) # Fruits and vegetables: ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] +``` + +### 统计列表项 + +使用 *count()* 方法返回列表中指定项出现的次数: + + +```py +# 语法 +lst = ['item1', 'item2'] +lst.count(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +print(fruits.count('orange')) # 1 +ages = [22, 19, 24, 25, 26, 24, 25, 24] +print(ages.count(24)) # 3 +``` + +### 查找项的索引 + +*index()* 方法返回列表中项的索引: + +```py +# 语法 +lst = ['item1', 'item2'] +lst.index(item) +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +print(fruits.index('orange')) # 1 +ages = [22, 19, 24, 25, 26, 24, 25, 24] +print(ages.index(24)) # 2, 第一次出现 +``` + +### 列表反转 + +使用 *reverse()* 方法反转列表的顺序。 + +```py +# 语法 +lst = ['item1', 'item2'] +lst.reverse() + +``` + +```py +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits.reverse() +print(fruits) # ['lemon', 'mango', 'orange', 'banana'] +ages = [22, 19, 24, 25, 26, 24, 25, 24] +ages.reverse() +print(ages) # [24, 25, 24, 26, 25, 24, 19, 22] +``` + +### 列表排序 + +要对列表进行排序,我们可以使用 *sort()* 方法或内置函数 *sorted()*。*sort()* 方法将列表项按升序重新排序并修改原始列表。如果 *sort()* 方法的 reverse 参数为 true,则会按降序排列列表。 + +- sort(): 这个方法会修改原始列表 + + ```py + # 语法 + lst = ['item1', 'item2'] + lst.sort() # ascending + lst.sort(reverse=True) # descending + ``` + + **示例:** + + ```py + fruits = ['banana', 'orange', 'mango', 'lemon'] + fruits.sort() + print(fruits) # 按字母排序, ['banana', 'lemon', 'mango', 'orange'] + fruits.sort(reverse=True) + print(fruits) # ['orange', 'mango', 'lemon', 'banana'] + ages = [22, 19, 24, 25, 26, 24, 25, 24] + ages.sort() + print(ages) # [19, 22, 24, 24, 24, 25, 25, 26] + + ages.sort(reverse=True) + print(ages) # [26, 25, 25, 24, 24, 24, 22, 19] + ``` + + sorted(): 不会修改原始列表,而是返回一个新列表 + + **示例:** + + ```py + fruits = ['banana', 'orange', 'mango', 'lemon'] + print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange'] + # Reverse order + fruits = ['banana', 'orange', 'mango', 'lemon'] + fruits = sorted(fruits,reverse=True) + print(fruits) # ['orange', 'mango', 'lemon', 'banana'] + ``` + + + +🌕 你很勤奋,已经取得了很多成就。你刚刚完成了第 5 天的挑战,并且已经朝着伟大的目标迈出了 5 步。现在做一些练习来锻练你的大脑和肌肉。 + +## 💻 练习 - 第五天 + +### 练习: 1级 + +1. 声明一个空列表 +2. 声明一个包含 5 个以上项的列表 +3. 查找列表的长度 +4. 获取列表的第一项、中间项和最后一项 +5. 声明一个名为 mixed_data_types 的列表,包含你的姓名、年龄、身高、婚姻状况和地址 +6. 声明一个名为 it_companies 的列表,并分配初始值 Facebook、Google、Microsoft、Apple、IBM、Oracle 和 Amazon。 +7. 使用 _print()_ 打印列表 +8. 打印列表中的公司数 +9. 打印第一、中间和最后一家公司 +10. 修改其中一家公司的名称后打印列表 +11. 向 it_companies 添加一家 IT 公司 +12. 在公司列表中间插入一家 IT 公司 +13. 将其中一家 it_companies 公司的名称更改为大写(不包括 IBM!) +14. 使用字符串 '#;  ' 连接 it_companies +15. 检查 it_companies 列表中是否存在某个公司。 +16. 使用 sort() 方法对列表进行排序 +17. 使用 reverse() 方法按降序反转列表 +18. 从列表中切分出前 3 家公司 +19. 从列表中切分出最后 3 家公司 +20. 从列表中切分出中间的 IT 公司或公司 +21. 从列表中删除第一家 IT 公司 +22. 从列表中删除中间的 IT 公司或公司 +23. 从列表中删除最后一家 IT 公司 +24. 从列表中删除所有 IT 公司 +25. 销毁 it_companies 列表 +26. 连接以下列表: + + ```py + front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux'] + back_end = ['Node','Express', 'MongoDB'] + ``` +27. 在连接的列表中插入 Python 和 SQL 到变量 full_stack 之后。 + +### 练习: 2级 + +1. 以下是 10 个学生的年龄列表: + +```sh +ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] +``` + +- 对列表进行排序,并找出最大和最小年龄 +- 将最小年龄和最大年龄再次添加到列表中 +- 找到年龄中位数(一个中间项或两个中间项除以二) +- 找到平均年龄(所有项的总和除以它们的数量) +- 找到年龄范围(最大减去最小) +- 比较 (min - average) 和 (max - average) 的值,使用 _abs()_ 方法 + +1. 在 [国家列表](https://github.com/Taki-Ta/30-Days-Of-Python-Simplified_Chinese_Version/tree/master/data/countries.py) 中查找中间的国家 +2. 将国家列表分成两个相等的列表(如果是偶数,如果不是,则第一个半多一个国家) +3. ['China', 'Russia', 'USA', 'Finland', 'Sweden', 'Norway', 'Denmark']。拆解前三个国家和剩下的北欧国家。 + +🎉 恭喜 ! 🎉 + +[<< 第四天](./04_strings.md) | [第六天 >>](../06_Day_Tuples/06_tuples.md) diff --git a/Chinese/README.md b/Chinese/README.md index 4f7aedcb3..e02ba7227 100644 --- a/Chinese/README.md +++ b/Chinese/README.md @@ -3,10 +3,10 @@ | # 天数 | 主题 | | ------ | :--------------------------------------------------------------------------------------: | | 01 | [介绍](./readme.md) | -| 02 | [变量,内置函数](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | -| 03 | [运算符](./03_Day_Operators/03_operators.md) | -| 04 | [字符串](./04_Day_Strings/04_strings.md) | -| 05 | [列表](./05_Day_Lists/05_lists.md) | +| 02 | [变量,内置函数](./02_variables_builtin_functions.md) | +| 03 | [运算符](./03_operators.md) | +| 04 | [字符串](./04_strings.md) | +| 05 | [列表](./05_lists.md) | | 06 | [元组](./06_Day_Tuples/06_tuples.md) | | 07 | [集合](./07_Day_Sets/07_sets.md) | | 08 | [字典](./08_Day_Dictionaries/08_dictionaries.md) | @@ -133,7 +133,7 @@ Python 被各行各业和公司(包括 Google)使用。它被用于开发 We python --version ``` -![Python Version](./images/python_versio.png) +![Python Version](../images/python_versio.png) 如你所见,在终端中,我当前使用的版本是 Python 3.7.5。你的 Python 版本可能与我的不同,但应为 3.6 或更高版本。如果你能看到 Python 版本,很好。Python 已安装在你的机器上。继续下一部分。 @@ -148,35 +148,35 @@ Python Shell 等待用户的 Python 代码。当输入代码时,它会解释 python ``` -![Python Scripting Shell](./images/opening_python_shell.png) +![Python Scripting Shell](../images/opening_python_shell.png) Python 交互式 Shell 已打开,等待你在该符号 >>> 旁边编写 Python 代码(Python 脚本)。编写第一个脚本并点击 Enter。 让我们在 Python 脚本 Shell 中编写第一个脚本。 -![Python script on Python shell](./images/adding_on_python_shell.png) +![Python script on Python shell](../images/adding_on_python_shell.png) 非常好,你已经在 Python 交互式 Shell 中编写了第一个 Python 脚本。如何关闭 Python 交互式 Shell? 要关闭 Shell,请在该符号 >>> 旁边输入命令 **exit()** 并按 Enter。 -![Exit from python shell](./images/exit_from_shell.png) +![Exit from python shell](../images/exit_from_shell.png) 现在你知道如何打开 Python 交互式 Shell 以及如何退出它。 Python 将在你编写 Python 可理解的脚本时提供结果;否则,它将返回错误。让我们故意犯一个错误,看看 Python 返回什么。 -![Invalid Syntax Error](./images/invalid_syntax_error.png) +![Invalid Syntax Error](../images/invalid_syntax_error.png) 如你所见,返回的错误表明 Python 非常智能,它知道我们犯了语法错误:Syntax Error: Invalid Syntax。在 Python 中使用 x 作为乘法是语法错误,因为 (x) 不是 Python 中的有效语法。我们用星号 (\*) 来表示乘法而不是 (x)。返回的错误明确显示了需要修正的地方。 识别和删除程序中的错误的过程称为调试。让我们通过将 \* 替换为 x 来调试它。 -![Fixing Syntax Error](./images/fixing_syntax_error.png) +![Fixing Syntax Error](../images/fixing_syntax_error.png) 我们的错误已修复,代码已执行,并得到了我们期望的结果。作为程序员,你每天都会看到这种类型的错误。了解如何调试是很重要的。为了擅长调试,你必须了解所遇到的错误类型。你可能会遇到的 Python 错误类型有 _SyntaxError_, _IndexError_, _NameError_, _ModuleNotFoundError_, _KeyError_, _ImportError_, _AttributeError_, _TypeError_, _ValueError_, _ZeroDivisionError_ 等等。我们将在后面的部分详细了解不同类型的 Python 错误! 让我们更多地练习如何使用 Python 交互式 Shell。转到终端或命令提示符并输入单词 python。 -![Python Scripting Shell](./images/opening_python_shell.png) +![Python Scripting Shell](../images/opening_python_shell.png) Python 交互式 Shell 已打开。让我们做一些基本的数学运算(加法、减法、乘法、除法、取模、指数运算)。 @@ -203,7 +203,7 @@ A _comment_ 是代码中未被 Python 执行的一部分,注释被 Python 解 # 这是一个python注释,因为它以(#)符号开头 ``` -![Maths on python shell](./images/maths_on_python_shell.png) +![Maths on python shell](../images/maths_on_python_shell.png) 在进入下一部分之前,让我们更多地练习 Python 交互式 Shell。通过在 Shell 中输入 _exit()_ 关闭已打开的 Shell,然后再次打开它,让我们练习如何在 Python Shell 中编写文本。 @@ -213,7 +213,7 @@ A _comment_ 是代码中未被 Python 执行的一部分,注释被 Python 解 Python 交互式 Shell 非常适合测试小的脚本代码,但对于大型项目来说并不适用。在实际的工作环境中,开发人员使用不同的代码编辑器来编写代码。在这个 30 天的 Python 编程挑战中,我们将使用 Visual Studio Code。Visual Studio Code 是一个非常流行的开源文本编辑器。我是 vscode 的粉丝,并推荐下载 Visual Studio Code,但如果你喜欢其他编辑器,可以随意使用。 -[![Visual Studio Code](./images/vscode.png)](https://code.visualstudio.com/) +[![Visual Studio Code](../images/vscode.png)](https://code.visualstudio.com/) 如果你已安装 Visual Studio Code,让我们看看如何使用它。 如果你喜欢视频教程,你可以观看安装和配置 Visual Studio Code 以用于 Python 的[视频教程](https://www.youtube.com/watch?v=bn7Cx4z-vSo) @@ -222,21 +222,21 @@ Python 交互式 Shell 非常适合测试小的脚本代码,但对于大型项 通过双击 Visual Studio 图标打开 Visual Studio Code。打开后,你会看到类似的界面。尝试与标注的图标进行交互。 -![Visual studio Code](./images/vscode_ui.png) +![Visual studio Code](../images/vscode_ui.png) 在桌面上创建一个名为 30DaysOfPython 的文件夹。然后使用 Visual Studio Code 打开它。 -![Opening Project on Visual studio](./images/how_to_open_project_on_vscode.png) +![Opening Project on Visual studio](../images/how_to_open_project_on_vscode.png) -![Opening a project](./images/opening_project.png) +![Opening a project](../images/opening_project.png) 打开后,你会看到在 30DaysOfPython 项目目录中创建文件和文件夹的快捷方式。如下所示,我创建了第一个文件 helloworld.py。你也可以这样做。 -![Creating a python file](./images/helloworld.png) +![Creating a python file](../images/helloworld.png) 经过长时间的编码,你想关闭你的代码编辑器,对吗?这是你关闭已打开项目的方法。 -![Closing project](./images/closing_opened_project.png) +![Closing project](../images/closing_opened_project.png) 恭喜你,完成了开发环境的设置。让我们开始编码。 @@ -250,7 +250,7 @@ Python 脚本可以在 Python 交互式 Shell 或代码编辑器中编写。Pyth 缩进是文本中的空白。在许多语言中,缩进用于提高代码的可读性,但 Python 使用缩进来创建代码块。在其他编程语言中,使用大括号来创建代码块,而不是缩进。在 Python 中编写代码时,一个常见的错误是缩进错误。 -![Indentation Error](./images/indentation.png) +![Indentation Error](../images/indentation.png) ### 注释 @@ -378,7 +378,7 @@ Python 字典对象是以键值对格式存储的无序集合。 要检查某个数据/变量的数据类型,我们使用 **type** 函数。在以下终端中,你将看到不同的 Python 数据类型: -![Checking Data types](./images/checking_data_types.png) +![Checking Data types](../images/checking_data_types.png) ### Python 文件 @@ -414,7 +414,7 @@ print(type((9.8, 3.14, 2.7))) # 元组 要运行 Python 文件,请查看下图。你可以通过在 Visual Studio Code 中点击绿色按钮或在终端中输入 _python helloworld.py_ 来运行 Python 文件。 -![Running python script](./images/running_python_script.png) +![Running python script](../images/running_python_script.png) 🌕 你很棒。你刚刚完成了第 1 天的挑战,你正在迈向伟大。现在做一些练习来锻练你的大脑和肌肉。 @@ -457,4 +457,4 @@ print(type((9.8, 3.14, 2.7))) # 元组 🎉 恭喜 ! 🎉 -[第 2 天 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) +[第 2 天 >>](./02_variables_builtin_functions.md) From 3883f3e336b45ac286a81d52c250f3be64663ea4 Mon Sep 17 00:00:00 2001 From: Taki-Ta Date: Mon, 15 Jul 2024 13:55:29 +0800 Subject: [PATCH 38/63] feature: add 06_tuples chinese translation --- Chinese/05_lists.md | 4 +- Chinese/06_tuples.md | 259 +++++++++++++++++++++++++++++++++++++++++++ Chinese/README.md | 4 +- 3 files changed, 263 insertions(+), 4 deletions(-) create mode 100644 Chinese/06_tuples.md diff --git a/Chinese/05_lists.md b/Chinese/05_lists.md index e9842e781..190d45146 100644 --- a/Chinese/05_lists.md +++ b/Chinese/05_lists.md @@ -14,7 +14,7 @@ -[<< 第四天](./04_strings.md) | [第六天 >>](../06_Day_Tuples/06_tuples.md) +[<< 第四天](./04_strings.md) | [第六天 >>](./06_tuples.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -593,4 +593,4 @@ ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] 🎉 恭喜 ! 🎉 -[<< 第四天](./04_strings.md) | [第六天 >>](../06_Day_Tuples/06_tuples.md) +[<< 第四天](./04_strings.md) | [第六天 >>](./06_tuples.md) diff --git a/Chinese/06_tuples.md b/Chinese/06_tuples.md new file mode 100644 index 000000000..d32a57921 --- /dev/null +++ b/Chinese/06_tuples.md @@ -0,0 +1,259 @@ +
+

30 天 Python:第六天 - Tuples

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[<< 第五天](./05_lists.md) | [第七天 >>](./07_sets.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [第六天:](#第六天) + - [元组](#元组) + - [如何创建元组](#如何创建元组) + - [元组长度](#元组长度) + - [获取元组项](#获取元组项) + - [元组切片](#元组切片) + - [将元组更改为列表](#将元组更改为列表) + - [检索元组中的项](#检索元组中的项) + - [连接元组](#连接元组) + - [删除元组](#删除元组) + - [💻 练习 - 第六天](#-练习---第六天) + - [练习: 1级](#练习-1级) + - [练习: 2级](#练习-2级) + +# 第六天: + +## 元组 + +元组是有序且不可变的不同数据类型的集合。一旦创建了元组,我们就无法更改其值。我们不能在元组中使用 add、insert、remove 方法,因为它是不可修改的(不可变的)。与列表不同,元组的方法很少。与元组相关的方法有: + +- tuple():创建一个空元组 +- count():计算元组中指定项的数量 +- index():查找元组中指定项的索引 +- + 运算符:连接两个或多个元组并创建一个新元组 + +### 如何创建元组 + +- 创建一个空元组 + + ```py + # 语法 + empty_tuple = () + # 或使用元组构造函数 + empty_tuple = tuple() + ``` + +- 创建一个具有初始值的元组 + + ```py + # 语法 + tpl = ('item1', 'item2','item3') + ``` + + ```py + fruits = ('banana', 'orange', 'mango', 'lemon') + ``` + + +### 元组长度 + +我们使用 _len()_ 方法来获取元组的长度。 + +```py +# 语法 +tpl = ('item1', 'item2', 'item3') +len(tpl) +``` + +### 获取元组项 + + +- 正索引 + 与列表数据类型类似,我们使用正索引或负索引来访问元组项。 + ![Accessing tuple items](../images/tuples_index.png) + + ```py + # 语法 + tpl = ('item1', 'item2', 'item3') + first_item = tpl[0] + second_item = tpl[1] + ``` + + ```py + fruits = ('banana', 'orange', 'mango', 'lemon') + first_fruit = fruits[0] + second_fruit = fruits[1] + last_index =len(fruits) - 1 + last_fruit = fruits[las_index] + ``` + +- 负索引 + 负索引是从末尾开始的,-1 表示最后一项,-2 表示倒数第二项,列表/元组长度的负数表示第一项。 + ![Tuple Negative indexing](../images/tuple_negative_indexing.png) + + ```py + # 语法 + tpl = ('item1', 'item2', 'item3','item4') + first_item = tpl[-4] + second_item = tpl[-3] + ``` + + ```py + fruits = ('banana', 'orange', 'mango', 'lemon') + first_fruit = fruits[-4] + second_fruit = fruits[-3] + last_fruit = fruits[-1] + ``` + +### 元组切片 + +我们可以通过指定开始和结束的索引范围来切出子元组,返回值是一个包含指定项的新元组。 + +- 正索引范围 + + ```py + # 语法 + tpl = ('item1', 'item2', 'item3','item4') + all_items = tpl[0:4] # 所有项 + all_items = tpl[0:] # 所有项 + middle_two_items = tpl[1:3] # 不包括索引 3 的项 + ``` + + ```py + fruits = ('banana', 'orange', 'mango', 'lemon') + all_fruits = fruits[0:4] # 所有项 + all_fruits= fruits[0:] # 所有项 + orange_mango = fruits[1:3] # 不包括索引 3 的项 + orange_to_the_rest = fruits[1:] + ``` + +- 负索引范围 + + ```py + # 语法 + tpl = ('item1', 'item2', 'item3','item4') + all_items = tpl[-4:] # 所有项 + middle_two_items = tpl[-3:-1] # 不包括索引 3 的项 + ``` + + ```py + + fruits = ('banana', 'orange', 'mango', 'lemon') + all_fruits = fruits[-4:] # 所有项 + orange_mango = fruits[-3:-1] # 不包括索引 3 的项 + orange_to_the_rest = fruits[-3:] + ``` + +### 将元组更改为列表 + +我们可以将元组更改为列表,将列表更改为元组。如果我们想修改元组,我们应该将其更改为列表。 + +```py +# 语法 +tpl = ('item1', 'item2', 'item3','item4') +lst = list(tpl) +``` + +```py +fruits = ('banana', 'orange', 'mango', 'lemon') +fruits = list(fruits) +fruits[0] = 'apple' +print(fruits) # ['apple', 'orange', 'mango', 'lemon'] +fruits = tuple(fruits) +print(fruits) # ('apple', 'orange', 'mango', 'lemon') +``` + +### 检索元组中的项 + +我们可以使用 _in_ 检查元组中是否存在某个项,它返回一个布尔值。 + +```py +# 语法 +tpl = ('item1', 'item2', 'item3','item4') +'item2' in tpl # True +``` + +```py +fruits = ('banana', 'orange', 'mango', 'lemon') +print('orange' in fruits) # True +print('apple' in fruits) # False +fruits[0] = 'apple' # TypeError: 'tuple' object does not support item assignment +``` + + + +### 连接元组 + +我们可以使用 + 运算符连接两个或多个元组 + +```py +# 语法 +tpl1 = ('item1', 'item2', 'item3') +tpl2 = ('item4', 'item5','item6') +tpl3 = tpl1 + tpl2 +``` + +```py +fruits = ('banana', 'orange', 'mango', 'lemon') +vegetables = ('Tomato', 'Potato', 'Cabbage','Onion', 'Carrot') +fruits_and_vegetables = fruits + vegetables +``` + +### 删除元组 + +不能删除元组中的单个项,但可以使用 _del_ 删除元组本身。 + +```py +# 语法 +tpl1 = ('item1', 'item2', 'item3') +del tpl1 + +``` + +```py +fruits = ('banana', 'orange', 'mango', 'lemon') +del fruits +``` + + +🌕 你太勇敢了,你做到了。你刚刚完成了第 6 天的挑战,你已向着伟大的目标迈出了 6 步。现在做一些练习来锻练你的大脑和肌肉。 + +## 💻 练习 - 第六天 + +### 练习: 1级 + +1. 创建一个空元组 +1. 创建一个包含你姐妹和兄弟名字的元组(虚构的兄弟姐妹也可以) +1. 连接兄弟姐妹元组并将其分配给 siblings +1. 你有多少兄弟姐妹? +1. 修改兄弟姐妹元组并添加你父母的名字,然后将其分配给 family_members + +### 练习: 2级 + +1. 从 family_members 中获取兄弟姐妹和父母 +1. 创建 fruits、vegetables 和 animal products 元组。连接三个元组并将其分配给名为 food_stuff_tp 的变量。 +1. 将 food_stuff_tp 元组更改为 food_stuff_lt 列表 +1. 从 food_stuff_tp 元组或 food_stuff_lt 列表中切出中间项或项。 +1. 从 food_staff_lt 列表中切出前三项和最后三项 +1. 完全删除 food_staff_tp 元组 +1. 检查元组中是否存在项: +- 检查 'Estonia' 是否在 nordic_country 元组中 +- 检查 'Iceland' 是否在 nordic_country 元组中 + + ```py + nordic_countries = ('Denmark', 'Finland','Iceland', 'Norway', 'Sweden') + ``` + + +[<< 第五天](./05_lists.md) | [第七天 >>](./07_sets.md) diff --git a/Chinese/README.md b/Chinese/README.md index e02ba7227..e49895221 100644 --- a/Chinese/README.md +++ b/Chinese/README.md @@ -7,8 +7,8 @@ | 03 | [运算符](./03_operators.md) | | 04 | [字符串](./04_strings.md) | | 05 | [列表](./05_lists.md) | -| 06 | [元组](./06_Day_Tuples/06_tuples.md) | -| 07 | [集合](./07_Day_Sets/07_sets.md) | +| 06 | [元组](./06_tuples.md) | +| 07 | [集合](./07_sets.md) | | 08 | [字典](./08_Day_Dictionaries/08_dictionaries.md) | | 09 | [条件](./09_Day_Conditionals/09_conditionals.md) | | 10 | [循环](./10_Day_Loops/10_loops.md) | From 53164f19f173171d93186f49d34329d0ae86edd7 Mon Sep 17 00:00:00 2001 From: Archie Date: Tue, 16 Jul 2024 20:50:12 +0100 Subject: [PATCH 39/63] Translate the 7 day into Chinese --- Chinese/07_sets.md | 431 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 431 insertions(+) create mode 100644 Chinese/07_sets.md diff --git a/Chinese/07_sets.md b/Chinese/07_sets.md new file mode 100644 index 000000000..21c8cf091 --- /dev/null +++ b/Chinese/07_sets.md @@ -0,0 +1,431 @@ +
+

30 天 Python:第 7 天 - 集合

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[<< 第 6 天](../06_Day_Tuples/06_tuples.md) | [第 8 天 >>](../08_Day_Dictionaries/08_dictionaries.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 第 7 天](#-第-7-天) + - [集合](#集合) + - [创建集合](#创建集合) + - [获取集合长度](#获取集合长度) + - [访问集合中的项目](#访问集合中的项目) + - [检查项目](#检查项目) + - [向集合中添加项目](#向集合中添加项目) + - [从集合中移除项目](#从集合中移除项目) + - [清空集合中的项目](#清空集合中的项目) + - [删除集合](#删除集合) + - [将列表转换为集合](#将列表转换为集合) + - [合并集合](#合并集合) + - [查找交集项目](#查找交集项目) + - [检查子集和超集](#检查子集和超集) + - [检查两个集合之间的差异](#检查两个集合之间的差异) + - [查找两个集合之间的对称差异](#查找两个集合之间的对称差异) + - [合并集合](#合并集合-1) + - [💻 练习:第 7 天](#-练习-第-7-天) + - [练习:等级 1](#练习-等级-1) + - [练习:等级 2](#练习-等级-2) + - [练习:等级 3](#练习-等级-3) + +# 📘 第 7 天 + +## 集合 + +集合是项目的集合。让我带你回到小学或高中的数学课。集合的数学定义也适用于 Python。集合是无序且未索引的不同元素的集合。在 Python 中,集合用于存储唯一项目,可以在集合之间找到 _并集_、_交集_、_差集_、_对称差集_、_子集_、_超集_ 和 _不相交集_。 + +### 创建集合 + +我们使用 _set()_ 内置函数。 + +- 创建空集合 + +```py +# 语法 +st = set() +``` + +- 创建一个包含初始项目的集合 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +``` + +**示例:** + +```py +# 语法 +fruits = {'banana', 'orange', 'mango', 'lemon'} +``` + +### 获取设置的长度 + +我们使用**len()**方法来查找集合的长度。 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +len(st) +``` + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +len(fruits) +``` + +### 访问集合中的项目 + +我们使用循环来访问项目。我们将在循环部分看到这一点。 + +### 检查项目 + +要检查列表中是否存在某个项目,我们使用 _in_ 成员运算符。 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +print("Does set st contain item3? ", 'item3' in st) # Does set st contain item3? True +``` + +**示例:** + +```py + +fruits = {'香蕉', '橙色', '芒果', '柠檬'} + +print('芒果' in fruits ) # True + +``` + +### 向集合中添加元素 + +一旦集合创建后,我们不能改变其中的任何元素,但可以添加其他的元素。 + +- 使用 _add()_ 方法添加单个元素 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +st.add('item5') +``` + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +fruits.add('lime') +``` + +- 使用 _update()_ 方法添加多个元素 + _update()_ 方法允许向集合中添加多个元素。_update()_ 接收一个列表作为参数。 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +st.update(['item5','item6','item7']) +``` + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +vegetables = ('tomato', 'potato', 'cabbage','onion', 'carrot') +fruits.update(vegetables) +``` + +### 从集合中移除元素 + +我们可以使用 _remove()_ 方法从集合中移除一个元素。如果找不到该元素,_remove()_ 方法会抛出错误,因此最好先检查该元素是否存在于集合中。_discard()_ 方法则不会抛出任何错误。 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +st.remove('item2') +``` + +_pop()_ 方法从集合中移除一个随机元素并返回该被移除的元素。 + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +fruits.pop() # 从集合中移除一个随机元素 +``` + +如果我们对被移除的元素感兴趣。 + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +removed_item = fruits.pop() +``` + +### 清空集合中的项目 + +如果我们想要清空或清除集合中的所有项目,可以使用 _clear_ 方法。 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +st.clear() +``` + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +fruits.clear() +print(fruits) # set() +``` + +### 删除一个集合 + +如果我们想要删除整个集合,可以使用 _del_ 操作符。 + +```py +# 语法 +st = {'item1', 'item2', 'item3', 'item4'} +del st +``` + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +del fruits +``` + +### 将列表转换为集合 + +我们可以将列表转换为集合,也可以将集合转换为列表。将列表转换为集合会去除重复项,只保留唯一项。 + +```py +# 语法 +lst = ['item1', 'item2', 'item3', 'item4', 'item1'] +st = set(lst) # {'item2', 'item4', 'item1', 'item3'} - 顺序是随机的,因为集合在一般情况下是无序的 +``` + +**示例:** + +```py +fruits = ['banana', 'orange', 'mango', 'lemon','orange', 'banana'] +fruits = set(fruits) # {'mango', 'lemon', 'banana', 'orange'} +``` + +### 合并集合 + +我们可以使用 _union()_ 或 _update()_ 方法来合并两个集合。 + +- Union + 这个方法返回一个新集合 + +```py +# 语法 +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item5', 'item6', 'item7', 'item8'} +st3 = st1.union(st2) +``` + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +vegetables = {'tomato', 'potato', 'cabbage','onion', 'carrot'} +print(fruits.union(vegetables)) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabbage', 'potato', 'onion'} +``` + +- Update + 这个方法将一个集合插入到给定的集合中 + +```py +# 语法 +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item5', 'item6', 'item7', 'item8'} +st1.update(st2) # st2 的内容被添加到 st1 中 +``` + +**示例:** + +```py +fruits = {'banana', 'orange', 'mango', 'lemon'} +vegetables = {'tomato', 'potato', 'cabbage','onion', 'carrot'} +fruits.update(vegetables) +print(fruits) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabbage', 'potato', 'onion'} +``` + +### 查找交集项 + +交集返回两个集合中都存在的项的集合。请参见示例 + +```py +# 语法 +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item3', 'item2'} +st1.intersection(st2) # {'item3', 'item2'} +``` + +**示例:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +even_numbers = {0, 2, 4, 6, 8, 10} +whole_numbers.intersection(even_numbers) # {0, 2, 4, 6, 8, 10} + +python = {'p', 'y', 't', 'h', 'o', 'n'} +dragon = {'d', 'r', 'a', 'g', 'o', 'n'} +python.intersection(dragon) # {'o', 'n'} +``` + +### 检查子集和超集 + +一个集合可以是另一个集合的子集或超集: + +- 子集: _issubset()_ +- 超集: _issuperset_ + +```py +# 语法 +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +st2.issubset(st1) # True +st1.issuperset(st2) # True +``` + +**示例:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +even_numbers = {0, 2, 4, 6, 8, 10} +whole_numbers.issubset(even_numbers) # 错误,因为它是超集 +whole_numbers.issuperset(even_numbers) # 正确 + +python = {'p', 'y', 't', 'h', 'o', 'n'} +dragon = {'d', 'r', 'a', 'g', 'o', 'n'} +python.issubset(dragon) # 错误 +``` + +### 检查两个集合之间的差异 + +它返回两个集合之间的差异。 + +```py +# 语法 +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +st2.difference(st1) # set() +st1.difference(st2) # {'item1', 'item4'} => st1\st2 +``` + +**示例:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +even_numbers = {0, 2, 4, 6, 8, 10} +whole_numbers.difference(even_numbers) # {1, 3, 5, 7, 9} + +python = {'p', 'y', 't', 'o', 'n'} +dragon = {'d', 'r', 'a', 'g', 'o', 'n'} +python.difference(dragon) # {'p', 'y', 't'} - 结果是无序的(集合的特性) +dragon.difference(python) # {'d', 'r', 'a', 'g'} +``` + +### 查找两个集合之间的对称差异 + +它返回两个集合之间的对称差异。它意味着它返回一个包含两个集合中所有项的集合,除了同时出现在两个集合中的项,数学上:(A\B) ∪ (B\A) + +```py +# 语法 +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +# 意思是 (A\B)∪(B\A) +st2.symmetric_difference(st1) # {'item1', 'item4'} +``` + +**示例:** + +```py +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +some_numbers = {1, 2, 3, 4, 5} +whole_numbers.symmetric_difference(some_numbers) # {0, 6, 7, 8, 9, 10} + +python = {'p', 'y', 't', 'h', 'o', 'n'} +dragon = {'d', 'r', 'a', 'g', 'o', 'n'} +python.symmetric_difference(dragon) # {'r', 't', 'p', 'y', 'g', 'a', 'd', 'h'} +``` + +### 合并集合 + +如果两个集合没有共同的项或项,我们称它们为不相交集合。我们可以使用 _isdisjoint()_ 方法来检查两个集合是否相交。 + +```py +# 语法 +st1 = {'item1', 'item2', 'item3', 'item4'} +st2 = {'item2', 'item3'} +st2.isdisjoint(st1) # 错误 +``` + +**示例:** + +```py +even_numbers = {0, 2, 4, 6, 8} +odd_numbers = {1, 3, 5, 7, 9} +even_numbers.isdisjoint(odd_numbers) # 正确,因为没有共同项 + +python = {'p', 'y', 't', 'h', 'o', 'n'} +dragon = {'d', 'r', 'a', 'g', 'o', 'n'} +python.isdisjoint(dragon) # 错误,有共同项 {'o', 'n'} +``` + +🌕 你是一颗冉冉升起的明星。你刚刚完成了第 7 天的挑战,你在通往伟大的道路上前进了 7 步。现在为你的大脑和肌肉做一些练习。 + +## 💻 练习:第 7 天 + +```py +# 集合 +it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'} +A = {19, 22, 24, 20, 25, 26} +B = {19, 22, 20, 25, 26, 24, 28, 27} +age = [22, 19, 24, 25, 26, 24, 25, 24] +``` + +### 练习:第 1 级 + +1. 找到集合 it_companies 的长度 +2. 向 it_companies 添加'Twitter' +3. 一次性向集合 it_companies 插入多个 IT 公司 +4. 从集合 it_companies 中移除一家公司 +5. 移除和丢弃之间有什么区别 + +### 练习:第 2 级 + +1. 合并 A 和 B +1. 找到 A 和 B 的交集 +1. A 是 B 的子集吗 +1. A 和 B 是不相交集合吗 +1. 将 A 与 B 合并,反之亦然 +1. A 和 B 之间的对称差异是什么 +1. 完全删除集合 + +### 练习:第 3 级 + +1. 将年龄转换为集合并比较列表和集合的长度,哪一个更大? +1. 解释以下数据类型之间的区别:字符串、列表、元组和集合 +1. _我是一个老师,我喜欢激励和教导人们。_ 这句句子中用了多少独特的单词?使用 split 方法和集合来获取独特的单词。 + +🎉 恭喜! 🎉 + +[<< 第 6 天](../06_Day_Tuples/06_tuples.md) | [第 8 天 >>](../08_Day_Dictionaries/08_dictionaries.md) From e2e03b98e2ce4fa88c6fe6ff37c5ebbec32f7c1d Mon Sep 17 00:00:00 2001 From: Archie Date: Wed, 31 Jul 2024 22:56:24 +0100 Subject: [PATCH 40/63] add 08_dictionaries Chinese support --- Chinese/08_dictionaries.md | 343 +++++++++++++++++++++++++++++++++++++ 1 file changed, 343 insertions(+) create mode 100644 Chinese/08_dictionaries.md diff --git a/Chinese/08_dictionaries.md b/Chinese/08_dictionaries.md new file mode 100644 index 000000000..7b5084297 --- /dev/null +++ b/Chinese/08_dictionaries.md @@ -0,0 +1,343 @@ +
+

30 天 Python 学习:第 8 天 - 字典

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[<< 第 7 天 ](../07_Day_Sets/07_sets.md) | [第 9 天 >>](../09_Day_Conditionals/09_conditionals.md) + +![30 天 Python 学习](../images/30DaysOfPython_banner3@2x.png) + +- [📘 第 8 天](#-第-8-天) + - [字典](#字典) + - [创建字典](#创建字典) + - [字典长度](#字典长度) + - [访问字典项](#访问字典项) + - [向字典添加项](#向字典添加项) + - [修改字典中的项](#修改字典中的项) + - [检查字典中的键](#检查字典中的键) + - [从字典中移除键值对](#从字典中移除键值对) + - [将字典转换为项目列表](#将字典转换为项目列表) + - [清空字典](#清空字典) + - [删除字典](#删除字典) + - [复制字典](#复制字典) + - [将字典键转换为列表](#将字典键转换为列表) + - [将字典值转换为列表](#将字典值转换为列表) + - [💻 练习:第 8 天](#-练习-第-8-天) + +# 📘 第 8 天 + +## 字典 + +字典是一种由无序、可修改(可变)的键值对组成的数据类型。 + +### 创建字典 + +为了创建字典,我们使用大括号 {} 或内置函数 _dict()_。 + +```py +# 语法 +empty_dict = {} +# 带数据值的字典 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +``` + +**示例:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +``` + +上面的字典显示,值可以是任何数据类型:字符串、布尔值、列表、元组、集合或字典。 + +### 字典长度 + +它检查字典中的键值对的数量。 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(len(dct)) # 4 +``` + +**示例:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +print(len(person)) # 7 + +``` + +### 访问字典项 + +我们可以通过参考其键名来访问字典项。 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(dct['key1']) # value1 +print(dct['key4']) # value4 +``` + +**示例:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +print(person['first_name']) # Asabeneh +print(person['country']) # Finland +print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'] +print(person['skills'][0]) # JavaScript +print(person['address']['street']) # Space street +print(person['city']) # 错误 +``` + +通过键名访问项时,如果键不存在会引发错误。为了避免这个错误,我们首先要检查键是否存在,或者使用 _get_ 方法。get 方法在键不存在时返回 None(这是 NoneType 对象数据类型)。 + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } + } +print(person.get('first_name')) # Asabeneh +print(person.get('country')) # Finland +print(person.get('skills')) #['HTML','CSS','JavaScript', 'React', 'Node', 'MongoDB', 'Python'] +print(person.get('city')) # None +``` + +### 向字典添加项 + +我们可以向字典中添加新的键值对 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct['key5'] = 'value5' +``` + +**示例:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } +} +person['job_title'] = 'Instructor' +person['skills'].append('HTML') +print(person) +``` + +### 修改字典中的项目 + +我们可以修改字典中的项目 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct['key1'] = 'value-one' +``` + +**示例:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_married':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } +} +person['first_name'] = 'Eyob' +person['age'] = 252 +``` + +### 检查字典中的键 + +我们使用 _in_ 运算符来检查字典中是否存在某个键 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print('key2' in dct) # True +print('key5' in dct) # False +``` + +### 从字典中删除键值对 + +- _pop(key)_: 删除具有指定键名的项目 +- _popitem()_: 删除最后一个项目 +- _del_: 删除具有指定键名的项目 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct.pop('key1') # 删除 key1 项目 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct.popitem() # 删除最后一项 +del dct['key2'] # 删除 key2 项目 +``` + +**示例:** + +```py +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_married':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } +} +person.pop('first_name') # 删除 firstname 项目 +person.popitem() # 删除 address 项目 +del person['is_married'] # 删除 is_married 项目 +``` + +### 将字典改变为项目列表 + +_items()_ 方法将字典变成由元组组成的列表。 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(dct.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')]) +``` + +### 清空字典 + +如果我们不需要字典中的项目,我们可以使用 _clear()_ 方法来清空它们 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +print(dct.clear()) # None +``` + +### 删除字典 + +如果我们不再使用字典,我们可以完全删除它 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +del dct +``` + +### 复制字典 + +我们可以使用 _copy()_ 方法复制一个字典。使用 copy 方法可以避免原始字典被修改。 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +``` + +### 获取字典的键列表 + +keys() 方法给我们一个包含所有字典键的列表。 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +keys = dct.keys() +print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4']) +``` + +### 获取字典的值列表 + +values 方法给我们一个包含所有字典值的列表。 + +```py +# 语法 +dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} +values = dct.values() +print(values) # dict_values(['value1', 'value2', 'value3', 'value4']) +``` + +🌕 你很了不起。现在,你已经掌握了字典的强大功能。你已经完成了第 8 天的挑战,离成功又近了一步。现在为你的大脑和肌肉做一些练习。 + +## 💻 练习:第 8 天 + +1. 创建一个名为 dog 的空字典 +2. 向 dog 字典添加 name、color、breed、legs、age 键 +3. 创建一个学生字典,添加 first_name、last_name、gender、age、marital status、skills、country、city 和 address 作为字典的键 +4. 获取学生字典的长度 +5. 获取 skills 的值并检查数据类型,应该是列表 +6. 修改 skills 值,添加一到两个技能 +7. 获取字典的键列表 +8. 获取字典的值列表 +9. 使用 _items()_ 方法将字典变为由元组组成的列表 +10. 删除字典中的一项 +11. 删除其中一个字典 + +🎉 恭喜你! 🎉 + +[<< 第 7 天 ](../07_Day_Sets/07_sets.md) | [第 9 天 >>](../09_Day_Conditionals/09_conditionals.md) From daedc7bfc6e940fc37cb31e02dec6bac418c6cba Mon Sep 17 00:00:00 2001 From: Archie Date: Thu, 1 Aug 2024 21:59:13 +0100 Subject: [PATCH 41/63] add 09 Day conditionals Chinese support --- Chinese/09_conditionals.md | 284 +++++++++++++++++++++++++++++++++++++ 1 file changed, 284 insertions(+) create mode 100644 Chinese/09_conditionals.md diff --git a/Chinese/09_conditionals.md b/Chinese/09_conditionals.md new file mode 100644 index 000000000..fb69fde31 --- /dev/null +++ b/Chinese/09_conditionals.md @@ -0,0 +1,284 @@ +
+

30天Python学习:第9天 - 条件语句

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+第二版:2021 年 7 月 +
+ +
+ +[<< 第 8 天](../08_Day_Dictionaries/08_dictionaries.md) | [第 10 天 >>](../10_Day_Loops/10_loops.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 第 9 天](#-第9天) + - [条件语句](#条件语句) + - [If 条件](#if条件) + - [If Else](#if-else) + - [If Elif Else](#if-elif-else) + - [简写](#简写) + - [嵌套条件](#嵌套条件) + - [If 条件和逻辑运算符](#if条件和逻辑运算符) + - [If 和 Or 逻辑运算符](#if和or逻辑运算符) + - [💻 练习:第 9 天](#-练习第9天) + - [练习:第一层级](#练习第一层级) + +# 📘 第 9 天 + +## 条件语句 + +默认情况下,Python 脚本中的语句是从上到下顺序执行的。如果处理逻辑需要,可以通过两种方式来改变顺序: + +- 条件执行:如果某个表达式为真,则执行一个或多个语句块 +- 重复执行:只要某个表达式为真,则重复执行一个或多个语句块。在本节中,我们将讨论*if*,_else_,*elif*语句。前面章节中学到的比较运算符和逻辑运算符在这里将派上用场。 + +### If 条件 + +在 Python 和其他编程语言中,关键字*if*用于检查条件是否为真并执行代码块。请记住冒号后的缩进。 + +```py +# 语法 +if condition: + 如果条件为真,则运行此部分代码 +``` + +**示例:1** + +```py +a = 3 +if a > 0: + print('A是一个正数') +# A是一个正数 +``` + +如上例所示,3 大于 0。条件为真,执行代码块。然而,如果条件为假,我们不会看到结果。为了看到假条件的结果,我们应有另一个代码块,即*else*。 + +### If Else + +如果条件为真,则执行第一个代码块,否则执行*else*条件。 + +```py +# 语法 +if condition: + 如果条件为真,则运行此部分代码 +else: + 如果条件为假,则运行此部分代码 +``` + +**示例:** + +```py +a = 3 +if a < 0: + print('A是一个负数') +else: + print('A是一个正数') +``` + +上面的条件为假,因此执行*else*代码块。如果我们的条件超过两个呢?我们可以使用*elif*。 + +### If Elif Else + +在我们的日常生活中,我们每天都在做决策。我们做出决策不仅仅是检查一个或两个条件,而是多个条件。与生活相似,编程中也充满了条件。当我们有多个条件时,可以使用*elif*。 + +```py +# 语法 +if condition: + 代码 +elif condition: + 代码 +else: + 代码 + +``` + +**示例:** + +```py +a = 0 +if a > 0: + print('A是一个正数') +elif a < 0: + print('A是一个负数') +else: + print('A是零') +``` + +### 简写 + +```py +# 语法 +代码 if 条件 else 代码 +``` + +**示例:** + +```py +a = 3 +print('A是正数') if a > 0 else print('A是负数') # 满足第一个条件,将打印 'A是正数' +``` + +### 嵌套条件 + +条件可以嵌套 + +```py +# 语法 +if 条件: + 代码 + if 条件: + 代码 +``` + +**示例:** + +```py +a = 0 +if a > 0: + if a % 2 == 0: + print('A是一个正数且为偶数') + else: + print('A是一个正数') +elif a == 0: + print('A是零') +else: + print('A是一个负数') +``` + +我们可以使用逻辑运算符*and*来避免编写嵌套条件。 + +### If 条件和逻辑运算符 + +```py +# 语法 +if 条件 and 条件: + 代码 +``` + +**示例:** + +```py +a = 0 +if a > 0 and a % 2 == 0: + print('A是一个正数且为偶数') +elif a > 0 and a % 2 != 0: + print('A是一个正数') +elif a == 0: + print('A是零') +else: + print('A是一个负数') +``` + +### If 和 Or 逻辑运算符 + +```py +# 语法 +if 条件 or 条件: + 代码 +``` + +**示例:** + +```py +user = 'James' +access_level = 3 +if user == 'admin' or access_level >= 4: + print('访问授权!') +else: + print('访问拒绝!') +``` + +🌕 你做得很好。永远不要放弃,因为伟大的事情需要时间。你刚刚完成了第 9 天的挑战,你已经在通向伟大的道路上前进了 9 步。现在做一些练习来锻炼你的大脑和肌肉。 + +## 💻 练习:第 9 天 + +### 练习:第一层级 + +1. 使用 input 获取用户输入(例如:“输入你的年龄:”)。如果用户 18 岁或以上,给出反馈:你已经足够大,可以学习驾驶。如果未满 18 岁,则给出需要等待的年数。输出: + + ```sh + 输入你的年龄:30 + 你已经足够大,可以学习驾驶。 + 输出: + 输入你的年龄:15 + 你还需要等待3年才能学习驾驶。 + ``` + +2. 使用 if…else 比较 my_age 和 your_age 的值。谁更年长(我还是你)?使用 input(“输入你的年龄:”)获取年龄作为输入。您可以使用嵌套条件来打印'年'表示 1 年的年龄差异,'年'表示更大的差异,如果 my_age = your_age,则打印自定义文本。输出: + + ```sh + 输入你的年龄:30 + 你比我大5岁。 + ``` + +3. 使用输入提示从用户处获得两个数字。如果 a 大于 b,返回 a 大于 b,如果 a 小于 b,返回 a 小于 b,否则返回 a 等于 b。输出: + +```sh +输入第一个数字:4 +输入第二个数字:3 +4大于3 +``` + +### 练习:第二层级 + +1. 编写代码,根据学生的分数给出等级: + + ```sh + 80-100, A + 70-79, B + 60-69, C + 50-59, D + 0-49, F + ``` + +2. 检查是否是秋天、冬天、春天或夏天。如果用户输入: + 9 月、10 月或 11 月,是秋天。 + 12 月、1 月或 2 月,是冬天。 + 3 月、4 月或 5 月,是春天。 + 6 月、7 月或 8 月,是夏天。 +3. 以下列表包含了一些水果: + + ```sh + fruits = ['banana', 'orange', 'mango', 'lemon'] + ``` + + 如果列表中不存在某个水果,则将其添加到列表中并打印修改后的列表。如果水果存在,则打印('该水果已在列表中')。 + +### 练习:第三层级 + +1. 这里有一个人员字典。请随意修改它! + +```py +person = { + 'first_name': 'Asabeneh', + 'last_name': 'Yetayeh', + 'age': 250, + 'country': '芬兰', + 'is_married': True, + 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address': { + 'street': '太空街', + 'zipcode': '02210' + } +} +``` + +- 检查是否在字典中有 skills 键,如果有则打印 skills 列表中的中间技能。 +- 检查是否在字典中有 skills 键,如果有则检查该人是否具备'Python'技能并打印结果。 +- 如果一个人的技能只有 JavaScript 和 React,打印('他是前端开发者'),如果一个人的技能有 Node、Python、MongoDB,打印('他是后端开发者'),如果一个人的技能有 React、Node 和 MongoDB,打印('他是全栈开发者'),否则打印'未知头衔' - 为获得更准确的结果,可以嵌套更多条件! +- 如果该人结婚了且居住在芬兰,按以下格式打印信息: + +```py +Asabeneh Yetayeh住在芬兰。他已婚。 +``` + +🎉 恭喜! 🎉 + +[<< 第 8 天](../08_Day_Dictionaries/08_dictionaries.md) | [第 10 天 >>](../10_Day_Loops/10_loops.md) From 97409874f7b6dd0b35a2c1c1fb46ba63c009d4dd Mon Sep 17 00:00:00 2001 From: XBsleepy Date: Sun, 4 Aug 2024 12:13:18 +0800 Subject: [PATCH 42/63] add 10 loops Chinese translation --- Chinese/10_loops.md | 451 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 451 insertions(+) create mode 100644 Chinese/10_loops.md diff --git a/Chinese/10_loops.md b/Chinese/10_loops.md new file mode 100644 index 000000000..40484074a --- /dev/null +++ b/Chinese/10_loops.md @@ -0,0 +1,451 @@ +
+

30 天 Python:第十天 - Loops

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ 第二版:2021 年 7 月 +
+ +
+ +[<<第九天](../Chinese/09_conditionals.md) | [第十一天>>](../Chinese/11_functions.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + + +- [📘 第十天](#-第十天) + - [循环](#循环) + - [while 循环](#while-循环) + - [break和continue - part 1](#break和continue---part-1) + - [for 循环](#for-循环) + - [break 和 continue - part 2](#break-和-continue---part-2) + - [range() 函数](#range-函数) + - [嵌套for循环](#嵌套for循环) + - [for和else](#for和else) + - [pass语句](#pass语句) + - [💻 练习:第十天](#-练习第十天) + - [练习:一级](#练习一级) + - [练习:二级](#练习二级) + - [练习:三级](#练习三级) + +# 📘 第十天 + +## 循环 + +生活充满了循环。在编程中,我们会做很多重复的任务。编程语言使用循环来处理重复的任务,而Python编程语言提供了以下两种类型的循环: +1. while 循环 +2. for 循环 + +### while 循环 + +我们使用关键字`while`来创建while循环。它在条件被满足时重复执行代码块。当条件变为false时,会结束循环代码块,执行循环之后的代码。 + +```python + # syntax +while condition: + code goes here +``` + +**示例:** + +```python +count = 0 +while count < 5: + print(count) + count = count + 1 +#prints from 0 to 4 +``` + +在上面的循环中,当count等于5时,循环条件变为false,此时循环停止。 + +如果我们想要在循环条件变为false时运行特定的代码块,我们可以使用`else`关键字。 + +```python + # syntax +while condition: + code goes here +else: + code goes here +``` + +**示例:** + +```python +count = 0 +while count < 5: + print(count) + count = count + 1 +else: + print(count) +``` + +当count等于5时,循环条件变为false,循环终止,然后开始执行else块中的代码。因此,5将会被打印输出。 + +### break和continue - part 1 + +* Break:当我们想要退出循环时,我们使用`break`关键字。 + +```python +# syntax +while condition: + code goes here + if another_condition: + break +``` + +**Example:** + +```python +count = 0 +while count < 5: + print(count) + count = count + 1 + if count == 3: + break +``` +上面的while循环只会打印输出0,1,2,但当count等于3时,循环会终止。 +- Continue:当我们想要跳过当前循环并继续执行下一个循环时,我们使用`continue`关键字。 + +```python + # syntax +while condition: + code goes here + if another_condition: + continue +``` + +**示例:** + +```python +count = 0 +while count < 5: + if count == 3: + count = count + 1 + continue + print(count) + count = count + 1 +``` + +上面的while循环只会打印输出0,1,2,4。(3被跳过了) + +### for 循环 + +`for`关键字用于创建for循环。和别的编程语言相似,但语法上有一些不同。它可以用于对序列的遍历(也就是列表、元组、字典、集合、字符串等)。 + +- 列表的for循环 + +```python +# syntax +for iterator in lst: + code goes here +``` + +**示例:** + +```python +numbers = [0, 1, 2, 3, 4, 5] +for number in numbers: # number是引用列表项的临时名称,仅在此循环中有效 + print(number) # number将会被逐行打印,从0到5 +``` + +- 字符串的for循环 + +```python +# syntax +for iterator in string: + code goes here +``` + +**示例:** + +```python +language = 'Python' +for letter in language: + print(letter) + +for i in range(len(language)): + print(language[i]) +``` + +- 元组的for循环 + +```python +# syntax +for iterator in tpl: + code goes here +``` + +**示例:** + +```python +numbers = (0, 1, 2, 3, 4, 5) +for number in numbers: + print(number) +``` + +- 字典的for循环 + 循环遍历将会遍历字典的键。 + +```python + # syntax +for iterator in dct: + code goes here +``` + +**示例:** + +```python +person = { + 'first_name':'Asabeneh', + 'last_name':'Yetayeh', + 'age':250, + 'country':'Finland', + 'is_marred':True, + 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address':{ + 'street':'Space street', + 'zipcode':'02210' + } +} +for key in person: + print(key) #仅输出键 + +for key, value in person.items(): + print(key, value) # 这样我们可以在迭代的过程中同时访问键和值 +``` + +- 集合的for循环 + +```python +# syntax +for iterator in st: + code goes here +``` + +**示例:** + +```python +it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'} +for company in it_companies: + print(company) +``` + +### break 和 continue - part 2 + +提示: +_break_:当我们想要在循环完成前退出循环时,我们使用`break`关键字。 + +```python +# syntax +for iterator in sequence: + code goes here + if condition: + break +``` + +**示例:** + +```python +numbers = (0,1,2,3,4,5) +for number in numbers: + print(number)#输出 0,1,2,3 + if number == 3: + break +``` +在上面的例子中,当number等于3时,循环会终止。 + +_continue_:当我们想要跳过当前循环并继续执行下一个循环时,我们使用`continue`关键字。 + +```python + # syntax +for iterator in sequence: + code goes here + if condition: + continue +``` + +**示例:** + +```python +numbers = (0,1,2,3,4,5) +for number in numbers: + print(number) + if number == 3: + continue + print('Next number should be ', number + 1) if number != 5 else print("loop's end") # 简而言之,对于简短的条件,需要同时使用if和else语句 +print('outside the loop') +``` +在上面的例子中,当number等于3时,在此条件之后的(但在循环中的)语句会被跳过,如果还有未完成的遍历元素,它会继续执行下一个循环。 + +### range() 函数 + +`range()`函数用于生成一个序列的数字。_range(start, end, step)_函数接受三个参数:起始值、结束值和步长。默认情况下,起始值是0,步长是1。这个函数需要至少一个参数。(结束值end) + +使用`range()`函数生成序列 + +```python +lst = list(range(11)) +print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +st = set(range(1, 11)) # 两个参数分别代表start和stop,步长step为默认值1 +print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + +lst = list(range(0,11,2)) +print(lst) # [0, 2, 4, 6, 8, 10] +st = set(range(0,11,2)) +print(st) # {0, 2, 4, 6, 8, 10} +``` + +```python +# syntax +for iterator in range(start, end, step): +``` + +**示例:** + +```python +for number in range(11): + print(number) # 打印输出0到10,不包括11。 +``` + +### 嵌套for循环 + +我们可以在循环中嵌套另一个循环。这种循环称为嵌套循环。 + +```python +# syntax +for x in y: + for t in x: + print(t) +``` + +**示例:** + +```python +person = { + 'first_name': 'Asabeneh', + 'last_name': 'Yetayeh', + 'age': 250, + 'country': 'Finland', + 'is_marred': True, + 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address': { + 'street': 'Space street', + 'zipcode': '02210' + } +} +for key in person: + if key == 'skills': + for skill in person['skills']: + print(skill) +``` + +### for和else + +如果我们想要在循环结束时执行特定的代码块,我们可以使用`else`关键字。 + +```python +# syntax +for iterator in range(start, end, step): + do something +else: + print('The loop ended') +``` + +**示例:** + +```python +for number in range(11): + print(number) # prints 0 to 10, not including 11 +else: + print('The loop stops at', number) +``` + +### pass语句 + +在python中,当需要一些语句(比如在`:`后),但我们不想执行任何代码时,我们可以使用`pass`关键字来避免报错。此外,我们也可以用它来作为一个占位符,以便在以后填充代码。 + +**示例:** + +```python +for number in range(6): + pass +``` + +🌕 你完成了伟大的一步,太猛了哥。冲冲冲!你刚刚完成了第10天的挑战,你在通往伟大的道路上迈出了10步。现在我们做一些练习来练练肌肉和大脑。 + +## 💻 练习:第十天 + +### 练习:一级 + +1. 分别使用while和for实现从0到10的迭代。 +2. 分别使用while和for实现从10到0的迭代。 +3. 写一个循环,调用7次`print()`函数,输出如下的三角形: + ```py + # + ## + ### + #### + ##### + ###### + ####### + ``` + +4. 使用嵌套循环来实现下面的输出: + + ```sh + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + # # # # # # # # + ``` +5. 使用循环实现下面格式的输出: + ```sh + 0 x 0 = 0 + 1 x 1 = 1 + 2 x 2 = 4 + 3 x 3 = 9 + 4 x 4 = 16 + 5 x 5 = 25 + 6 x 6 = 36 + 7 x 7 = 49 + 8 x 8 = 64 + 9 x 9 = 81 + 10 x 10 = 100 + ``` +6. 用for循环遍历列表`['Python', 'Numpy','Pandas','Django', 'Flask']`,并打印输出每个元素。 +7. 用for循环从0到100遍历并且打印输出所有偶数。 +8. 用for循环从0到100遍历并且打印输出所有奇数。 + +### 练习:二级 + +1. 使用for循环从0到100遍历并且输出所有数字的和。 + ```sh + The sum of all numbers is 5050. + ``` +2. 使用for循环从0到100遍历并且分别输出所有奇数和所有偶数的和。 + ```sh + The sum of all odd numbers is 2500. And the sum of all even numbers is 2550. + ``` + +### 练习:三级 + +1. 跳转到data文件夹并使用[countries.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py)文件。循环遍历所有国家,并且提取出所有包含字母`land`的国家。 +2. 有一个列表`fruits = ['banana', 'orange', 'mango', 'lemon']`,使用循环反转列表中的元素。 +3. 跳转到data文件夹并使用[countries_data.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py)文件。 + 1. 数据中一共有多少个语言? + 2. 找到被最多国家使用的语言。 + 3. 找到人数排名前十的国家。 + +🎉 恭喜! 🎉 + +[<< Day 9](./09_conditionals.md) | [Day 11 >>](./11_functions.md) \ No newline at end of file From 0581ad54a69c8cea036eb377ff731c532bf90f12 Mon Sep 17 00:00:00 2001 From: Archie Date: Thu, 8 Aug 2024 21:56:55 +0100 Subject: [PATCH 43/63] add 11_Day_Functions --- Chinese/11_functions.md | 458 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 458 insertions(+) create mode 100644 Chinese/11_functions.md diff --git a/Chinese/11_functions.md b/Chinese/11_functions.md new file mode 100644 index 000000000..a7d8a4c76 --- /dev/null +++ b/Chinese/11_functions.md @@ -0,0 +1,458 @@ +
+

30 天 Python 挑战: 第 11 天 - 函数

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+ 第二版: 2021 年 7 月 +
+ +
+ +[<< 第 10 天](../10_Day_Loops/10_loops.md) | [第 12 天 >>](../12_Day_Modules/12_modules.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 第 11 天](#-day-11) + - [函数](#functions) + - [定义函数](#defining-a-function) + - [声明和调用函数](#declaring-and-calling-a-function) + - [无参数的函数](#function-without-parameters) + - [返回值的函数 - 第 1 部分](#function-returning-a-value---part-1) + - [有参数的函数](#function-with-parameters) + - [使用键值对传递参数](#passing-arguments-with-key-and-value) + - [返回值的函数 - 第 2 部分](#function-returning-a-value---part-2) + - [带默认参数的函数](#function-with-default-parameters) + - [不定数量的参数](#arbitrary-number-of-arguments) + - [函数中的默认和不定数量的参数](#default-and-arbitrary-number-of-parameters-in-functions) + - [作为另一个函数参数的函数](#function-as-a-parameter-of-another-function) + - [💻 练习: 第 11 天](#-exercises-day-11) + - [练习: Level 1](#exercises-level-1) + - [练习: Level 2](#exercises-level-2) + - [练习: Level 3](#exercises-level-3) + +# 📘 第 11 天 + +## 函数 + +到目前为止,我们已经学习了很多内置的 Python 函数。在这一节中,我们将重点关注自定义函数。什么是函数?在开始创建函数之前,让我们先了解一下什么是函数以及为什么需要它们。 + +### 定义函数 + +函数是一块可重复使用的代码块或编程语句,用于执行某些任务。要定义或声明一个函数,Python 提供了 _def_ 关键字。下面是定义函数的语法。只有在调用或触发函数时,这段函数代码才会执行。 + +### 声明和调用函数 + +当我们创建一个函数时,我们称其为声明一个函数。当我们开始使用它时,我们称其为调用或触发一个函数。函数可以带参数也可以不带参数。 + +```py +# 语法 +# 声明一个函数 +def function_name(): + codes + codes +# 调用一个函数 +function_name() +``` + +### 无参数的函数 + +函数可以在没有参数的情况下声明。 + +**示例:** + +```py +def generate_full_name (): + first_name = 'Asabeneh' + last_name = 'Yetayeh' + space = ' ' + full_name = first_name + space + last_name + print(full_name) +generate_full_name () # 调用一个函数 + +def add_two_numbers (): + num_one = 2 + num_two = 3 + total = num_one + num_two + print(total) +add_two_numbers() +``` + +### 返回值的函数 - 第 1 部分 + +函数也可以返回值,如果一个函数没有 return 语句,那么函数的返回值为 None。让我们使用 return 重写上述函数。从现在开始,当我们调用函数并打印时,我们会得到一个值。 + +```py +def generate_full_name (): + first_name = 'Asabeneh' + last_name = 'Yetayeh' + space = ' ' + full_name = first_name + space + last_name + return full_name +print(generate_full_name()) + +def add_two_numbers (): + num_one = 2 + num_two = 3 + total = num_one + num_two + return total +print(add_two_numbers()) +``` + +### 有参数的函数 + +在一个函数中,我们可以传递不同的数据类型(数字、字符串、布尔值、列表、元组、字典或集合)作为参数。 + +- 单个参数:如果我们的函数需要一个参数,我们应该用一个实参调用它。 + +```py + # 语法 + # 声明一个函数 + def function_name(parameter): + codes + codes + # 调用函数 + print(function_name(argument)) +``` + +**示例:** + +```py +def greetings (name): + message = name + ', welcome to Python for Everyone!' + return message + +print(greetings('Asabeneh')) + +def add_ten(num): + ten = 10 + return num + ten +print(add_ten(90)) + +def square_number(x): + return x * x +print(square_number(2)) + +def area_of_circle (r): + PI = 3.14 + area = PI * r ** 2 + return area +print(area_of_circle(10)) + +def sum_of_numbers(n): + total = 0 + for i in range(n+1): + total+=i + print(total) +print(sum_of_numbers(10)) # 55 +print(sum_of_numbers(100)) # 5050 +``` + +- 两个参数:一个函数可以没有参数,也可以有一个或多个参数。如果我们的函数需要两个参数,我们应该用两个实参调用它。让我们看看一个带有两个参数的函数: + +```py + # 语法 + # 声明一个函数 + def function_name(para1, para2): + codes + codes + # 调用函数 + print(function_name(arg1, arg2)) +``` + +**示例:** + +```py +def generate_full_name (first_name, last_name): + space = ' ' + full_name = first_name + space + last_name + return full_name +print('Full Name: ', generate_full_name('Asabeneh','Yetayeh')) + +def sum_two_numbers (num_one, num_two): + sum = num_one + num_two + return sum +print('Sum of two numbers: ', sum_two_numbers(1, 9)) + +def calculate_age (current_year, birth_year): + age = current_year - birth_year + return age; + +print('Age: ', calculate_age(2021, 1819)) + +def weight_of_object (mass, gravity): + weight = str(mass * gravity)+ ' N' # 值需要先转换为字符串 + return weight +print('Weight of an object in Newtons: ', weight_of_object(100, 9.81)) +``` + +### 使用键值对传递参数 + +如果我们使用键值对传递参数,参数的顺序就无关紧要了。 + +```py +# 语法 +# 声明一个函数 +def function_name(para1, para2): + codes + codes +# 调用函数 +print(function_name(para1 = 'John', para2 = 'Doe')) # 参数的顺序在这里无关紧要 +``` + +**示例:** + +```py +def print_fullname(firstname, lastname): + space = ' ' + full_name = firstname + space + lastname + print(full_name) +print(print_fullname(firstname = 'Asabeneh', lastname = 'Yetayeh')) + +def add_two_numbers (num1, num2): + total = num1 + num2 + print(total) +print(add_two_numbers(num2 = 3, num1 = 2)) # 顺序无关紧要 +``` + +### 返回值的函数 - 第 2 部分 + +如果我们不在函数中返回一个值,那么我们的函数默认返回 _None_。要用函数返回一个值,我们使用关键字 _return_,后面跟上我们要返回的变量。我们可以从一个函数返回任何类型的数据。 + +- 返回字符串: + **示例:** + +```py +def print_name(firstname): + return firstname +print_name('Asabeneh') # Asabeneh + +def print_full_name(firstname, lastname): + space = ' ' + full_name = firstname + space + lastname + return full_name +print_full_name(firstname='Asabeneh', lastname='Yetayeh') +``` + +- 返回数字: + +**示例:** + +```py +def add_two_numbers (num1, num2): + total = num1 + num2 + return total +print(add_two_numbers(2, 3)) + +def calculate_age (current_year, birth_year): + age = current_year - birth_year + return age; +print('Age: ', calculate_age(2019, 1819)) +``` + +- 返回布尔值: + **示例:** + +```py +def is_even (n): + if n % 2 == 0: + print('even') + return True # return 语句会停止函数的进一步执行,类似于 break + return False +print(is_even(10)) # True +print(is_even(7)) # False +``` + +- 返回列表: + **示例:** + +```py +def find_even_numbers(n): + evens = [] + for i in range(n + 1): + if i % 2 == 0: + evens.append(i) + return evens +print(find_even_numbers(10)) +``` + +### 带默认参数的函数 + +有时我们在调用函数时会传递默认值给参数。如果我们在调用函数时没有传递实参,参数的默认值将会被使用。 + +```py +# 语法 +# 声明一个函数 +def function_name(param = value): + codes + codes +# 调用函数 +function_name() +function_name(arg) +``` + +**示例:** + +```py +def greetings (name = 'Peter'): + message = name + ', welcome to Python for Everyone!' + return message +print(greetings()) +print(greetings('Asabeneh')) + +def generate_full_name (first_name = 'Asabeneh', last_name = 'Yetayeh'): + space = ' ' + full_name = first_name + space + last_name + return full_name + +print(generate_full_name()) +print(generate_full_name('David','Smith')) + +def calculate_age (birth_year,current_year = 2021): + age = current_year - birth_year + return age; +print('Age: ', calculate_age(1821)) + +def weight_of_object (mass, gravity = 9.81): + weight = str(mass * gravity)+ ' N' # 值需要先转换为字符串 + return weight +print('Weight of an object in Newtons: ', weight_of_object(100)) # 9.81 - 地球表面的平均重力 +print('Weight of an object in Newtons: ', weight_of_object(100, 1.62)) # 月球表面的重力 +``` + +### 不定数量的参数 + +如果我们不知道传递给函数的参数数量,可以通过在参数名前加上 \* 来创建一个可以接受不定数量参数的函数。 + +```py +# 语法 +# 声明一个函数 +def function_name(*args): + codes + codes +# 调用函数 +function_name(param1, param2, param3,..) +``` + +**示例:** + +```py +def sum_all_nums(*nums): + total = 0 + for num in nums: + total += num # 相当于 total = total + num + return total +print(sum_all_nums(2, 3, 5)) # 10 +``` + +### 函数中的默认和不定数量的参数 + +```py +def generate_groups (team,*args): + print(team) + for i in args: + print(i) +print(generate_groups('Team-1','Asabeneh','Brook','David','Eyob')) +``` + +### 作为另一个函数参数的函数 + +```py +# 你可以将函数作为参数传递 +def square_number (n): + return n * n +def do_something(f, x): + return f(x) +print(do_something(square_number, 3)) # 27 +``` + +🌕 你已经完成了很多。继续加油!你已经完成了第 11 天的挑战,你在走向成功的道路上已经迈出了 11 步。现在做一些锻炼脑力和肌肉的练习。 + +## 见证 + +现在是时候表达你对作者和 30DaysOfPython 的看法了。你可以在这个[链接](https://testimonify.herokuapp.com/)留下你的见证。 + +## 💻 练习: 第 11 天 + +### 练习: Level 1 + +1. 声明一个函数 _add_two_numbers_。它接受两个参数并返回它们的和。 +2. 圆的面积计算公式为:area = π x r x r。编写一个函数计算 _area_of_circle_。 +3. 编写一个名为 add_all_nums 的函数,它接受不定数量的参数并求和所有参数。检查所有列表项是否都是数字类型。如果不是,给予合理的反馈。 +4. 摄氏温度(°C)可以使用以下公式转换为华氏温度(°F):°F = (°C x 9/5) + 32。编写一个函数将 °C 转换为 °F,_convert_celsius_to_fahrenheit_。 +5. 编写一个名为 check-season 的函数,它接受一个月份作为参数并返回季节:秋季、冬季、春季或夏季。 +6. 编写一个名为 calculate_slope 的函数,它返回线性方程的斜率。 +7. 二次方程按以下公式计算:ax² + bx + c = 0。编写一个函数计算二次方程的解集,_solve_quadratic_eqn_。 +8. 声明一个名为 print_list 的函数。它接受一个列表作为参数,并打印列表的每个元素。 +9. 声明一个名为 reverse_list 的函数。它接受一个数组作为参数,并返回数组的反转(使用循环)。 + +```py +print(reverse_list([1, 2, 3, 4, 5])) +# [5, 4, 3, 2, 1] +print(reverse_list1(["A", "B", "C"])) +# ["C", "B", "A"] +``` + +10. 声明一个名为 capitalize_list_items 的函数。它接受一个列表作为参数,并返回一个大写的列表项。 +11. 声明一个名为 add_item 的函数。它接受一个列表和一个项作为参数。它返回在末尾添加项的列表。 + +```py +food_staff = ['Potato', 'Tomato', 'Mango', 'Milk']; +print(add_item(food_staff, 'Meat')) # ['Potato', 'Tomato', 'Mango', 'Milk','Meat']; +numbers = [2, 3, 7, 9]; +print(add_item(numbers, 5)) [2, 3, 7, 9, 5] +``` + +12. 声明一个名为 remove_item 的函数。它接受一个列表和一个项作为参数。它返回移除该项后的列表。 + +```py +food_staff = ['Potato', 'Tomato', 'Mango', 'Milk']; +print(remove_item(food_staff, 'Mango')) # ['Potato', 'Tomato', 'Milk']; +numbers = [2, 3, 7, 9]; +print(remove_item(numbers, 3)) # [2, 7, 9] +``` + +13. 声明一个名为 sum_of_numbers 的函数。它接受一个数字参数并将范围内的所有数字相加。 + +```py +print(sum_of_numbers(5)) # 15 +print(sum_all_numbers(10)) # 55 +print(sum_all_numbers(100)) # 5050 +``` + +14. 声明一个名为 sum_of_odds 的函数。它接受一个数字参数并将范围内的所有奇数相加。 +15. 声明一个名为 sum_of_even 的函数。它接受一个数字参数并将范围内的所有偶数相加。 + +### 练习: Level 2 + +1. 声明一个名为 evens_and_odds 的函数。它接受一个正整数作为参数并计算该数内偶数和奇数的数量。 + +```py + print(evens_and_odds(100)) + # 偶数的数量是 50。 + # 奇数的数量是 51。 +``` + +1. 调用你的函数 factorial,它接受一个整数作为参数并返回该数的阶乘。 +1. 调用你的函数 _is_empty_,它接受一个参数并检查它是否为空。 +1. 编写不同的函数,它们接受列表。它们应该计算平均值、计算中位数、计算众数、计算范围、计算方差、计算标准差。 + +### 练习: Level 3 + +1. 编写一个名为 is_prime 的函数,检查一个数是否是质数。 +1. 编写一个函数检查列表中的所有项是否都是唯一的。 +1. 编写一个函数检查列表中的所有项是否都是相同的数据类型。 +1. 编写一个函数检查提供的变量是否是一个有效的 python 变量。 +1. 访问数据文件并访问 countries-data.py 文件。 + +- 创建一个名为 the most_spoken_languages 的函数。它返回世界上使用最多的 10 或 20 种语言,按降序排列。 +- 创建一个名为 the most_populated_countries 的函数。它返回世界上人口最多的 10 或 20 个国家,按降序排列。 + +🎉 恭喜! 🎉 + +[<< 第 10 天](../10_Day_Loops/10_loops.md) | [第 12 天 >>](../12_Day_Modules/12_modules.md) From 88c1ba9a4e52ede982b61bf2479d89f56c4b1477 Mon Sep 17 00:00:00 2001 From: Archie Date: Sat, 10 Aug 2024 21:39:53 +0100 Subject: [PATCH 44/63] add 12 Day Modules Chinese support --- Chinese/12_modules.md | 303 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 303 insertions(+) create mode 100644 Chinese/12_modules.md diff --git a/Chinese/12_modules.md b/Chinese/12_modules.md new file mode 100644 index 000000000..1632a36c0 --- /dev/null +++ b/Chinese/12_modules.md @@ -0,0 +1,303 @@ +
+

30 天 Python :第 12 天 - 模块

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+第二版: 2021 年 7 月 +
+ +
+ + +[<< 第 11 天](../11_Day_Functions/11_functions.md) | [第 13 天>>](../13_Day_List_comprehension/13_list_comprehension.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 第 12 天](#-第12天) + - [模块](#模块) + - [什么是模块](#什么是模块) + - [创建模块](#创建模块) + - [导入模块](#导入模块) + - [从模块中导入函数](#从模块中导入函数) + - [从模块中导入函数并重命名](#从模块中导入函数并重命名) + - [导入内置模块](#导入内置模块) + - [OS 模块](#os-模块) + - [Sys 模块](#sys-模块) + - [统计模块](#统计模块) + - [数学模块](#数学模块) + - [字符串模块](#字符串模块) + - [随机模块](#随机模块) + - [💻 练习:第 12 天](#-练习-第12天) + - [练习:级别 1](#练习-级别-1) + - [练习:级别 2](#练习-级别-2) + - [练习:级别 3](#练习-级别-3) + +# 📘 第 12 天 + +## 模块 + +### 什么是模块 + +模块是包含一组代码或一组函数的文件,可以包含在一个应用程序中。一个模块可以是包含单个变量、函数或大规模代码库的文件。 + +### 创建模块 + +要创建模块,我们在一个 Python 脚本中编写代码并保存为 .py 文件。 在项目文件夹中创建一个名为 mymodule.py 的文件。让我们在此文件中编写一些代码。 + +```py +# mymodule.py 文件 +def generate_full_name(firstname, lastname): + return firstname + ' ' + lastname +``` + +在项目目录中创建 main.py 文件并导入 mymodule.py 文件。 + +### 导入模块 + +要导入文件,我们使用 _import_ 关键字和文件名。 + +```py +# main.py 文件 +import mymodule +print(mymodule.generate_full_name('Asabeneh', 'Yetayeh')) # Asabeneh Yetayeh +``` + +### 从模块中导入函数 + +我们可以在一个文件中有很多函数,并且我们可以分别导入所有函数。 + +```py +# main.py 文件 +from mymodule import generate_full_name, sum_two_nums, person, gravity +print(generate_full_name('Asabneh','Yetayeh')) +print(sum_two_nums(1,9)) +mass = 100 +weight = mass * gravity +print(weight) +print(person['firstname']) +``` + +### 从模块中导入函数并重命名 + +在导入过程中,我们可以重命名模块名称。 + +```py +# main.py 文件 +from mymodule import generate_full_name as fullname, sum_two_nums as total, person as p, gravity as g +print(fullname('Asabneh','Yetayeh')) +print(total(1, 9)) +mass = 100 +weight = mass * g +print(weight) +print(p) +print(p['firstname']) +``` + +## 导入内置模块 + +像其他编程语言一样,我们也可以通过使用关键字 _import_ 导入文件/函数来导入模块。让我们导入我们大多数时候会使用的常见模块。一些常见的内置模块:_math_、_datetime_、_os_、_sys_、_random_、_statistics_、_collections_、_json_、_re_ + +### OS 模块 + +使用 Python _os_ 模块可以自动执行许多操作系统任务。Python 中的 OS 模块提供了创建、更改当前工作目录和删除目录(文件夹)、获取其内容、更改和识别当前目录的函数。 + +```py +# 导入模块 +import os +# 创建目录 +os.mkdir('directory_name') +# 更改当前目录 +os.chdir('path') +# 获取当前工作目录 +os.getcwd() +# 删除目录 +os.rmdir() +``` + +### Sys 模块 + +sys 模块提供用于操作 Python 运行时环境不同部分的函数和变量。函数 sys.argv 返回传递给 Python 脚本的命令行参数列表。此列表中索引 0 处的项始终是脚本的名称,索引 1 处是从命令行传递的参数。 + +示例 script.py 文件: + +```py +import sys +#print(sys.argv[0], argv[1],sys.argv[2]) # 这一行会打印出来:文件名 argument1 argument2 +print('Welcome {}. Enjoy {} challenge!'.format(sys.argv[1], sys.argv[2])) +``` + +现在要查看这个脚本的工作效果,我在命令行中写: + +```sh +python script.py Asabeneh 30DaysOfPython +``` + +结果: + +```sh +Welcome Asabeneh. Enjoy 30DayOfPython challenge! +``` + +一些有用的 sys 命令: + +```py +# 退出 sys +sys.exit() +# 知道最大整数变量 +sys.maxsize +# 知道环境路径 +sys.path +# 知道使用的 Python 版本 +sys.version +``` + +### 统计模块 + +统计模块提供用于数值数据的数学统计的函数。这个模块中定义的流行统计函数:_mean_、_median_、_mode_、_stdev_ 等。 + +```py +from statistics import * # 导入所有统计模块 +ages = [20, 20, 4, 24, 25, 22, 26, 20, 23, 22, 26] +print(mean(ages)) # ~22.9 +print(median(ages)) # 23 +print(mode(ages)) # 20 +print(stdev(ages)) # ~2.3 +``` + +### 数学模块 + +包含许多数学运算和常数的模块。 + +```py +import math +print(math.pi) # 3.141592653589793, pi 常数 +print(math.sqrt(2)) # 1.4142135623730951, 平方根 +print(math.pow(2, 3)) # 8.0, 指数函数 +print(math.floor(9.81)) # 9, 向下取整 +print(math.ceil(9.81)) # 10, 向上取整 +print(math.log10(100)) # 2, 以 10 为底的对数 +``` + +现在,我们已经导入了包含大量函数的 _math_ 模块,可以帮助我们进行数学计算。要检查模块中包含哪些函数,我们可以使用 _help(math)_ 或 _dir(math)_。这将显示模块中的可用函数。如果我们只想从模块中导入特定的函数,我们可以这样导入: + +```py +from math import pi +print(pi) +``` + +也可以一次导入多个函数 + +```py +from math import pi, sqrt, pow, floor, ceil, log10 +print(pi) # 3.141592653589793 +print(sqrt(2)) # 1.4142135623730951 +print(pow(2, 3)) # 8.0 +print(floor(9.81)) # 9 +print(ceil(9.81)) # 10 +print(math.log10(100)) # 2 +``` + +但如果我们想要导入数学模块中的所有函数,可以使用 \* . + +```py +from math import * +print(pi) # 3.141592653589793, pi 常数 +print(sqrt(2)) # 1.4142135623730951, 平方根 +print(pow(2, 3)) # 8.0, 指数 +print(floor(9.81)) # 9, 向下取整 +print(ceil(9.81)) # 10, 向上取整 +print(math.log10(100)) # 2 +``` + +当我们导入时,我们也可以重命名函数名称。 + +```py +from math import pi as PI +print(PI) # 3.141592653589793 +``` + +### 字符串模块 + +字符串模块是一个很有用的模块。下面的例子展示了字符串模块的一些用法。 + +```py +import string +print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ +print(string.digits) # 0123456789 +print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ +``` + +### 随机模块 + +现在你已经熟悉了导入模块。让我们再进行一次导入以熟悉它。让我们导入 _random_ 模块,它会给我们一个 0 到 0.9999 之间的随机数。_random_ 模块有很多函数,但在本节中,我们将只使用 _random_ 和 _randint_。 + +```py +from random import random, randint +print(random()) # 它不需要任何参数;它返回一个介于 0 和 0.9999 之间的值 +print(randint(5, 20)) # 它返回一个介于 [5, 20] 之间的随机整数(含边界) +``` + +🌕 你走得很远了。继续努力!你刚刚完成第 12 天的挑战,现在你已经在通往伟大的路上迈出了 12 步。现在为你的大脑和肌肉做一些练习。 + +## 💻 练习:第 12 天 + +### 练习:级别 1 + +1. 编写一个生成六位数/字符 random_user_id 的函数。 + ```py + print(random_user_id()); + '1ee33d' + ``` +2. 修改上一个任务。声明一个名为 user_id_gen_by_user 的函数。它不接受任何参数,但接受两个输入。一个输入是字符的数量,另一个输入是应生成的 ID 数量。 + +```py +print(user_id_gen_by_user()) # 用户输入:5 5 +#输出: +#kcsy2 +#SMFYb +#bWmeq +#ZXOYh +#2Rgxf + +print(user_id_gen_by_user()) # 16 5 +#1GCSgPLMaBAVQZ26 +#YD7eFwNQKNs7qXaT +#ycArC5yrRupyG00S +#UbGxOFI7UXSWAyKN +#dIV0SSUTgAdKwStr +``` + +3. 编写一个名为 rgb_color_gen 的函数。它将生成 RGB 颜色(每个值范围从 0 到 255)。 + +```py +print(rgb_color_gen()) +# rgb(125,244,255) - 输出应该是这种形式 +``` + +### 练习:级别 2 + +1. 编写一个函数 list_of_hexa_colors,它返回一个数组中的任意数量的十六进制颜色(六个十六进制数写在 # 后面。十六进制数字系统由 16 个符号组成,0-9 和 前 6 个字母 a-f。查看任务 6 的输出示例)。 +2. 编写一个函数 list_of_rgb_colors,它返回一个数组中的任意数量的 RGB 颜色。 +3. 编写一个函数 generate_colors,它可以生成任意数量的十六进制或 RGB 颜色。 + +```py + generate_colors('hexa', 3) # ['#a3e12f','#03ed55','#eb3d2b'] + generate_colors('hexa', 1) # ['#b334ef'] + generate_colors('rgb', 3) # ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80'] + generate_colors('rgb', 1) # ['rgb(33,79, 176)'] +``` + +### 练习:级别 3 + +1. 调用你的函数 shuffle_list,它接受一个列表作为参数并返回一个打乱的列表。 +2. 编写一个函数,它在 0-9 的范围内返回七个随机数的数组。所有数字必须是唯一的。 + +🎉 恭喜! 🎉 + +[<< 第 11 天](../11_Day_Functions/11_functions.md) | [第 13 天>>](../13_Day_List_comprehension/13_list_comprehension.md) From e6aa1bb6dbc9c75ac7ce8a8e9e69217155aad9f6 Mon Sep 17 00:00:00 2001 From: Archie Date: Mon, 12 Aug 2024 23:09:11 +0100 Subject: [PATCH 45/63] add 13_Day_List_comprehension Chinese support --- Chinese/13_list_comprehension.md | 208 +++++++++++++++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 Chinese/13_list_comprehension.md diff --git a/Chinese/13_list_comprehension.md b/Chinese/13_list_comprehension.md new file mode 100644 index 000000000..d2b9887b0 --- /dev/null +++ b/Chinese/13_list_comprehension.md @@ -0,0 +1,208 @@ +
+

Python 30 天挑战:第 13 天 - 列表推导式

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+第二版: 2021 年 7 月 +
+ +
+ + +[<< 第 12 天](../12_Day_Modules/12_modules.md) | [第 14 天>>](../14_Day_Higher_order_functions/14_higher_order_functions.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 第 13 天](#📘-第-13-天) + - [列表推导式](#列表推导式) + - [Lambda 函数](#lambda函数) + - [创建 Lambda 函数](#创建-lambda-函数) + - [Lambda 函数在另一个函数中](#lambda-函数在另一个函数中) + - [💻 练习:第 13 天](#💻-练习第-13-天) + +# 📘 第 13 天 + +## 列表推导式 + +在 Python 中,列表推导式是一种从序列中创建列表的简洁方式。它是创建新列表的简短方法。列表推导式比使用 _for_ 循环处理列表快得多。 + +```py +# 语法 +[i for i in iterable if 表达式] +``` + +**例子: 1** + +例如,如果你想将字符串转换为字符列表。你可以使用几种方法。我们来看看其中的一些: + +```py +# 一种方法 +language = 'Python' +lst = list(language) # 将字符串转换为列表 +print(type(lst)) # list +print(lst) # ['P', 'y', 't', 'h', 'o', 'n'] + +# 第二种方法: 列表推导式 +lst = [i for i in language] +print(type(lst)) # list +print(lst) # ['P', 'y', 't', 'h', 'o', 'n'] +``` + +**例子: 2** + +例如,如果你想生成一个数字列表 + +```py +# 生成数字 +numbers = [i for i in range(11)] # 生成从0到10的数字 +print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +# 也可以在迭代过程中进行数学运算 +squares = [i * i for i in range(11)] +print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] + +# 还可以生成元组列表 +numbers = [(i, i * i) for i in range(11)] +print(numbers) # [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] +``` + +**例子: 3** + +列表推导式可以与 if 表达式结合使用 + +```py +# 生成偶数 +even_numbers = [i for i in range(21) if i % 2 == 0] # 生成从0到21的偶数列表 +print(even_numbers) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + +# 生成奇数 +odd_numbers = [i for i in range(21) if i % 2 != 0] # 生成从0到21的奇数列表 +print(odd_numbers) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + +# 过滤数字:让我们从下面的列表中过滤出正偶数 +numbers = [-8, -7, -3, -1, 0, 1, 3, 4, 5, 7, 6, 8, 10] +positive_even_numbers = [i for i in range(21) if i % 2 == 0 and i > 0] +print(positive_even_numbers) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + +# 扁平化三维数组 +list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +flattened_list = [number for row in list_of_lists for number in row] +print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9] +``` + +## Lambda 函数 + +Lambda 函数是没有名字的小匿名函数。它可以接受任意数量的参数,但只能有一个表达式。Lambda 函数类似于 JavaScript 中的匿名函数。当我们想在另一个函数中编写匿名函数时,需要它。 + +### 创建 Lambda 函数 + +要创建一个 lambda 函数,我们使用 _lambda_ 关键字,然后是一个或多个参数,再然后是一个表达式。请参阅下面的语法和示例。Lambda 函数不用 return,但它会隐式地返回表达式。 + +```py +# 语法 +x = lambda param1, param2, param3: param1 + param2 + param3 +print(x(arg1, arg2, arg3)) +``` + +**示例:** + +```py +# 命名函数 +def add_two_nums(a, b): + return a + b + +print(add_two_nums(2, 3)) # 5 + +# 让我们将上述函数更改为 lambda 函数 +add_two_nums = lambda a, b: a + b +print(add_two_nums(2, 3)) # 5 + +# 自调用 lambda 函数 +print((lambda a, b: a + b)(2, 3)) # 5 + +square = lambda x: x ** 2 +print(square(3)) # 9 +cube = lambda x: x ** 3 +print(cube(3)) # 27 + +# 多个变量 +multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c +print(multiple_variable(5, 5, 3)) # 22 +``` + +### Lambda 函数在另一个函数中 + +在另一个函数中使用 lambda 函数。 + +```py +def power(x): + return lambda n: x ** n + +cube = power(2)(3) # 函数 power 现在需要两个单独的括号中的参数 +print(cube) # 8 +two_power_of_five = power(2)(5) +print(two_power_of_five) # 32 +``` + +🌕 继续保持良好的工作。保持动力,天空才是你的极限!你已经完成了第 13 天的挑战,你已经向伟大的目标迈出了 13 步。现在为你的大脑和肌肉来做一些练习。 + +## 💻 练习: 第 13 天 + +1. 使用列表推导式过滤出列表中的负数和零: + ```py + numbers = [-4, -3, -2, -1, 0, 2, 4, 6] + ``` +2. 将以下列表中的列表展平为一维列表: + + ```py + list_of_lists = [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]] + + 输出: + [1, 2, 3, 4, 5, 6, 7, 8, 9] + ``` + +3. 使用列表推导式创建以下元组列表: + ```py + [(0, 1, 0, 0, 0, 0, 0), + (1, 1, 1, 1, 1, 1, 1), + (2, 1, 2, 4, 8, 16, 32), + (3, 1, 3, 9, 27, 81, 243), + (4, 1, 4, 16, 64, 256, 1024), + (5, 1, 5, 25, 125, 625, 3125), + (6, 1, 6, 36, 216, 1296, 7776), + (7, 1, 7, 49, 343, 2401, 16807), + (8, 1, 8, 64, 512, 4096, 32768), + (9, 1, 9, 81, 729, 6561, 59049), + (10, 1, 10, 100, 1000, 10000, 100000)] + ``` +4. 将以下列表展平成一个新列表: + ```py + countries = [[('芬兰', '赫尔辛基')], [('瑞典', '斯德哥尔摩')], [('挪威', '奥斯陆')]] + 输出: + [['芬兰', '汇编', '赫尔辛基'], ['瑞典', 'SWE', '斯德哥尔摩'], ['挪威', 'NOR', '奥斯陆']] + ``` +5. 将以下列表转换为字典列表: + ```py + countries = [[('芬兰', '赫尔辛基')], [('瑞典', '斯德哥尔摩')], [('挪威', '奥斯陆')]] + 输出: + [{'国家': '芬兰', '城市': '赫尔辛基'}, + {'国家': '瑞典', '城市': '斯德哥尔摩'}, + {'国家': '挪威', '城市': '奥斯陆'}] + ``` +6. 将以下列表转换为连接字符串的列表: + ```py + names = [[('Asabeneh', 'Yetayeh')], [('David', 'Smith')], [('Donald', 'Trump')], [('Bill', 'Gates')]] + 输出: + ['Asabeneh Yetayeh', 'David Smith', 'Donald Trump', 'Bill Gates'] + ``` +7. 编写一个 lambda 函数,可以求解线性函数的斜率或 y 截距。 + +🎉 祝贺你!🎉 + +[<< 第 12 天](../12_Day_Modules/12_modules.md) | [第 14 天>>](../14_Day_Higher_order_functions/14_higher_order_functions.md) From e8e8d25c6f532284cd11c8faf5e699597de9a657 Mon Sep 17 00:00:00 2001 From: Archie Date: Wed, 14 Aug 2024 21:04:43 +0100 Subject: [PATCH 46/63] add 14_Day_Higher_order_functions Chinese support --- Chinese/14_higher_order_functions.md | 368 +++++++++++++++++++++++++++ 1 file changed, 368 insertions(+) create mode 100644 Chinese/14_higher_order_functions.md diff --git a/Chinese/14_higher_order_functions.md b/Chinese/14_higher_order_functions.md new file mode 100644 index 000000000..be1b415dd --- /dev/null +++ b/Chinese/14_higher_order_functions.md @@ -0,0 +1,368 @@ +
+

30天Python:第14天 - 高阶函数

+ + + + + Twitter Follow + + +作者: +Asabeneh Yetayeh
+第二版:2021 年 7 月 +
+ +
+ +[<< 第 13 天](../13_Day_List_comprehension/13_list_comprehension.md) | [第 15 天>>](../15_Day_Python_type_errors/15_python_type_errors.md) + +![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) + +- [📘 第 14 天](#-第14天) + - [高阶函数](#高阶函数) + - [函数作为参数](#函数作为参数) + - [函数作为返回值](#函数作为返回值) + - [Python 闭包](#python闭包) + - [Python 装饰器](#python装饰器) + - [创建装饰器](#创建装饰器) + - [将多个装饰器应用于单个函数](#将多个装饰器应用于单个函数) + - [在装饰器函数中接受参数](#在装饰器函数中接受参数) + - [内置高阶函数](#内置高阶函数) + - [Python - Map 函数](#python---map函数) + - [Python - Filter 函数](#python---filter函数) + - [Python - Reduce 函数](#python---reduce函数) + - [💻 练习:第 14 天](#-练习-第14天) + - [练习:简单](#练习-简单) + - [练习:中等](#练习-中等) + - [练习:高级](#练习-高级) + +# 📘 第 14 天 + +## 高阶函数 + +在 Python 中,函数被视为第一类公民,可以对函数执行以下操作: + +- 一个函数可以接收一个或多个函数作为参数 +- 一个函数可以作为另一个函数的返回值 +- 一个函数可以被修改 +- 一个函数可以被赋值给变量 + +在本节中,我们将讨论: + +1. 将函数作为参数传递 +2. 将函数作为返回值返回 +3. 使用 Python 闭包和装饰器 + +### 函数作为参数 + +```py +def sum_numbers(nums): # 普通函数 + return sum(nums) # 使用内置函数sum的函数 + +def higher_order_function(f, lst): # 将函数作为参数 + summation = f(lst) + return summation +result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5]) +print(result) # 15 +``` + +### 函数作为返回值 + +```py +def square(x): # 求平方函数 + return x ** 2 + +def cube(x): # 求立方函数 + return x ** 3 + +def absolute(x): # 求绝对值函数 + if x >= 0: + return x + else: + return -(x) + +def higher_order_function(type): # 返回一个函数的高阶函数 + if type == 'square': + return square + elif type == 'cube': + return cube + elif type == 'absolute': + return absolute + +result = higher_order_function('square') +print(result(3)) # 9 +result = higher_order_function('cube') +print(result(3)) # 27 +result = higher_order_function('absolute') +print(result(-3)) # 3 +``` + +从上述示例中可以看到,高阶函数根据传入的参数来返回不同的函数。 + +## Python 闭包 + +Python 允许嵌套函数访问外部封闭函数的作用域。 这称为闭包。 让我们看看闭包在 Python 中的工作原理。在 Python 中,闭包是通过在另一个封装函数内部嵌套函数,然后返回内部函数来创建的。请看下面的例子。 + +**示例:** + +```py +def add_ten(): + ten = 10 + def add(num): + return num + ten + return add + +closure_result = add_ten() +print(closure_result(5)) # 15 +print(closure_result(10)) # 20 +``` + +## Python 装饰器 + +装饰器是一种设计模式,允许用户在不修改对象结构的情况下为其添加新功能。装饰器通常在你想要装饰的函数定义之前调用。 + +### 创建装饰器 + +要创建装饰器函数,我们需要一个带有内部包装器函数的外部函数。 + +**示例:** + +```py +# 普通函数 +def greeting(): + return 'Welcome to Python' +def uppercase_decorator(function): + def wrapper(): + func = function() + make_uppercase = func.upper() + return make_uppercase + return wrapper +g = uppercase_decorator(greeting) +print(g()) # WELCOME TO PYTHON + +# 使用装饰器实现上面的示例 + +'''这个装饰器函数是一个高阶函数,接收一个函数作为参数''' +def uppercase_decorator(function): + def wrapper(): + func = function() + make_uppercase = func.upper() + return make_uppercase + return wrapper +@uppercase_decorator +def greeting(): + return 'Welcome to Python' +print(greeting()) # WELCOME TO PYTHON +``` + +### 将多个装饰器应用于单个函数 + +```py + +'''这些装饰器函数是高阶函数,接收函数作为参数''' + +# 第一个装饰器 +def uppercase_decorator(function): + def wrapper(): + func = function() + make_uppercase = func.upper() + return make_uppercase + return wrapper + +# 第二个装饰器 +def split_string_decorator(function): + def wrapper(): + func = function() + splitted_string = func.split() + return splitted_string + + return wrapper + +@split_string_decorator +@uppercase_decorator # 在此情况下,装饰器的顺序很重要 - .upper()函数不适用于列表 +def greeting(): + return 'Welcome to Python' +print(greeting()) # WELCOME TO PYTHON +``` + +### 在装饰器函数中接受参数 + +大多数时候我们需要我们的函数接受参数,所以我们可能需要定义一个接受参数的装饰器。 + +```py +def decorator_with_parameters(function): + def wrapper_accepting_parameters(para1, para2, para3): + function(para1, para2, para3) + print("I live in {}".format(para3)) + return wrapper_accepting_parameters + +@decorator_with_parameters +def print_full_name(first_name, last_name, country): + print("I am {} {}. I love to teach.".format( + first_name, last_name, country)) + +print_full_name("Asabeneh", "Yetayeh",'Finland') +``` + +## 内置高阶函数 + +在本部分中,我们将讨论一些内置的高阶函数,如*map()*, *filter*和*reduce*。 +Lambda 函数可以作为参数传递,其最佳使用案例是在地图、过滤和减少等功能中。 + +### Python - Map 函数 + +map()函数是一个内置函数,接收一个函数和可迭代对象作为参数。 + +```py + # 语法 + map(function, iterable) +``` + +**示例:1** + +```py +numbers = [1, 2, 3, 4, 5] # 可迭代对象 +def square(x): + return x ** 2 +numbers_squared = map(square, numbers) +print(list(numbers_squared)) # [1, 4, 9, 16, 25] +# 让我们应用lambda函数 +numbers_squared = map(lambda x : x ** 2, numbers) +print(list(numbers_squared)) # [1, 4, 9, 16, 25] +``` + +**示例:2** + +```py +numbers_str = ['1', '2', '3', '4', '5'] # 可迭代对象 +numbers_int = map(int, numbers_str) +print(list(numbers_int)) # [1, 2, 3, 4, 5] +``` + +**示例:3** + +```py +names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # 可迭代对象 + +def change_to_upper(name): + return name.upper() + +names_upper_cased = map(change_to_upper, names) +print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM'] + +# 让我们应用lambda函数 +names_upper_cased = map(lambda name: name.upper(), names) +print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM'] +``` + +map 函数实际上是迭代列表。例如,它将名称更改为大写并返回一个新列表。 + +### Python - Filter 函数 + +filter()函数调用指定函数,该函数对指定的可迭代对象(列表)中的每个项目返回布尔值。它过滤出满足过滤条件的项目。 + +```py + # 语法 + filter(function, iterable) +``` + +**示例:1** + +```py +# 让我们只过滤偶数 +numbers = [1, 2, 3, 4, 5] # 可迭代对象 + +def is_even(num): + if num % 2 == 0: + return True + return False + +even_numbers = filter(is_even, numbers) +print(list(even_numbers)) # [2, 4] +``` + +**示例:2** + +```py +numbers = [1, 2, 3, 4, 5] # 可迭代对象 + +def is_odd(num): + if num % 2 != 0: + return True + return False + +odd_numbers = filter(is_odd, numbers) +print(list(odd_numbers)) # [1, 3, 5] +``` + +```py +# 过滤长名称 +names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # 可迭代对象 +def is_name_long(name): + if len(name) > 7: + return True + return False + +long_names = filter(is_name_long, names) +print(list(long_names)) # ['Asabeneh'] +``` + +### Python - Reduce 函数 + +*reduce()*函数定义在 functools 模块中,我们需要从这个模块中导入它。像 map 和 filter 一样,它接收两个参数,一个函数和一个可迭代对象。然而,它不返回另一个可迭代对象,而是返回一个单一的值。 +**示例:1** + +```py +numbers_str = ['1', '2', '3', '4', '5'] # 可迭代对象 +def add_two_nums(x, y): + return int(x) + int(y) + +total = reduce(add_two_nums, numbers_str) +print(total) # 15 +``` + +## 💻 练习:第 14 天 + +```py +countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland'] +names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +``` + +### 练习:简单 + +1. 解释 map、filter 和 reduce 的区别。 +2. 解释高阶函数、闭包和装饰器的区别。 +3. 定义调用函数,见示例。 +4. 使用 for 循环打印 countries 列表中的每个国家。 +5. 使用 for 循环打印 names 列表中的每个名称。 +6. 使用 for 循环打印 numbers 列表中的每个数字。 + +### 练习:中等 + +1. 使用 map 将 countries 列表中的每个国家更改为大写,生成一个新列表。 +2. 使用 map 将 numbers 列表中的每个数字更改为平方,生成一个新列表。 +3. 使用 map 将 names 列表中的每个名称更改为大写,生成一个新列表。 +4. 使用 filter 过滤出包含“land”的国家。 +5. 使用 filter 过滤出正好六个字符的国家。 +6. 使用 filter 过滤出包含六个字母及以上的国家。 +7. 使用 filter 过滤出以'E'开头的国家。 +8. 链接两个或多个列表迭代器(例如 arr.map(callback).filter(callback).reduce(callback))。 +9. 声明一个函数 get_string_lists,它接收一个列表作为参数并返回一个仅包含字符串项的列表。 +10. 使用 reduce 对 numbers 列表中的所有数字求和。 +11. 使用 reduce 将所有国家连接起来,生成句子:Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries。 +12. 声明一个函数 categorize_countries,返回一个包含某种通用模式的国家列表(可以在本仓库的 countries.js 文件中找到国家列表,例如 'land', 'ia', 'island', 'stan')。 +13. 创建一个返回字典的函数,其中键表示国家名称的首字母,值表示以该字母开头的国家数。 +14. 声明一个 get_first_ten_countries 函数 - 它返回数据文件夹中 countries.js 列表中的前十个国家。 +15. 声明一个 get_last_ten_countries 函数 - 它返回国家列表中的最后十个国家。 + +### 练习:高级 + +1. 使用 countries_data.py (https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) 文件,完成以下任务: + - 按国家名称、首都和人口排序国家 + - 按位置排序出前十个最常用语言。 + - 排序出前十个人口最多的国家。 + +🎉 恭喜你! 🎉 + +[<< 第 13 天](../13_Day_List_comprehension/13_list_comprehension.md) | [第 15 天>>](../15_Day_Python_type_errors/15_python_type_errors.md) From cb74247d2418049b89065102963614d6b93c85f1 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Wed, 9 Oct 2024 11:40:24 +0300 Subject: [PATCH 47/63] big changes --- 01_Day_Introduction/helloworld.py | 8 ++-- .../02_variables_builtin_functions.md | 42 +++++++++--------- 04_Day_Strings/04_strings.md | 3 +- 05_Day_Lists/05_lists.md | 2 +- 07_Day_Sets/07_sets.md | 4 +- 08_Day_Dictionaries/08_dictionaries.md | 2 +- 09_Day_Conditionals/09_conditionals.md | 43 +++++++++++-------- 11_Day_Functions/11_functions.md | 22 +++++----- .../13_list_comprehension.md | 2 +- 16_Day_Python_date_time/16_python_datetime.md | 4 +- .../17_exception_handling.md | 4 +- 24_Day_Statistics/24_statistics.md | 2 +- .../27_python_with_mongodb.md | 9 ++-- 30_Day_Conclusions/30_conclusions.md | 3 +- readme.md | 21 +++++---- 15 files changed, 96 insertions(+), 75 deletions(-) diff --git a/01_Day_Introduction/helloworld.py b/01_Day_Introduction/helloworld.py index cfded3c68..9c5f92cdf 100644 --- a/01_Day_Introduction/helloworld.py +++ b/01_Day_Introduction/helloworld.py @@ -1,9 +1,9 @@ # Introduction # Day 1 - 30DaysOfPython Challenge -print(2 + 3) # addition(+) -print(3 - 1) # subtraction(-) -print(2 * 3) # multiplication(*) +print(3 + 2) # addition(+) +print(3 - 2) # subtraction(-) +print(3 * 2) # multiplication(*) print(3 / 2) # division(/) print(3 ** 2) # exponential(**) print(3 % 2) # modulus(%) @@ -19,3 +19,5 @@ print(type({'name':'Asabeneh'})) # Dictionary print(type({9.8, 3.14, 2.7})) # Set print(type((9.8, 3.14, 2.7))) # Tuple +print(type(3 == 3)) # Bool +print(type(3 >= 3)) # Bool diff --git a/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md index 4646285e0..400b990c2 100644 --- a/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md +++ b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md @@ -180,7 +180,7 @@ There are several data types in Python. To identify the data type we use the _ty ## Checking Data types and Casting - Check Data types: To check the data type of certain data/variable we use the _type_ - **Example:** + **Examples:** ```py # Different python data types @@ -193,22 +193,22 @@ city= 'Helsinki' # str age = 250 # int, it is not my real age, don't worry about it # Printing out types -print(type('Asabeneh')) # str -print(type(first_name)) # str -print(type(10)) # int -print(type(3.14)) # float -print(type(1 + 1j)) # complex -print(type(True)) # bool -print(type([1, 2, 3, 4])) # list -print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict -print(type((1,2))) # tuple -print(type(zip([1,2],[3,4]))) # set +print(type('Asabeneh')) # str +print(type(first_name)) # str +print(type(10)) # int +print(type(3.14)) # float +print(type(1 + 1j)) # complex +print(type(True)) # bool +print(type([1, 2, 3, 4])) # list +print(type({'name':'Asabeneh'})) # dict +print(type((1,2))) # tuple +print(type(zip([1,2],[3,4]))) # zip ``` - Casting: Converting one data type to another data type. We use _int()_, _float()_, _str()_, _list_, _set_ When we do arithmetic operations string numbers should be first converted to int or float otherwise it will return an error. If we concatenate a number with a string, the number should be first converted to a string. We will talk about concatenation in String section. - **Example:** + **Examples:** ```py # int to float @@ -229,8 +229,10 @@ print(num_str) # '10' # str to int or float num_str = '10.6' -print('num_int', int(num_str)) # 10 +num_float = float(num_str) print('num_float', float(num_str)) # 10.6 +num_int = int(num_float) +print('num_int', int(num_int)) # 10 # str to list first_name = 'Asabeneh' @@ -281,13 +283,13 @@ Number data types in Python: 1. Using the _len()_ built-in function, find the length of your first name 1. Compare the length of your first name and your last name 1. Declare 5 as num_one and 4 as num_two - 1. Add num_one and num_two and assign the value to a variable total - 2. Subtract num_two from num_one and assign the value to a variable diff - 3. Multiply num_two and num_one and assign the value to a variable product - 4. Divide num_one by num_two and assign the value to a variable division - 5. Use modulus division to find num_two divided by num_one and assign the value to a variable remainder - 6. Calculate num_one to the power of num_two and assign the value to a variable exp - 7. Find floor division of num_one by num_two and assign the value to a variable floor_division +1. Add num_one and num_two and assign the value to a variable total +1. Subtract num_two from num_one and assign the value to a variable diff +1. Multiply num_two and num_one and assign the value to a variable product +1. Divide num_one by num_two and assign the value to a variable division +1. Use modulus division to find num_two divided by num_one and assign the value to a variable remainder +1. Calculate num_one to the power of num_two and assign the value to a variable exp +1. Find floor division of num_one by num_two and assign the value to a variable floor_division 1. The radius of a circle is 30 meters. 1. Calculate the area of a circle and assign the value to a variable name of _area_of_circle_ 2. Calculate the circumference of a circle and assign the value to a variable name of _circum_of_circle_ diff --git a/04_Day_Strings/04_strings.md b/04_Day_Strings/04_strings.md index 5b5648ba0..3bf09ed2a 100644 --- a/04_Day_Strings/04_strings.md +++ b/04_Day_Strings/04_strings.md @@ -373,8 +373,9 @@ print(challenge.index(sub_string, 9)) # error ```py challenge = 'thirty days of python' sub_string = 'da' -print(challenge.rindex(sub_string)) # 8 +print(challenge.rindex(sub_string)) # 7 print(challenge.rindex(sub_string, 9)) # error +print(challenge.rindex('on', 8)) # 19 ``` - isalnum(): Checks alphanumeric character diff --git a/05_Day_Lists/05_lists.md b/05_Day_Lists/05_lists.md index fea7f515c..19a1a7049 100644 --- a/05_Day_Lists/05_lists.md +++ b/05_Day_Lists/05_lists.md @@ -562,7 +562,7 @@ To sort lists we can use _sort()_ method or _sorted()_ built-in functions. The _ back_end = ['Node','Express', 'MongoDB'] ``` -27. After joining the lists in question 26. Copy the joined list and assign it to a variable full_stack. Then insert Python and SQL after Redux. +27. After joining the lists in question 26. Copy the joined list and assign it to a variable full_stack, then insert Python and SQL after Redux. ### Exercises: Level 2 diff --git a/07_Day_Sets/07_sets.md b/07_Day_Sets/07_sets.md index 12bc2ca43..3c61dd07c 100644 --- a/07_Day_Sets/07_sets.md +++ b/07_Day_Sets/07_sets.md @@ -343,7 +343,7 @@ dragon.difference(python) # {'d', 'r', 'a', 'g'} ### Finding Symmetric Difference Between Two Sets -It returns the the symmetric difference between two sets. It means that it returns a set that contains all items from both sets, except items that are present in both sets, mathematically: (A\B) ∪ (B\A) +It returns the symmetric difference between two sets. It means that it returns a set that contains all items from both sets, except items that are present in both sets, mathematically: (A\B) ∪ (B\A) ```py # syntax @@ -380,7 +380,7 @@ st2.isdisjoint(st1) # False ```py even_numbers = {0, 2, 4 ,6, 8} -even_numbers = {1, 3, 5, 7, 9} +odd_numbers = {1, 3, 5, 7, 9} even_numbers.isdisjoint(odd_numbers) # True, because no common item python = {'p', 'y', 't', 'h', 'o','n'} diff --git a/08_Day_Dictionaries/08_dictionaries.md b/08_Day_Dictionaries/08_dictionaries.md index 20248a1de..8d6bc2c44 100644 --- a/08_Day_Dictionaries/08_dictionaries.md +++ b/08_Day_Dictionaries/08_dictionaries.md @@ -89,7 +89,7 @@ person = { 'last_name':'Yetayeh', 'age':250, 'country':'Finland', - 'is_marred':True, + 'is_married':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', diff --git a/09_Day_Conditionals/09_conditionals.md b/09_Day_Conditionals/09_conditionals.md index 578ea5780..522bbac33 100644 --- a/09_Day_Conditionals/09_conditionals.md +++ b/09_Day_Conditionals/09_conditionals.md @@ -29,6 +29,8 @@ - [If and Or Logical Operators](#if-and-or-logical-operators) - [💻 Exercises: Day 9](#-exercises-day-9) - [Exercises: Level 1](#exercises-level-1) + - [Exercises: Level 2](#exercises-level-2) + - [Exercises: Level 3](#exercises-level-3) # 📘 Day 9 @@ -72,7 +74,7 @@ else: this part of code runs for false conditions ``` -**Example: ** +**Example:** ```py a = 3 @@ -82,7 +84,7 @@ else: print('A is a positive number') ``` -The condition above proves false, therefore the else block was executed. How about if our condition is more than two? We could use _ elif_. +The condition above proves false, therefore the else block was executed. How about if our condition is more than two? We could use _elif_. ### If Elif Else @@ -99,7 +101,7 @@ else: ``` -**Example: ** +**Example:** ```py a = 0 @@ -118,7 +120,7 @@ else: code if condition else code ``` -**Example: ** +**Example:** ```py a = 3 @@ -137,7 +139,7 @@ if condition: code ``` -**Example: ** +**Example:** ```py a = 0 @@ -163,7 +165,7 @@ if condition and condition: code ``` -**Example: ** +**Example:** ```py a = 0 @@ -185,7 +187,7 @@ if condition or condition: code ``` -**Example: ** +**Example:** ```py user = 'James' @@ -202,7 +204,8 @@ else: ### Exercises: Level 1 -1. Get user input using input(“Enter your age: ”). If user is 18 or older, give feedback: You are old enough to drive. If below 18 give feedback to wait for the missing amount of years. Output: +1. Get user input using input(“Enter your age: ”). If user is 18 or older, give feedback: You are old enough to drive. If below 18 give feedback to wait for the missing amount of years. Output: + ```sh Enter your age: 30 You are old enough to learn to drive. @@ -210,12 +213,15 @@ else: Enter your age: 15 You need 3 more years to learn to drive. ``` -2. Compare the values of my_age and your_age using if … else. Who is older (me or you)? Use input(“Enter your age: ”) to get the age as input. You can use a nested condition to print 'year' for 1 year difference in age, 'years' for bigger differences, and a custom text if my_age = your_age. Output: + +2. Compare the values of my_age and your_age using if … else. Who is older (me or you)? Use input(“Enter your age: ”) to get the age as input. You can use a nested condition to print 'year' for 1 year difference in age, 'years' for bigger differences, and a custom text if my_age = your_age. Output: + ```sh Enter your age: 30 You are 5 years older than me. ``` -3. Get two numbers from the user using input prompt. If a is greater than b return a is greater than b, if a is less b return a is smaller than b, else a is equal to b. Output: + +3. Get two numbers from the user using input prompt. If a is greater than b return a is greater than b, if a is less b return a is smaller than b, else a is equal to b. Output: ```sh Enter number one: 4 @@ -223,10 +229,10 @@ Enter number two: 3 4 is greater than 3 ``` - ### Exercises: Level 2 +### Exercises: Level 2 1. Write a code which gives grade to students according to theirs scores: - + ```sh 80-100, A 70-89, B @@ -234,21 +240,24 @@ Enter number two: 3 50-59, D 0-49, F ``` -1. Check if the season is Autumn, Winter, Spring or Summer. If the user input is: + + 1. Check if the season is Autumn, Winter, Spring or Summer. If the user input is: September, October or November, the season is Autumn. December, January or February, the season is Winter. March, April or May, the season is Spring June, July or August, the season is Summer -2. The following list contains some fruits: + 2. The following list contains some fruits: + ```sh fruits = ['banana', 'orange', 'mango', 'lemon'] ``` - If a fruit doesn't exist in the list add the fruit to the list and print the modified list. If the fruit exists print('That fruit already exist in the list') - ### Exercises: Level 3 + If a fruit doesn't exist in the list add the fruit to the list and print the modified list. If the fruit exists print('That fruit already exist in the list') + +### Exercises: Level 3 1. Here we have a person dictionary. Feel free to modify it! - + ```py person={ 'first_name': 'Asabeneh', diff --git a/11_Day_Functions/11_functions.md b/11_Day_Functions/11_functions.md index a80e5bfb4..2a0ad39b8 100644 --- a/11_Day_Functions/11_functions.md +++ b/11_Day_Functions/11_functions.md @@ -31,6 +31,7 @@ - [Arbitrary Number of Arguments](#arbitrary-number-of-arguments) - [Default and Arbitrary Number of Parameters in Functions](#default-and-arbitrary-number-of-parameters-in-functions) - [Function as a Parameter of Another Function](#function-as-a-parameter-of-another-function) + - [Testimony](#testimony) - [💻 Exercises: Day 11](#-exercises-day-11) - [Exercises: Level 1](#exercises-level-1) - [Exercises: Level 2](#exercises-level-2) @@ -48,7 +49,7 @@ A function is a reusable block of code or programming statements designed to per ### Declaring and Calling a Function -When we make a function, we call it declaring a function. When we start using the it, we call it *calling* or *invoking* a function. Function can be declared with or without parameters. +When we make a function, we call it declaring a function. When we start using the it, we call it _calling_ or _invoking_ a function. Function can be declared with or without parameters. ```py # syntax @@ -374,7 +375,8 @@ print(do_something(square_number, 3)) # 27 🌕 You achieved quite a lot so far. Keep going! You have just completed day 11 challenges and you are 11 steps a head in to your way to greatness. Now do some exercises for your brain and muscles. ## Testimony -Now it is time to express your thoughts about the Author and 30DaysOfPython. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/) + +Now it is time to express your thoughts about the Author and 30DaysOfPython. You can leave your testimonial on this [link](https://testimonial-s3sw.onrender.com/) ## 💻 Exercises: Day 11 @@ -401,18 +403,18 @@ print(reverse_list1(["A", "B", "C"])) 11. Declare a function named add_item. It takes a list and an item parameters. It returns a list with the item added at the end. ```py -food_staff = ['Potato', 'Tomato', 'Mango', 'Milk']; -print(add_item(food_staff, 'Meat')) # ['Potato', 'Tomato', 'Mango', 'Milk','Meat']; -numbers = [2, 3, 7, 9]; +food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'] +print(add_item(food_staff, 'Meat')) # ['Potato', 'Tomato', 'Mango', 'Milk','Meat'] +numbers = [2, 3, 7, 9] print(add_item(numbers, 5)) [2, 3, 7, 9, 5] ``` 12. Declare a function named remove_item. It takes a list and an item parameters. It returns a list with the item removed from it. ```py -food_staff = ['Potato', 'Tomato', 'Mango', 'Milk']; +food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'] print(remove_item(food_staff, 'Mango')) # ['Potato', 'Tomato', 'Milk']; -numbers = [2, 3, 7, 9]; +numbers = [2, 3, 7, 9] print(remove_item(numbers, 3)) # [2, 7, 9] ``` @@ -420,8 +422,8 @@ print(remove_item(numbers, 3)) # [2, 7, 9] ```py print(sum_of_numbers(5)) # 15 -print(sum_all_numbers(10)) # 55 -print(sum_all_numbers(100)) # 5050 +print(sum_of_numbers(10)) # 55 +print(sum_of_numbers(100)) # 5050 ``` 14. Declare a function named sum_of_odds. It takes a number parameter and it adds all the odd numbers in that range. @@ -429,7 +431,7 @@ print(sum_all_numbers(100)) # 5050 ### Exercises: Level 2 -1. Declare a function named evens_and_odds . It takes a positive integer as parameter and it counts number of evens and odds in the number. +1. Declare a function named evens_and_odds . It takes a positive integer as parameter and it counts number of evens and odds in the number. ```py print(evens_and_odds(100)) diff --git a/13_Day_List_comprehension/13_list_comprehension.md b/13_Day_List_comprehension/13_list_comprehension.md index d5c392f1c..a2cd9aa99 100644 --- a/13_Day_List_comprehension/13_list_comprehension.md +++ b/13_Day_List_comprehension/13_list_comprehension.md @@ -89,7 +89,7 @@ odd_numbers = [i for i in range(21) if i % 2 != 0] # to generate odd numbers in print(odd_numbers) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] # Filter numbers: let's filter out positive even numbers from the list below numbers = [-8, -7, -3, -1, 0, 1, 3, 4, 5, 7, 6, 8, 10] -positive_even_numbers = [i for i in range(21) if i % 2 == 0 and i > 0] +positive_even_numbers = [i for i in numbers if i % 2 == 0 and i > 0] print(positive_even_numbers) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # Flattening a three dimensional array diff --git a/16_Day_Python_date_time/16_python_datetime.md b/16_Day_Python_date_time/16_python_datetime.md index 65172be3b..e103a599e 100644 --- a/16_Day_Python_date_time/16_python_datetime.md +++ b/16_Day_Python_date_time/16_python_datetime.md @@ -25,7 +25,7 @@ - [Using *date* from *datetime*](#using-date-from-datetime) - [Time Objects to Represent Time](#time-objects-to-represent-time) - [Difference Between Two Points in Time Using](#difference-between-two-points-in-time-using) - - [Difference Between Two Points in Time Using *timedelata*](#difference-between-two-points-in-time-using-timedelata) + - [Difference Between Two Points in Time Using *timedelta*](#difference-between-two-points-in-time-using-timedelta) - [💻 Exercises: Day 16](#-exercises-day-16) # 📘 Day 16 @@ -173,7 +173,7 @@ diff = t2 - t1 print('Time left for new year:', diff) # Time left for new year: 26 days, 23: 01: 00 ``` -### Difference Between Two Points in Time Using *timedelata* +### Difference Between Two Points in Time Using *timedelta* ```py from datetime import timedelta diff --git a/17_Day_Exception_handling/17_exception_handling.md b/17_Day_Exception_handling/17_exception_handling.md index b9d533509..c5d082388 100644 --- a/17_Day_Exception_handling/17_exception_handling.md +++ b/17_Day_Exception_handling/17_exception_handling.md @@ -107,7 +107,7 @@ try: name = input('Enter your name:') year_born = input('Year you born:') age = 2019 - int(year_born) - print('You are {name}. And your age is {age}.') + print(f'You are {name}. And your age is {age}.') except TypeError: print('Type error occur') except ValueError: @@ -135,7 +135,7 @@ try: name = input('Enter your name:') year_born = input('Year you born:') age = 2019 - int(year_born) - print('You are {name}. And your age is {age}.') + print(f'You are {name}. And your age is {age}.') except Exception as e: print(e) diff --git a/24_Day_Statistics/24_statistics.md b/24_Day_Statistics/24_statistics.md index 4978e3c27..cd3c62788 100644 --- a/24_Day_Statistics/24_statistics.md +++ b/24_Day_Statistics/24_statistics.md @@ -1218,7 +1218,7 @@ plt.show() ![png](../test_files/test_143_0.png) -# Summery +# Summary To summarize, the main differences with python lists are: diff --git a/27_Day_Python_with_mongodb/27_python_with_mongodb.md b/27_Day_Python_with_mongodb/27_python_with_mongodb.md index b708ed92c..2214d84cf 100644 --- a/27_Day_Python_with_mongodb/27_python_with_mongodb.md +++ b/27_Day_Python_with_mongodb/27_python_with_mongodb.md @@ -88,7 +88,7 @@ Select Python 3.6 or above driver ### Getting Connection String(MongoDB URI) -Copy the connection string link and you will get something like this +Copy the connection string link and you will get something like this: ```sh mongodb+srv://asabeneh:@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority @@ -103,7 +103,7 @@ Let us replace the password placeholder with the password you used to add a user mongodb+srv://asabeneh:123123123@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority ``` -Now, I replaced everything and the password is 123123 and the name of the database is thirty_days_python. This is just an example, your password must be a bit stronger than this. +Now, I replaced everything and the password is 123123 and the name of the database is *thirty_days_python*. This is just an example, your password must be stronger than the example password. Python needs a mongoDB driver to access mongoDB database. We will use _pymongo_ with _dnspython_ to connect our application with mongoDB base . Inside your project directory install pymongo and dnspython. @@ -140,8 +140,9 @@ When we run the above code we get the default mongoDB databases. ### Creating a database and collection -Let us create a database, database and collection in mongoDB will be created if it doesn't exist. Let's create a data base name _thirty_days_of_python_ and _students_ collection. -To create a database +Let us create a database, database and collection in mongoDB will be created if it doesn't exist. Let's create a data base name *thirty_days_of_python* and *students* collection. + +To create a database: ```sh db = client.name_of_databse # we can create a database like this or the second way diff --git a/30_Day_Conclusions/30_conclusions.md b/30_Day_Conclusions/30_conclusions.md index e8865fc6a..c3cb3b8f7 100644 --- a/30_Day_Conclusions/30_conclusions.md +++ b/30_Day_Conclusions/30_conclusions.md @@ -21,6 +21,7 @@ - [Day 30](#day-30) - [Conclusions](#conclusions) + - [Testimony](#testimony) # Day 30 @@ -30,7 +31,7 @@ In the process of preparing this material I have learned quite a lot and you have inspired me to do more. Congratulations for making it to this level. If you have done all the exercise and the projects, now you are capable to go to a data analysis, data science, machine learning or web development paths. [Support the author for more educational materials](https://www.paypal.com/paypalme/asabeneh). ## Testimony -Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://testimonial-vdzd.onrender.com/) +Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://testimonial-s3sw.onrender.com/) GIVE FEEDBACK: http://thirtydayofpython-api.herokuapp.com/feedback diff --git a/readme.md b/readme.md index 5bd0eb887..0a899ecb9 100644 --- a/readme.md +++ b/readme.md @@ -1,5 +1,7 @@ # 🐍 30 Days Of Python + Learn with Asabeneh by joining the upcoming [CODING BOOTCAMP](https://docs.google.com/forms/d/e/1FAIpQLSf0oNIYR9XU1DCctfl-pY36KbWse-SQX5aQaUgetqSinFYnmQ/viewform) + |# Day | Topics | |------|:---------------------------------------------------------:| | 01 | [Introduction](./readme.md)| @@ -33,6 +35,8 @@ | 29 | [Building API](./29_Day_Building_API/29_building_API.md)| | 30 | [Conclusions](./30_Day_Conclusions/30_conclusions.md)| + Learn with Asabeneh by joining the upcoming [CODING BOOTCAMP](https://docs.google.com/forms/d/e/1FAIpQLSf0oNIYR9XU1DCctfl-pY36KbWse-SQX5aQaUgetqSinFYnmQ/viewform) + 🧡🧡🧡 HAPPY CODING 🧡🧡🧡
@@ -92,24 +96,24 @@ ## Welcome -**Congratulations** for deciding to participate in a _30 days of Python_ programming challenge . In this challenge you will learn everything you need to be a python programmer and the whole concept of programming. In the end of the challenge you will get a _30DaysOfPython_ programming challenge certificate. +**Congratulations** for deciding to participate in a _30 days of Python_ programming challenge. In this challenge, you will learn everything you need to be a python programmer and the whole concept of programming. At the end of the challenge, you will get a _30DaysOfPython_ programming challenge certificate. If you would like to actively engage in the challenge, you may join the [30DaysOfPython challenge](https://t.me/ThirtyDaysOfPython) telegram group. ## Introduction -Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of Python programming language was derived from a British sketch comedy series, _Monty Python's Flying Circus_. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, many hands on exercises and projects. +Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of the Python programming language was derived from a British sketch comedy series, *Monty Python's Flying Circus*. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, and many hands on exercises and projects. -This challenge is designed for beginners and professionals who want to learn python programming language. It may take 30 to 100 days to complete the challenge, people who actively participate on the telegram group have a high probability of completing the challenge. +This challenge is designed for beginners and professionals who want to learn python programming language. It may take 30 to 100 days to complete the challenge. People who actively participate in the telegram group have a high probability of completing the challenge. This challenge is easy to read, written in conversational English, engaging, motivating and at the same time, it is very demanding. You need to allocate much time to finish this challenge. If you are a visual learner, you may get the video lesson on Washera YouTube channel. You may start from [Python for Absolute Beginners video](https://youtu.be/OCCWZheOesI). Subscribe the channel, comment and ask questions on YouTube vidoes and be proactive, the author will eventually notice you. -The author likes to hear your opinion about the challenge, share the author by expressing your thoughts about the 30DaysOfPython challenge. You can leave your testimonial on this [link](https://testimonial-vdzd.onrender.com/) +The author likes to hear your opinion about the challenge, share the author by expressing your thoughts about the 30DaysOfPython challenge. You can leave your testimonial on this [link](https://testimonial-s3sw.onrender.com/) ## Why Python ? -It is a programming language which is very close to human language and because of that it is easy to learn and use. -Python is used by various industries and companies (including Google). It has been used to develop web applications, desktop applications, system adminstration, and machine learning libraries. Python is highly embraced language in the data science and machine learning community. I hope this is enough to convince you to start learning Python. Python is eating the world and you are killing it before it eats you. +It is a programming language which is very close to human language and because of that, it is easy to learn and use. +Python is used by various industries and companies (including Google). It has been used to develop web applications, desktop applications, system administration, and machine learning libraries. Python is a highly embraced language in the data science and machine learning community. I hope this is enough to convince you to start learning Python. Python is eating the world and you are killing it before it eats you. ## Environment Setup @@ -245,14 +249,13 @@ A Python script can be written in Python interactive shell or in the code editor ### Python Indentation -An indentation is a white space in a text. Indentation in many languages is used to increase code readability, however Python uses indentation to create block of codes. In other programming languages curly brackets are used to create blocks of codes instead of indentation. One of the common bugs when writing python code is wrong indentation. +An indentation is a white space in a text. Indentation in many languages is used to increase code readability; however, Python uses indentation to create blocks of code. In other programming languages, curly brackets are used to create code blocks instead of indentation. One of the common bugs when writing Python code is incorrect indentation. ![Indentation Error](./images/indentation.png) ### Comments -Comments are very important to make the code more readable and to leave remarks in our code. Python does not run comment parts of our code. -Any text starting with hash(#) in Python is a comment. +Comments play a crucial role in enhancing code readability and allowing developers to leave notes within their code. In Python, any text preceded by a hash (#) symbol is considered a comment and is not executed when the code runs. **Example: Single Line Comment** From 40b3e0be19b883ff9817dba8d6de420f8cb2b1e0 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Tue, 11 Feb 2025 11:57:55 +0200 Subject: [PATCH 48/63] link modified --- 30_Day_Conclusions/30_conclusions.md | 2 +- Chinese/README.md | 12 ++++++----- Portuguese/README.md | 30 ++++++++++++++-------------- readme.md | 2 +- 4 files changed, 24 insertions(+), 22 deletions(-) diff --git a/30_Day_Conclusions/30_conclusions.md b/30_Day_Conclusions/30_conclusions.md index c3cb3b8f7..3bbb084d0 100644 --- a/30_Day_Conclusions/30_conclusions.md +++ b/30_Day_Conclusions/30_conclusions.md @@ -31,7 +31,7 @@ In the process of preparing this material I have learned quite a lot and you have inspired me to do more. Congratulations for making it to this level. If you have done all the exercise and the projects, now you are capable to go to a data analysis, data science, machine learning or web development paths. [Support the author for more educational materials](https://www.paypal.com/paypalme/asabeneh). ## Testimony -Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://testimonial-s3sw.onrender.com/) +Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://www.asabeneh.com/testimonials) GIVE FEEDBACK: http://thirtydayofpython-api.herokuapp.com/feedback diff --git a/Chinese/README.md b/Chinese/README.md index e49895221..76747b167 100644 --- a/Chinese/README.md +++ b/Chinese/README.md @@ -61,10 +61,10 @@ ![30DaysOfPython](.././images/30DaysOfPython_banner3@2x.png) - [🐍 30 天 Python](#-30-天-python) -- [📘 第 1 天](#第-1-天) - - [欢迎](#欢迎) +- [📘 第 1 天](#-第-1-天) + - [欢迎!](#欢迎) - [介绍](#介绍) - - [为什么选择 Python?](#为什么选择-python) + - [为什么选择 Python?](#为什么选择-python) - [环境设置](#环境设置) - [安装 Python](#安装-python) - [Python Shell](#python-shell) @@ -74,6 +74,8 @@ - [Python 语法](#python-语法) - [Python 缩进](#python-缩进) - [注释](#注释) +- [示例:单行注释](#示例单行注释) +- [示例:多行注释,称为文档字符串](#示例多行注释称为文档字符串) - [数据类型](#数据类型) - [数字](#数字) - [字符串](#字符串) @@ -84,7 +86,7 @@ - [集合](#集合) - [检查数据类型](#检查数据类型) - [Python 文件](#python-文件) - - [💻 练习 - 第 1 天](#-练习-第-1-天) + - [💻 练习 - 第 1 天](#-练习---第-1-天) - [练习:等级 1](#练习等级-1) - [练习:等级 2](#练习等级-2) - [练习:等级 3](#练习等级-3) @@ -106,7 +108,7 @@ Python 是一种高级编程语言,适用于通用编程。它是一种开源 本挑战易于阅读,最初以通俗英语编写,并翻译成中文,既具有吸引力、激励性,又具有很高的挑战性。你需要投入大量时间来完成这个挑战。如果你是通过观看学习效果更好的人,可以观看视频教程,访问 Washera YouTube 频道 你可以从 [Python 对绝对初学者的视频](https://youtu.be/OCCWZheOesI) 开始。订阅频道,在 YouTube 视频中评论你的问题,并积极主动,作者最终会注意到你。 -作者喜欢听取你对挑战的意见,分享文章并反馈你对 30DaysOfPython 挑战的看法。你可以在此处留下对文章的反馈:[link](https://testimonial-vdzd.onrender.com/) +作者喜欢听取你对挑战的意见,分享文章并反馈你对 30DaysOfPython 挑战的看法。你可以在此处留下对文章的反馈:[link](https://www.asabeneh.com/testimonials) ## 为什么选择 Python? diff --git a/Portuguese/README.md b/Portuguese/README.md index 09feb4a88..45c9bb693 100644 --- a/Portuguese/README.md +++ b/Portuguese/README.md @@ -59,31 +59,31 @@ ![30DaysOfPython](.././images/30DaysOfPython_banner3@2x.png) -- [🐍 30 Dias De Python](#-30-dias-de-python) -- [📘 Dia 1](#Dia-1) - - [Bem Vindo](#welcome) +- [🐍 30 Dias de python](#-30-dias-de-python) +- [📘 Dia 1](#-dia-1) + - [Bem Vindo!](#bem-vindo) - [Introdução](#introdução) - - [Por quê Python ?](#Por-quê-python) - - [Setup do ambiente](#Setup-do-ambiente) + - [Por quê Python?](#por-quê-python) + - [Setup do ambiente](#setup-do-ambiente) - [Instalando o Python](#instalando-o-python) - [Python Shell](#python-shell) - [Instalando o Visual Studio Code](#instalando-o-visual-studio-code) - - [Como usar o visual studio code](#como-usar-o-visual-studio-code) + - [Como usar o Visual Studio Code](#como-usar-o-visual-studio-code) - [Basico de Python](#basico-de-python) - - [Sintaxe do Python](#Sintaxe-do-python) - - [Indentação do Python](#indentaçao-do-python) - - [Comentários](#comentarios) + - [Sintaxe do Python](#sintaxe-do-python) + - [Identação do Python](#identação-do-python) + - [Comentários](#comentários) - [Tipos de dados](#tipos-de-dados) - - [Numeros](#numeros) + - [Números](#números) - [Strings](#strings) - [Booleanos](#booleanos) - [Listas](#listas) - - [Dicionários](#dicionarios) - - [Tuplas](#tupla) + - [Dicionário](#dicionário) + - [Tupla](#tupla) - [Set](#set) - - [Checando tipos de dados](#checando-tipos-de-dados) + - [Checando Tipos de Dados](#checando-tipos-de-dados) - [Arquivo Python](#arquivo-python) - - [💻 Exercicios - Dia 1](#-exercicios-dia-1) + - [💻 Exercicios - Dia 1](#-exercicios---dia-1) - [Exercicio: Level 1](#exercicio-level-1) - [Exercicio: Level 2](#exercicio-level-2) - [Exercicio: Level 3](#exercicio-level-3) @@ -105,7 +105,7 @@ Este desafio foi desenvolvido para iniciantes e profissionais que desejam aprend Este desafio é fácil de ler, escrito originalmente em inglês coloquial e traduzido para um português, envolvente, motivador e ao mesmo tempo muito exigente. Você precisa destinar muito tempo para terminar este desafio. Se você é um dos que aprendem melhor vendo, você pode assistir às vídeo-aulas em Canal do Youtube do Washera Você pode começar pelo [Video de Python para iniciantes absolutos](https://youtu.be/OCCWZheOesI). Se inscreva no canal, comente suas dúvidas nos vídeos do YouTube e seja proativo, o autor eventualmente notará você. -O autor gosta de ouvir sua opinião sobre o desafio, compartilhe o artigo do autor dando um feedback com sua opinião sobre o desafio 30DiasDePython. E você pode deixar seu feedback sobre o artigo em: [link](https://testimonial-vdzd.onrender.com/) +O autor gosta de ouvir sua opinião sobre o desafio, compartilhe o artigo do autor dando um feedback com sua opinião sobre o desafio 30DiasDePython. E você pode deixar seu feedback sobre o artigo em: [link](https://www.asabeneh.com/testimonials) ## Por quê Python? diff --git a/readme.md b/readme.md index 064fe8816..95bae55af 100644 --- a/readme.md +++ b/readme.md @@ -111,7 +111,7 @@ This challenge is designed for beginners and professionals who want to learn pyt This challenge is easy to read, written in conversational English, engaging, motivating and at the same time, it is very demanding. You need to allocate much time to finish this challenge. If you are a visual learner, you may get the video lesson on Washera YouTube channel. You may start from [Python for Absolute Beginners video](https://youtu.be/OCCWZheOesI). Subscribe the channel, comment and ask questions on YouTube vidoes and be proactive, the author will eventually notice you. -The author likes to hear your opinion about the challenge, share the author by expressing your thoughts about the 30DaysOfPython challenge. You can leave your testimonial on this [link](https://testimonial-s3sw.onrender.com/) +The author likes to hear your opinion about the challenge, share the author by expressing your thoughts about the 30DaysOfPython challenge. You can leave your testimonial on this [link](https://www.asabeneh.com/testimonials) ## Why Python ? From 201b90a8203c770de7e9f4e982fcd4464b1ad5fe Mon Sep 17 00:00:00 2001 From: hoshino <19860620884@163.com> Date: Mon, 17 Mar 2025 21:47:43 +0800 Subject: [PATCH 49/63] Add files via upload --- Chinese/15_python_type_errors_cn.md | 344 ++++++++++ Chinese/16_python_datetime_cn.md | 192 ++++++ Chinese/17_exception_handling_cn.md | 285 +++++++++ Chinese/18_regular_expressions_cn.md | 417 ++++++++++++ Chinese/19_file_handling_cn.md | 549 ++++++++++++++++ Chinese/20_python_package_manager_cn.md | 352 ++++++++++ Chinese/21_classes_and_objects_cn.md | 419 ++++++++++++ Chinese/22_web_scraping_cn.md | 89 +++ Chinese/23_virtual_environment_cn.md | 97 +++ Chinese/24_statistics_cn.md | 589 +++++++++++++++++ Chinese/25_pandas_cn.md | 551 ++++++++++++++++ Chinese/26_python_web_cn.md | 817 ++++++++++++++++++++++++ Chinese/27_python_with_mongodb_cn.md | 632 ++++++++++++++++++ Chinese/28_API_cn.md | 143 +++++ Chinese/29_building_API_cn.md | 460 +++++++++++++ Chinese/30_conclusions_cn.md | 22 + 16 files changed, 5958 insertions(+) create mode 100644 Chinese/15_python_type_errors_cn.md create mode 100644 Chinese/16_python_datetime_cn.md create mode 100644 Chinese/17_exception_handling_cn.md create mode 100644 Chinese/18_regular_expressions_cn.md create mode 100644 Chinese/19_file_handling_cn.md create mode 100644 Chinese/20_python_package_manager_cn.md create mode 100644 Chinese/21_classes_and_objects_cn.md create mode 100644 Chinese/22_web_scraping_cn.md create mode 100644 Chinese/23_virtual_environment_cn.md create mode 100644 Chinese/24_statistics_cn.md create mode 100644 Chinese/25_pandas_cn.md create mode 100644 Chinese/26_python_web_cn.md create mode 100644 Chinese/27_python_with_mongodb_cn.md create mode 100644 Chinese/28_API_cn.md create mode 100644 Chinese/29_building_API_cn.md create mode 100644 Chinese/30_conclusions_cn.md diff --git a/Chinese/15_python_type_errors_cn.md b/Chinese/15_python_type_errors_cn.md new file mode 100644 index 000000000..13c9cc87f --- /dev/null +++ b/Chinese/15_python_type_errors_cn.md @@ -0,0 +1,344 @@ +# 30天Python编程挑战:第15天 - Python类型错误 + +- [Day 15](#day-15) + - [Python错误类型](#python错误类型) + - [SyntaxError (语法错误)](#syntaxerror-语法错误) + - [NameError (名称错误)](#nameerror-名称错误) + - [IndexError (索引错误)](#indexerror-索引错误) + - [ModuleNotFoundError (模块未找到错误)](#modulenotfounderror-模块未找到错误) + - [AttributeError (属性错误)](#attributeerror-属性错误) + - [KeyError (键错误)](#keyerror-键错误) + - [TypeError (类型错误)](#typeerror-类型错误) + - [ImportError (导入错误)](#importerror-导入错误) + - [ValueError (值错误)](#valueerror-值错误) + - [ZeroDivisionError (零除错误)](#zerodivisionerror-零除错误) + - [💻 练习 - 第15天](#-练习---第15天) + +# 📘 Day 15 + +## Python错误类型 + +当我们编写代码时,常常会出现打字错误或其他常见错误。如果我们的代码运行失败,Python解释器会显示一条消息,提供有关问题发生位置和错误类型的反馈信息。有时它还会给我们提供可能的修复建议。了解编程语言中不同类型的错误将帮助我们快速调试代码,并使我们在编程技能上有所提高。 + +让我们一一查看最常见的错误类型。首先,让我们打开Python交互式shell。转到你的计算机终端并输入'python'。Python交互式shell将会被打开。 + +### SyntaxError (语法错误) + +**示例1: SyntaxError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print 'hello world' + File "", line 1 + print 'hello world' + ^ +SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')? +>>> +``` + +如你所见,我们犯了一个语法错误,因为我们忘记用括号括起字符串,而Python已经提出了解决方案。让我们修复它。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print 'hello world' + File "", line 1 + print 'hello world' + ^ +SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')? +>>> print('hello world') +hello world +>>> +``` + +错误是一个_SyntaxError_。修复后,我们的代码顺利执行。让我们看看更多的错误类型。 + +### NameError (名称错误) + +**示例1: NameError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print(age) +Traceback (most recent call last): + File "", line 1, in +NameError: name 'age' is not defined +>>> +``` + +从上面的消息可以看出,名称age没有被定义。是的,确实如此,我们没有定义age变量,但我们试图像已经声明了一样打印它。现在,让我们通过声明变量并为其赋值来修复这个问题。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print(age) +Traceback (most recent call last): + File "", line 1, in +NameError: name 'age' is not defined +>>> age = 25 +>>> print(age) +25 +>>> +``` + +错误类型是_NameError_。我们通过定义变量名来调试了错误。 + +### IndexError (索引错误) + +**示例1: IndexError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> numbers = [1, 2, 3, 4, 5] +>>> numbers[5] +Traceback (most recent call last): + File "", line 1, in +IndexError: list index out of range +>>> +``` + +在上面的例子中,Python抛出了一个_IndexError_,因为列表的索引只有0到4,所以索引5超出了范围。 + +### ModuleNotFoundError (模块未找到错误) + +**示例1: ModuleNotFoundError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> +``` + +在上面的例子中,我故意在math后面添加了一个多余的s,结果抛出了_ModuleNotFoundError_。让我们通过从math中删除多余的s来修复它。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> import math +>>> +``` + +我们修复了它,所以让我们使用math模块中的一些函数。 + +### AttributeError (属性错误) + +**示例1: AttributeError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> import math +>>> math.PI +Traceback (most recent call last): + File "", line 1, in +AttributeError: module 'math' has no attribute 'PI' +>>> +``` + +如你所见,我又犯了一个错误!我试图从math模块调用PI函数,而不是pi。这抛出了一个属性错误,表示该函数在模块中不存在。让我们通过将PI更改为pi来修复它。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> import math +>>> math.PI +Traceback (most recent call last): + File "", line 1, in +AttributeError: module 'math' has no attribute 'PI' +>>> math.pi +3.141592653589793 +>>> +``` + +现在,当我们从math模块调用pi时,我们得到了结果。 + +### KeyError (键错误) + +**示例1: KeyError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> users = {'name':'Asab', 'age':250, 'country':'Finland'} +>>> users['name'] +'Asab' +>>> users['county'] +Traceback (most recent call last): + File "", line 1, in +KeyError: 'county' +>>> +``` + +如你所见,在用于获取字典值的键中有一个拼写错误。这是一个键错误,修复方法很简单。让我们来做这个! + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> user = {'name':'Asab', 'age':250, 'country':'Finland'} +>>> user['name'] +'Asab' +>>> user['county'] +Traceback (most recent call last): + File "", line 1, in +KeyError: 'county' +>>> user['country'] +'Finland' +>>> +``` + +我们调试了错误,我们的代码运行并得到了结果。 + +### TypeError (类型错误) + +**示例1: TypeError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> 4 + '3' +Traceback (most recent call last): + File "", line 1, in +TypeError: unsupported operand type(s) for +: 'int' and 'str' +>>> +``` + +在上面的例子中,出现了TypeError,因为我们不能将数字与字符串相加。第一个解决方案是将字符串转换为int或float。另一个解决方案是将数字转换为字符串(那么结果将是'43')。让我们采用第一种修复方式。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> 4 + '3' +Traceback (most recent call last): + File "", line 1, in +TypeError: unsupported operand type(s) for +: 'int' and 'str' +>>> 4 + int('3') +7 +>>> 4 + float('3') +7.0 +>>> +``` + +错误已消除,我们得到了预期的结果。 + +### ImportError (导入错误) + +**示例1: ImportError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> from math import power +Traceback (most recent call last): + File "", line 1, in +ImportError: cannot import name 'power' from 'math' +>>> +``` + +math模块中没有名为power的函数,它的名字是不同的:_pow_。让我们纠正它: + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> from math import power +Traceback (most recent call last): + File "", line 1, in +ImportError: cannot import name 'power' from 'math' +>>> from math import pow +>>> pow(2,3) +8.0 +>>> +``` + +### ValueError (值错误) + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> int('12a') +Traceback (most recent call last): + File "", line 1, in +ValueError: invalid literal for int() with base 10: '12a' +>>> +``` + +在这种情况下,我们无法将给定的字符串转换为数字,因为其中有字母'a'。 + +### ZeroDivisionError (零除错误) + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> 1/0 +Traceback (most recent call last): + File "", line 1, in +ZeroDivisionError: division by zero +>>> +``` + +我们不能用零去除一个数字。 + +我们已经介绍了一些Python错误类型,如果你想了解更多,请查看Python文档中关于Python错误类型的内容。 +如果你擅长阅读错误类型,那么你将能够快速修复你的bug,你也将成为一个更好的程序员。 + +🌕 你正在进步。你已经完成了一半的道路,正走向伟大。现在做一些练习来锻炼你的大脑和肌肉。 + +## 💻 练习 - 第15天 + +1. 打开你的Python交互式shell,尝试本节中介绍的所有示例。 + +🎉 恭喜!🎉 + +[<< 第14天](../14_Day_Higher_order_functions/14_higher_order_functions_cn.md) | [第16天 >>](../16_Day_Python_date_time/16_python_datetime_cn.md) \ No newline at end of file diff --git a/Chinese/16_python_datetime_cn.md b/Chinese/16_python_datetime_cn.md new file mode 100644 index 000000000..c833d4210 --- /dev/null +++ b/Chinese/16_python_datetime_cn.md @@ -0,0 +1,192 @@ +# 30天Python编程挑战:第16天 - Python日期时间 + +- [第16天](#-第16天) + - [Python *datetime*](#python-datetime) + - [获取 *datetime* 信息](#获取-datetime-信息) + - [使用 *strftime* 格式化日期输出](#使用-strftime-格式化日期输出) + - [使用 *strptime* 将字符串转换为时间](#使用-strptime-将字符串转换为时间) + - [从 *datetime* 使用 *date*](#从-datetime-使用-date) + - [使用Time对象表示时间](#使用time对象表示时间) + - [计算两个时间点之间的差异](#计算两个时间点之间的差异) + - [使用 *timedelta* 计算两个时间点之间的差异](#使用-timedelta-计算两个时间点之间的差异) + - [💻 练习 - 第16天](#-练习---第16天) + +# 📘 第16天 + +## Python *datetime* + +Python有一个 _datetime_ 模块用于处理日期和时间。 + +```py +import datetime +print(dir(datetime)) +['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo'] +``` + +通过dir或help内置命令,可以了解特定模块中可用的函数。如你所见,datetime模块中有许多函数,但我们将重点关注 _date_、_datetime_、_time_ 和 _timedelta_。让我们一个一个地看。 + +### 获取 *datetime* 信息 + +```py +from datetime import datetime +now = datetime.now() +print(now) # 2021-07-08 07:34:46.549883 +day = now.day # 8 +month = now.month # 7 +year = now.year # 2021 +hour = now.hour # 7 +minute = now.minute # 38 +second = now.second +timestamp = now.timestamp() +print(day, month, year, hour, minute) +print('timestamp', timestamp) +print(f'{day}/{month}/{year}, {hour}:{minute}') # 8/7/2021, 7:38 +``` + +时间戳或Unix时间戳是从1970年1月1日UTC开始经过的秒数。 + +### 使用 *strftime* 格式化日期输出 + +```py +from datetime import datetime +new_year = datetime(2020, 1, 1) +print(new_year) # 2020-01-01 00:00:00 +day = new_year.day +month = new_year.month +year = new_year.year +hour = new_year.hour +minute = new_year.minute +second = new_year.second +print(day, month, year, hour, minute) #1 1 2020 0 0 +print(f'{day}/{month}/{year}, {hour}:{minute}') # 1/1/2020, 0:0 + +``` + +使用 *strftime* 方法格式化日期时间,相关文档可以在[这里](https://strftime.org/)找到。 + +```py +from datetime import datetime +# 当前日期和时间 +now = datetime.now() +t = now.strftime("%H:%M:%S") +print("时间:", t) +time_one = now.strftime("%m/%d/%Y, %H:%M:%S") +# mm/dd/YY H:M:S 格式 +print("时间一:", time_one) +time_two = now.strftime("%d/%m/%Y, %H:%M:%S") +# dd/mm/YY H:M:S 格式 +print("时间二:", time_two) +``` + +```sh +时间: 01:05:01 +时间一: 12/05/2019, 01:05:01 +时间二: 05/12/2019, 01:05:01 +``` + +以下是我们用来格式化时间的所有 _strftime_ 符号。这个模块的所有格式示例。 + +![strftime](../images/strftime.png) + +### 使用 *strptime* 将字符串转换为时间 +这里有一个[文档](https://www.programiz.com/python-programming/datetime/strptimet),有助于理解格式。 + +```py +from datetime import datetime +date_string = "5 December, 2019" +print("date_string =", date_string) +date_object = datetime.strptime(date_string, "%d %B, %Y") +print("date_object =", date_object) +``` + +```sh +date_string = 5 December, 2019 +date_object = 2019-12-05 00:00:00 +``` + +### 从 *datetime* 使用 *date* + +```py +from datetime import date +d = date(2020, 1, 1) +print(d) +print('当前日期:', d.today()) # 2019-12-05 +# 今天的日期对象 +today = date.today() +print("当前年份:", today.year) # 2019 +print("当前月份:", today.month) # 12 +print("当前日:", today.day) # 5 +``` + +### 使用Time对象表示时间 + +```py +from datetime import time +# time(hour = 0, minute = 0, second = 0) +a = time() +print("a =", a) +# time(hour, minute 和 second) +b = time(10, 30, 50) +print("b =", b) +# time(hour, minute 和 second) +c = time(hour=10, minute=30, second=50) +print("c =", c) +# time(hour, minute, second, microsecond) +d = time(10, 30, 50, 200555) +print("d =", d) +``` + +输出: +a = 00:00:00 +b = 10:30:50 +c = 10:30:50 +d = 10:30:50.200555 + +### 计算两个时间点之间的差异 + +```py +today = date(year=2019, month=12, day=5) +new_year = date(year=2020, month=1, day=1) +time_left_for_newyear = new_year - today +# 距离新年的时间: 27 days, 0:00:00 +print('距离新年的时间: ', time_left_for_newyear) + +t1 = datetime(year = 2019, month = 12, day = 5, hour = 0, minute = 59, second = 0) +t2 = datetime(year = 2020, month = 1, day = 1, hour = 0, minute = 0, second = 0) +diff = t2 - t1 +print('距离新年的时间:', diff) # 距离新年的时间: 26 days, 23: 01: 00 +``` + +### 使用 *timedelta* 计算两个时间点之间的差异 + +```py +from datetime import timedelta +t1 = timedelta(weeks=12, days=10, hours=4, seconds=20) +t2 = timedelta(days=7, hours=5, minutes=3, seconds=30) +t3 = t1 - t2 +print("t3 =", t3) +``` + +```sh +date_string = 5 December, 2019 +date_object = 2019-12-05 00:00:00 +t3 = 86 days, 22:56:50 +``` + +🌕 你太了不起了。你在通往卓越的道路上已经前进了16步。现在做一些练习锻炼你的大脑和肌肉。 + +## 💻 练习 - 第16天 + +1. 从datetime模块获取当前的日、月、年、小时、分钟和时间戳 +2. 使用此格式格式化当前日期:"%m/%d/%Y, %H:%M:%S" +3. 今天是2019年12月5日。将此时间字符串转换为时间。 +4. 计算现在和新年之间的时间差。 +5. 计算1970年1月1日和现在之间的时间差。 +6. 思考,你可以将datetime模块用于什么?例如: + - 时间序列分析 + - 获取应用程序中任何活动的时间戳 + - 在博客上添加帖子 + +🎉 恭喜!🎉 + +[<< 第15天](../15_Day_Python_type_errors/15_python_type_errors_cn.md) | [第17天 >>](../17_Day_Exception_handling/17_exception_handling_cn.md) \ No newline at end of file diff --git a/Chinese/17_exception_handling_cn.md b/Chinese/17_exception_handling_cn.md new file mode 100644 index 000000000..9fab14e9f --- /dev/null +++ b/Chinese/17_exception_handling_cn.md @@ -0,0 +1,285 @@ +# 30天Python编程挑战:第17天 - 异常处理 + +- [第17天](#-第17天) + - [异常处理](#异常处理) + - [Python中的打包和解包参数](#python中的打包和解包参数) + - [解包](#解包) + - [解包列表](#解包列表) + - [解包字典](#解包字典) + - [打包](#打包) + - [打包列表](#打包列表) + - [打包字典](#打包字典) + - [Python中的展开](#python中的展开) + - [枚举](#枚举) + - [Zip](#zip) + - [练习:第17天](#练习第17天) + +# 📘 第17天 + +## 异常处理 + +Python使用 _try_ 和 _except_ 优雅地处理错误。优雅的退出(或优雅的错误处理)是一种简单的编程习惯 - 程序检测到严重的错误条件并"优雅地退出",即以受控的方式处理结果。通常,程序会在优雅退出时向终端或日志打印描述性错误消息,这使我们的应用程序更加健壮。异常的原因通常是程序本身之外的因素,例如错误的输入、错误的文件名、找不到文件、IO设备故障等。优雅的错误处理可以防止我们的应用程序崩溃。 + +我们在前一部分已经介绍了不同类型的Python _错误_。如果我们在程序中使用 _try_ 和 _except_,那么这些块中就不会引发错误。 + +![Try and Except](../images/try_except.png) + +```py +try: + # 如果一切正常,执行这个块中的代码 +except: + # 如果出错,执行这个块中的代码 +``` + +**示例:** + +```py +try: + print(10 + '5') +except: + print('出现了一些错误') +``` + +在上面的例子中,第二个操作数是一个字符串。我们可以将其更改为float或int,使其能够与数字相加。但如果不做任何更改,第二个块 _except_ 将被执行。 + +**示例:** + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - year_born + print(f'你是{name}. 你的年龄是{age}.') +except: + print('出现了一些错误') +``` + +```sh +出现了一些错误 +``` + +在上面的例子中,异常块将运行,但我们不知道具体的问题是什么。为了分析问题,我们可以使用不同的错误类型配合except。 + +在下面的例子中,它将处理错误,并且告诉我们引发了什么类型的错误。 + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - year_born + print(f'你是{name}. 你的年龄是{age}.') +except TypeError: + print('发生了类型错误') +except ValueError: + print('发生了值错误') +except ZeroDivisionError: + print('发生了除零错误') +``` + +```sh +输入你的名字:Asabeneh +你出生的年份:1920 +发生了类型错误 +``` + +在上述代码中,输出将是 _TypeError_。 +现在,让我们添加一个额外的块: + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - int(year_born) + print(f'你是{name}. 你的年龄是{age}.') +except TypeError: + print('发生了类型错误') +except ValueError: + print('发生了值错误') +except ZeroDivisionError: + print('发生了除零错误') +else: + print('我通常与try块一起运行') +finally: + print('我总是运行。') +``` + +```sh +输入你的名字:Asabeneh +你出生的年份:1920 +你是Asabeneh. 你的年龄是99. +我通常与try块一起运行 +我总是运行。 +``` + +也可以将上述代码简化如下: + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - int(year_born) + print(f'你是{name}. 你的年龄是{age}.') +except Exception as e: + print(e) +``` + +## Python中的打包和解包参数 + +我们使用两个操作符: + +- \* 用于元组 +- \*\* 用于字典 + +让我们看一个例子。假设函数只接受参数,但我们有一个列表。我们可以解包列表并将其转换为参数。 + +### 解包 + +#### 解包列表 + +```py +def sum_of_five_nums(a, b, c, d, e): + return a + b + c + d + e + +lst = [1, 2, 3, 4, 5] +print(sum_of_five_nums(lst)) # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e' +``` + +当我们运行这段代码时,会引发错误,因为这个函数接受数字(而不是列表)作为参数。让我们解包/解构这个列表。 + +```py +def sum_of_five_nums(a, b, c, d, e): + return a + b + c + d + e + +lst = [1, 2, 3, 4, 5] +print(sum_of_five_nums(*lst)) # 15 +``` + +我们也可以在内置的range函数中使用解包,该函数需要一个起始和结束参数。 + +```py +numbers = range(2, 7) # 正常调用,使用单独的参数 +print(list(numbers)) # [2, 3, 4, 5, 6] +args = [2, 7] +numbers = range(*args) # 使用从列表解包的参数调用 +print(numbers) # [2, 3, 4, 5,6] +``` + +列表或元组也可以这样解包: + +```py +countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] +fin, sw, nor, *rest = countries +print(fin, sw, nor, rest) # Finland Sweden Norway ['Denmark', 'Iceland'] +numbers = [1, 2, 3, 4, 5, 6, 7] +one, *middle, last = numbers +print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7 +``` + +#### 解包字典 + +```py +def unpacking_person_info(name, country, city, age): + return f'{name}住在{country}的{city}。他{age}岁。' +dct = {'name':'Asabeneh', 'country':'Finland', 'city':'Helsinki', 'age':250} +print(unpacking_person_info(**dct)) # Asabeneh住在Finland的Helsinki。他250岁。 +``` + +### 打包 + +有时候我们不知道需要向Python函数传递多少个参数。我们可以使用打包方法让我们的函数接受无限数量或任意数量的参数。 + +### 打包列表 + +```py +def sum_all(*args): + s = 0 + for i in args: + s += i + return s +print(sum_all(1, 2, 3)) # 6 +print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28 +``` + +#### 打包字典 + +```py +def packing_person_info(**kwargs): + # 检查kwargs的类型,它是一个字典类型 + # print(type(kwargs)) + # 打印字典项 + for key in kwargs: + print(f"{key} = {kwargs[key]}") + return kwargs + +print(packing_person_info(name="Asabeneh", + country="Finland", city="Helsinki", age=250)) +``` + +```sh +name = Asabeneh +country = Finland +city = Helsinki +age = 250 +{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +``` + +## Python中的展开 + +与JavaScript类似,Python中也可以进行展开操作。让我们通过下面的例子来看看: + +```py +lst_one = [1, 2, 3] +lst_two = [4, 5, 6, 7] +lst = [0, *lst_one, *lst_two] +print(lst) # [0, 1, 2, 3, 4, 5, 6, 7] +``` + +## 枚举 + +如果我们对列表的索引感兴趣,我们使用enumerate内置函数。 + +```py +for index, item in enumerate([20, 30, 40]): + print(index, item) +``` + +```py +for index, i in enumerate(countries): + print('hi') + if i == 'Finland': + print('国家 {i} 位于索引 {index}') +``` + +```sh +0 20 +1 30 +2 40 +``` + +## Zip + +有时,我们可能需要将列表组合起来。看看以下示例: + +```py +fruits = ['banana', 'orange', 'mango', 'lemon', 'lime'] +vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] +fruits_and_veges = [] +for f, v in zip(fruits, vegetables): + fruits_and_veges.append({'fruit':f, 'veg':v}) + +print(fruits_and_veges) +``` + +```sh +[{'fruit': 'banana', 'veg': 'Tomato'}, {'fruit': 'orange', 'veg': 'Potato'}, {'fruit': 'mango', 'veg': 'Cabbage'}, {'fruit': 'lemon', 'veg': 'Onion'}, {'fruit': 'lime', 'veg': 'Carrot'}] +``` + +## 练习:第17天 + +1. 为名为 _countries_data.py_ 的文件中的数据创建一个名为 _countries.py_ 的函数。 + - 创建一个函数,找出十大使用的语言 + - 创建一个函数,找出十大人口最多的国家 + +🎉 恭喜!🎉 + +[<< 第16天](../16_Day_Python_date_time/16_python_datetime_cn.md) | [第18天 >>](../18_Day_Regular_expressions/18_regular_expressions_cn.md) \ No newline at end of file diff --git a/Chinese/18_regular_expressions_cn.md b/Chinese/18_regular_expressions_cn.md new file mode 100644 index 000000000..c9987be10 --- /dev/null +++ b/Chinese/18_regular_expressions_cn.md @@ -0,0 +1,417 @@ +# 30天Python编程挑战:第18天 - 正则表达式 + +- [第18天](#-第18天) + - [正则表达式](#正则表达式) + - [*re* 模块](#re-模块) + - [*re* 模块中的方法](#re-模块中的方法) + - [匹配](#匹配) + - [搜索](#搜索) + - [使用 *findall* 搜索所有匹配项](#使用-findall-搜索所有匹配项) + - [替换子字符串](#替换子字符串) + - [使用RegEx拆分文本](#使用regex拆分文本) + - [编写RegEx模式](#编写regex模式) + - [方括号](#方括号) + - [RegEx中的转义字符(\\)](#regex中的转义字符) + - [一次或多次(+)](#一次或多次) + - [句点(.)](#句点) + - [零次或多次(*)](#零次或多次) + - [零次或一次(?)](#零次或一次) + - [RegEx中的量词](#regex中的量词) + - [脱字符(^)](#脱字符) + - [💻 练习:第18天](#-练习第18天) + - [练习:级别1](#练习级别1) + - [练习:级别2](#练习级别2) + - [练习:级别3](#练习级别3) + +# 📘 第18天 + +## 正则表达式 + +正则表达式(RegEx)是一种特殊的文本字符串,有助于在数据中查找模式。RegEx可用于检查不同数据类型中是否存在某种模式。要在Python中使用RegEx,首先我们应该导入RegEx模块,该模块被称为*re*。 + +### *re* 模块 + +导入模块后,我们可以使用它来检测或查找模式。 + +```py +import re +``` + +### *re* 模块中的方法 + +要查找模式,我们使用不同的*re*字符集,这些字符集允许在字符串中搜索匹配项。 + +- *re.match()*:只在字符串的第一行开头搜索,如果找到则返回匹配的对象,否则返回None。 +- *re.search*:如果字符串中的任何地方(包括多行字符串)有匹配项,则返回匹配对象。 +- *re.findall*:返回包含所有匹配项的列表。 +- *re.split*:接受一个字符串,在匹配点处分割,返回一个列表。 +- *re.sub*:替换字符串中的一个或多个匹配项。 + +#### 匹配 + +```py +# 语法 +re.match(substring, string, re.I) +# substring是一个字符串或模式,string是我们查找模式的文本,re.I是忽略大小写 +``` + +```py +import re + +txt = 'I love to teach python and javaScript' +# 它返回一个带有span和match的对象 +match = re.match('I love to teach', txt, re.I) +print(match) # +# 我们可以使用span获取匹配的起始和结束位置,作为元组 +span = match.span() +print(span) # (0, 15) +# 让我们从span中找到起始和结束位置 +start, end = span +print(start, end) # 0, 15 +substring = txt[start:end] +print(substring) # I love to teach +``` + +从上面的例子可以看出,我们正在寻找的模式(或我们正在寻找的子字符串)是*I love to teach*。match函数**只有**在文本以该模式开头时才会返回一个对象。 + +```py +import re + +txt = 'I love to teach python and javaScript' +match = re.match('I like to teach', txt, re.I) +print(match) # None +``` + +该字符串不以*I like to teach*开头,因此没有匹配,match方法返回None。 + +#### 搜索 + +```py +# 语法 +re.match(substring, string, re.I) +# substring是一个模式,string是我们查找模式的文本,re.I是忽略大小写标志 +``` + +```py +import re + +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +# 它返回一个带有span和match的对象 +match = re.search('first', txt, re.I) +print(match) # +# 我们可以使用span获取匹配的起始和结束位置,作为元组 +span = match.span() +print(span) # (100, 105) +# 让我们从span中找到起始和结束位置 +start, end = span +print(start, end) # 100 105 +substring = txt[start:end] +print(substring) # first +``` + +如你所见,search比match好得多,因为它可以在整个文本中查找模式。Search返回找到的第一个匹配项的匹配对象,否则返回*None*。更好的*re*函数是*findall*。此函数检查整个字符串中的模式,并将所有匹配项作为列表返回。 + +#### 使用 *findall* 搜索所有匹配项 + +*findall()* 将所有匹配项作为列表返回 + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +# 它返回一个列表 +matches = re.findall('language', txt, re.I) +print(matches) # ['language', 'language'] +``` + +如你所见,单词*language*在字符串中被找到了两次。让我们再练习一些。 +现在我们将在字符串中查找Python和python这两个单词: + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +# 它返回一个列表 +matches = re.findall('python', txt, re.I) +print(matches) # ['Python', 'python'] + +``` + +由于我们使用*re.I*,所以包含了大小写字母。如果我们没有re.I标志,那么我们将不得不以不同的方式编写我们的模式。让我们来看看: + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +matches = re.findall('Python|python', txt) +print(matches) # ['Python', 'python'] + +# +matches = re.findall('[Pp]ython', txt) +print(matches) # ['Python', 'python'] + +``` + +#### 替换子字符串 + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +match_replaced = re.sub('Python|python', 'JavaScript', txt, re.I) +print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created. +# 或者 +match_replaced = re.sub('[Pp]ython', 'JavaScript', txt, re.I) +print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created. +``` + +让我们再添加一个例子。除非我们删除%符号,否则以下字符串真的很难阅读。用空字符串替换%将清理文本。 + +```py + +txt = '''%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing. +T%he%re i%s n%o%th%ing as r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing p%e%o%ple. +I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs. +D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher?''' + +matches = re.sub('%', '', txt) +print(matches) +``` + +```sh +I am teacher and I love teaching. +There is nothing as rewarding as educating and empowering people. +I found teaching more interesting than any other jobs. Does this motivate you to be a teacher? +``` + +## 使用RegEx拆分文本 + +```py +txt = '''I am teacher and I love teaching. +There is nothing as rewarding as educating and empowering people. +I found teaching more interesting than any other jobs. +Does this motivate you to be a teacher?''' +print(re.split('\n', txt)) # 使用\n分割 - 行尾符号 +``` + +```sh +['I am teacher and I love teaching.', 'There is nothing as rewarding as educating and empowering people.', 'I found teaching more interesting than any other jobs.', 'Does this motivate you to be a teacher?'] +``` + +## 编写RegEx模式 + +要声明字符串变量,我们使用单引号或双引号。要声明RegEx变量,使用*r''*。 +以下模式仅识别小写的apple,要使其不区分大小写,我们应该重写模式或添加标志。 + +```py +import re + +regex_pattern = r'apple' +txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. ' +matches = re.findall(regex_pattern, txt) +print(matches) # ['apple'] + +# 要使其不区分大小写,添加标志' +matches = re.findall(regex_pattern, txt, re.I) +print(matches) # ['Apple', 'apple'] +# 或者我们可以使用一组字符方法 +regex_pattern = r'[Aa]pple' # 这意味着第一个字母可以是Apple或apple +matches = re.findall(regex_pattern, txt) +print(matches) # ['Apple', 'apple'] + +``` + +* []: 一组字符 + - [a-c] 表示,a或b或c + - [a-z] 表示,从a到z的任何字母 + - [A-Z] 表示,从A到Z的任何字符 + - [0-3] 表示,0或1或2或3 + - [0-9] 表示从0到9的任何数字 + - [A-Za-z0-9] 任何单个字符,即a到z,A到Z或0到9 + +### 方括号 + +让我们使用方括号练习更多的模式。记得,我们使用*re.I*作为标志,使搜索不区分大小写。 + +```py +regex_pattern = r'[Aa]pple|[Bb]anana' # 这意味着Apple或apple或Banana或banana +txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.' +matches = re.findall(regex_pattern, txt) +print(matches) # ['Apple', 'banana', 'apple', 'banana'] + +``` + +使用方括号和管道。 +```py +regex_pattern = r'[a-zA-Z0-9]' # 这个方括号表示 a 到 z, A 到 Z, 0 到 9 +txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.' +matches = re.findall(regex_pattern, txt) +print(matches) # ['A', 'p', 'p', 'l', 'e', 'a', 'n', 'd', 'b', 'a', 'n', 'a', 'n', 'a', 'a', 'r', 'e',...] + +regex_pattern = r'\d' # d 是一个特殊字符,表示数字 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2', '0', '1', '9', '8', '2', '0', '2', '1'] + +regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +### RegEx中的转义字符(\\) + +```py +regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +要查找 \ 本身,我们应该使用双倍反斜杠: +```py +regex_pattern = r'\\d' # 这意味着寻找 \d +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # [] +``` + +当我们在字符串中没有任何与 \d 匹配的内容时,找不到任何匹配项。 + +### 一次或多次(+) + +```py +regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +### 句点(.) + +```py +regex_pattern = r'[a].' # 这个方括号表示 a 和 . 表示任何字符,除了新行 +txt = '''Apple and banana are fruits''' +matches = re.findall(regex_pattern, txt) +print(matches) # ['an', 'an', 'an', 'a ', 'ar'] + +regex_pattern = r'[a].+' # . 任何字符,+ 任何字符一次或多次 +matches = re.findall(regex_pattern, txt) +print(matches) # ['and banana are fruits'] +``` + +### 零次或多次(*) + +零次或多次。这个例子不太明显,所以请慢慢看。 + +```py +regex_pattern = r'[a].*' # . 任何字符,* 任何字符零次或多次 +txt = '''Apple and banana are fruits''' +matches = re.findall(regex_pattern, txt) +print(matches) # ['and banana are fruits'] +``` + +### 零次或一次(?) + +零次或一次。它可以存在,也可以不存在。 + +```py +txt = '''I am not sure if there is a convention how to write the word e-mail. +Some people write it as email others may write it as Email or E-mail.''' +regex_pattern = r'[Ee]-?mail' # ? 表示零次或一次 +matches = re.findall(regex_pattern, txt) +print(matches) # ['e-mail', 'email', 'Email', 'E-mail'] +``` + +### RegEx中的量词 + +使用大括号,我们可以指定模式的长度 +```py +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'\d{4}' # 正好有四位数的数字 +matches = re.findall(regex_pattern, txt) +print(matches) # ['2019', '2021'] + +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'\d{1,4}' # 1到4位数的数字 +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +### 脱字符(^) + +- 以什么开始 + +```py +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'^This' # ^ 表示以 This 开始 +matches = re.findall(regex_pattern, txt) +print(matches) # ['This'] +``` + +- 否定 + +```py +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'[^A-Za-z ]+' # ^ 在方括号内表示否定,不是A-Z,不是a-z,不是空格 +matches = re.findall(regex_pattern, txt) +print(matches) # ['6,', '2019', '8,', '2021'] +``` + +## 💻 练习:第18天 + +### 练习:级别1 + +1. 什么是正则表达式? +2. 正则表达式的变量是什么? +3. 重新创建字符串模式,这些模式可以: + a) 查找对带有*才能*的字符串的引用,在一本书中 + b) 找出日期格式为 _DD-MM-YYYY_,例如12-01-2021 + c) 找出文本中动词的时态为ing + +### 练习:级别2 + +1. 编写一个模式,用于识别表示有效Python变量名的字符串 +2. 从以下文本中清除HTML标签。 +```python +text = ''' +HTML +Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript. + +Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document. + +HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects such as interactive forms may be embedded into the rendered page. HTML provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such as and directly introduce content into the page. Other tags such as

surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page. + +HTML can embed programs written in a scripting language such as JavaScript, which affects the behavior and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web Consortium (W3C), former maintainer of the HTML and current maintainer of the CSS standards, has encouraged the use of CSS over explicit presentational HTML since 1997. +''' +``` + +### 练习:级别3 + +1. 清理以下文本。在清理过程后,计算最常见的三个单词是什么。 + +```python + + paragraph = '''I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.''' + +``` + +2. 下面的文本包含了几个电子邮件地址。编写一个可以查找或提取电子邮件地址的模式。 + +```py +email_address = ''' +asabeneh@gmail.com +alex@yahoo.com +kofi@yahoo.com +doe@arc.gov +asabeneh.com +asabeneh@gmail +alex@yahoo +''' +``` + +🎉 恭喜!🎉 + +[<< 第17天](../17_Day_Exception_handling/17_exception_handling_cn.md) | [第19天 >>](../19_Day_File_handling/19_file_handling_cn.md) \ No newline at end of file diff --git a/Chinese/19_file_handling_cn.md b/Chinese/19_file_handling_cn.md new file mode 100644 index 000000000..3c8e147e6 --- /dev/null +++ b/Chinese/19_file_handling_cn.md @@ -0,0 +1,549 @@ +# 30天Python编程挑战:第19天 - 文件处理 + +- [第19天](#-第19天) + - [文件处理](#文件处理) + - [打开文件进行读取](#打开文件进行读取) + - [打开文件进行写入和更新](#打开文件进行写入和更新) + - [删除文件](#删除文件) + - [文件类型](#文件类型) + - [带有txt扩展名的文件](#带有txt扩展名的文件) + - [带有json扩展名的文件](#带有json扩展名的文件) + - [将JSON转换为字典](#将json转换为字典) + - [将字典转换为JSON](#将字典转换为json) + - [保存为JSON文件](#保存为json文件) + - [带有csv扩展名的文件](#带有csv扩展名的文件) + - [带有xlsx扩展名的文件](#带有xlsx扩展名的文件) + - [带有xml扩展名的文件](#带有xml扩展名的文件) + - [💻 练习:第19天](#-练习第19天) + - [练习:级别1](#练习级别1) + - [练习:级别2](#练习级别2) + - [练习:级别3](#练习级别3) + +# 📘 第19天 + +## 文件处理 + +到目前为止,我们已经了解了不同的Python数据类型。我们通常在不同的文件格式中存储数据。除了处理文件外,在本节中我们还将看到不同的文件格式(.txt、.json、.xml、.csv、.tsv、.excel)。首先,让我们熟悉使用常见文件格式(.txt)处理文件。 + +文件处理是编程的重要部分,它允许我们创建、读取、更新和删除文件。在Python中,处理数据我们使用内置函数 _open()_。 + +```py +# 语法 +open('filename', mode) # mode(r, a, w, x, t, b) 可以是读取、写入、更新 +``` + +- "r" - 读取 - 默认值。打开文件进行读取,如果文件不存在则返回错误 +- "a" - 追加 - 打开文件进行追加,如果文件不存在则创建文件 +- "w" - 写入 - 打开文件进行写入,如果文件不存在则创建文件 +- "x" - 创建 - 创建指定的文件,如果文件已存在则返回错误 +- "t" - 文本 - 默认值。文本模式 +- "b" - 二进制 - 二进制模式(例如图像) + +### 打开文件进行读取 + +_open_ 的默认模式是读取,因此我们不必指定'r'或'rt'。我已经在files目录中创建并保存了一个名为reading_file_example.txt的文件。让我们看看它是如何完成的: + +```py +f = open('./files/reading_file_example.txt') +print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'> +``` + +如上例所示,我打印了打开的文件,它提供了一些关于文件的信息。已打开的文件有不同的读取方法:_read()_、_readline_、_readlines_。打开的文件必须用 _close()_ 方法关闭。 + +- _read()_:将整个文本作为字符串读取。如果我们想限制想要读取的字符数,可以通过向 *read(number)* 方法传递int值来限制。 + +```py +f = open('./files/reading_file_example.txt') +txt = f.read() +print(type(txt)) +print(txt) +f.close() +``` + +```sh +# 输出 + +This is an example to show how to open a file and read. +This is the second line of the text. +``` + +与其打印所有文本,不如打印文本文件的前10个字符。 + +```py +f = open('./files/reading_file_example.txt') +txt = f.read(10) +print(type(txt)) +print(txt) +f.close() +``` + +```sh +# 输出 + +This is an +``` + +- _readline()_:只读取第一行 + +```py +f = open('./files/reading_file_example.txt') +line = f.readline() +print(type(line)) +print(line) +f.close() +``` + +```sh +# 输出 + +This is an example to show how to open a file and read. +``` + +- _readlines()_:逐行读取所有文本,并返回一个行列表 + +```py +f = open('./files/reading_file_example.txt') +lines = f.readlines() +print(type(lines)) +print(lines) +f.close() +``` + +```sh +# 输出 + +['This is an example to show how to open a file and read.\n', 'This is the second line of the text.'] +``` + +获取所有行作为列表的另一种方法是使用 _splitlines()_: + +```py +f = open('./files/reading_file_example.txt') +lines = f.read().splitlines() +print(type(lines)) +print(lines) +f.close() +``` + +```sh +# 输出 + +['This is an example to show how to open a file and read.', 'This is the second line of the text.'] +``` + +在打开文件后,我们应该关闭它。我们很容易忘记关闭它们。有一种使用 _with_ 打开文件的新方法——它会自动关闭文件。让我们用 _with_ 方法重写前面的例子: + +```py +with open('./files/reading_file_example.txt') as f: + lines = f.read().splitlines() + print(type(lines)) + print(lines) +``` + +```sh +# 输出 + +['This is an example to show how to open a file and read.', 'This is the second line of the text.'] +``` + +### 打开文件进行写入和更新 + +要写入现有文件,我们必须向 _open()_ 函数添加模式作为参数: + +- "a" - 追加 - 将在文件末尾追加,如果文件不存在则创建一个新文件。 +- "w" - 写入 - 将覆盖任何现有内容,如果文件不存在则创建。 + +让我们在我们一直在读取的文件中追加一些文本: + +```py +with open('./files/reading_file_example.txt','a') as f: + f.write('此文本必须附加在末尾') +``` + +如果文件不存在,以下方法将创建一个新文件: + +```py +with open('./files/writing_file_example.txt','w') as f: + f.write('这段文本将被写入新创建的文件中') +``` + +### 删除文件 + +我们在前面的部分中已经看到,如何使用 _os_ 模块创建和删除目录。现在,如果我们想删除一个文件,我们也使用 _os_ 模块。 + +```py +import os +os.remove('./files/example.txt') + +``` + +如果文件不存在,remove方法将引发错误,因此最好使用条件语句: + +```py +import os +if os.path.exists('./files/example.txt'): + os.remove('./files/example.txt') +else: + print('文件不存在') +``` + +## 文件类型 + +### 带有txt扩展名的文件 + +带有 _txt_ 扩展名的文件是一种非常常见的数据形式,我们已经在前面的部分中介绍了它。让我们转到JSON文件。 + +### 带有json扩展名的文件 + +JSON代表JavaScript对象表示法。实际上,它是一个字符串化的JavaScript对象或Python字典。 + +_示例:_ + +```py +# 字典 +person_dct= { + "name":"Asabeneh", + "country":"Finland", + "city":"Helsinki", + "skills":["JavaScrip", "React","Python"] +} +# JSON: 字典的字符串形式 +person_json = "{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'React', 'Python']}" + +# 我们使用三个引号并使其多行以使其更具可读性 +person_json = '''{ + "name":"Asabeneh", + "country":"Finland", + "city":"Helsinki", + "skills":["JavaScrip", "React","Python"] +}''' +``` + +### 将JSON转换为字典 + +要将JSON更改为字典,首先我们导入json模块,然后使用 _loads_ 方法。 + +```py +import json +# JSON +person_json = '''{ + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": ["JavaScrip", "React", "Python"] +}''' +# 将JSON字符串更改为字典 +person_dct = json.loads(person_json) +print(type(person_dct)) +print(person_dct) +print(person_dct['name']) +``` + +```sh +# 输出 + +{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'React', 'Python']} +Asabeneh +``` + +### 将字典转换为JSON + +要将字典更改为JSON,我们使用 _dumps_ 方法。 + +```py +import json +# python字典 +person = { + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": ["JavaScrip", "React", "Python"] +} +# 将字典转换为JSON字符串 +person_json = json.dumps(person, indent=4) # indent可以是2, 4, 8. 它漂亮地打印了。 +print(type(person_json)) +print(person_json) +``` + +```sh +# 输出 + +{ + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": [ + "JavaScrip", + "React", + "Python" + ] +} +``` + +### 保存为JSON文件 + +我们也可以将我们的数据保存为JSON文件。让我们使用前面的示例保存: + +```py +import json +# python字典 +person = { + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": ["JavaScrip", "React", "Python"] +} +with open('./files/json_example.json', 'w', encoding='utf-8') as f: + json.dump(person, f, ensure_ascii=False, indent=4) +``` + +在上面的代码中,我们使用了编码和确保_ascii参数。这些参数是为了保存非ASCII字符,如果我们想保存非英语字符。下面是一个包含非ASCII字符的示例: + +```py +import json +# python字典 +person = { + "name": "张三", + "country": "中国", + "city": "北京", + "skills": ["JavaScript", "React", "Python"] +} +with open('./files/json_example.json', 'w', encoding='utf-8') as f: + json.dump(person, f, ensure_ascii=False, indent=4) +``` + +现在,让我们读取我们刚刚创建的json文件: + +```py +import json +with open('./files/json_example.json', 'r', encoding='utf-8') as f: + person = json.load(f) + print(person) +``` + +```sh +# 输出 +{'name': '张三', 'country': '中国', 'city': '北京', 'skills': ['JavaScript', 'React', 'Python']} +``` + +### 带有csv扩展名的文件 + +CSV代表逗号分隔值。CSV是一种简单的文件格式,用于存储表格数据,如电子表格或数据库。CSV是数据科学中非常常见的数据格式。 + +**示例:** + +```csv +"name","country","city","skills" +"Asabeneh","Finland","Helsinki","JavaScript" +``` + +**示例:** + +```py +import csv +with open('./files/csv_example.csv') as f: + csv_reader = csv.reader(f, delimiter=',') # w+ 创建文件(如果不存在) + line_count = 0 + for row in csv_reader: + if line_count == 0: + print(f'列名为: {", ".join(row)}') + line_count += 1 + else: + print(f'{row[0]}来自{row[1]}的{row[2]}。 他了解{row[3]}') + line_count += 1 + print(f'已处理{line_count}行。') +``` + +```sh +# 输出: +列名为: name, country, city, skills +Asabeneh来自Finland的Helsinki。 他了解JavaScript +已处理2行。 +``` + +我们还可以使用相同的方法将数据写入csv文件 + +```py +import csv +with open('./files/csv_example.csv', 'w', encoding='UTF8', newline='') as f: + writer = csv.writer(f) + # 写入列名 + writer.writerow(['name', 'country', 'city', 'skills']) + # 写入数据 + writer.writerow(['Asabeneh', 'Finland', 'Helsinki', 'JavaScript']) +``` + +### 带有xlsx扩展名的文件 + +要读取Excel文件,我们需要安装xlrd包。我们将使用它来读取Excel文件。 + +```py +import xlrd +excel_book = xlrd.open_workbook('sample.xls') +print(excel_book.nsheets) +print(excel_book.sheet_names) +``` + +### 带有xml扩展名的文件 + +XML是一种元标记语言,非常类似于HTML。在XML中,我们可以使用自己的标签,从而使其更加灵活。我们使用XML主要是为了结构化数据。在Python中有少量的XML库。在本部分中,我们将使用xml.etree.ElementTree模块。 + +**示例:XML** + +```xml + + + Asabeneh + Finland + Helsinki + + JavaScript + React + Python + + +``` + +我们将使用xml.etree.ElementTree模块来解析XML文件。 + +```py +import xml.etree.ElementTree as ET +tree = ET.parse('./files/xml_example.xml') +root = tree.getroot() +print('Root tag:', root.tag) +print('Attribute:', root.attrib) +for child in root: + print('字段: ', child.tag) +``` + +```sh +# 输出 +Root tag: person +Attribute: {'gender': 'female'} +字段: name +字段: country +字段: city +字段: skills +``` + +```py +import xml.etree.ElementTree as ET +tree = ET.parse('./files/xml_example.xml') +root = tree.getroot() +print('Root tag:', root.tag) +print('Attribute:', root.attrib) +for child in root: + print('字段: ', child.tag) +``` + +```sh +# 输出 +Root tag: person +Attribute: {'gender': 'female'} +字段: name +字段: country +字段: city +字段: skills +``` + +让我们获取更多细节: + +```py +import xml.etree.ElementTree as ET +tree = ET.parse('./files/xml_example.xml') +root = tree.getroot() +print('Root tag:', root.tag) +print('Attribute:', root.attrib) +for child in root: + print('field: ', child.tag) + if child.tag != 'skills': + print(child.text) + else: + for skill in child: + print(skill.text) +``` + +```sh +# 输出 +Root tag: person +Attribute: {'gender': 'female'} +field: name +Asabeneh +field: country +Finland +field: city +Helsinki +field: skills +JavaScript +React +Python +``` + +## 💻 练习:第19天 + +### 练习:级别1 + +1. 编写一个函数,该函数需要一个参数(文件名)并统计文件中单词的数量 +2. 阅读obama_speech.txt文件并计算单词数 +3. 阅读michelle_obama_speech.txt文件并计算单词数 +4. 阅读donald_speech.txt文件并计算单词数 +5. 阅读melina_trump_speech.txt文件并计算单词数 + +### 练习:级别2 + +1. 从编程语言中提取所有Python目录文件: + a) 处理30DaysOfPython文件夹,提取出所有python文件,并将它们的名称存储在files_list.txt文件中 + b) 创建一个名为find_python.py的脚本,可以通过命令行运行它 + c) 添加一个名为--version的标志来处理命令行参数 + +### 练习:级别3 + +1. 使用以下数据集创建一个JSON文件: + ```py + python_libraries = [ + { + "库名称": "Django", + "创建者": "Adrian Holovaty", + "首次发布年份": 2005, + "版本": "4.0.2", + "用途": "Web开发", + "描述": "Django让您可以快速构建更好的Web应用程序。" + }, + { + "库名称": "Flask", + "创建者": "Armin Ronacher", + "首次发布年份": 2010, + "版本": "2.0.2", + "用途": "Web开发", + "描述": "Flask是一个轻量级的WSGI Web应用程序框架。" + }, + { + "库名称": "NumPy", + "创建者": "Travis Oliphant", + "首次发布年份": 2005, + "版本": "1.22.0", + "用途": "科学计算", + "描述": "NumPy是Python中用于科学计算的基础包。" + }, + { + "库名称": "Pandas", + "创建者": "Wes McKinney", + "首次发布年份": 2008, + "版本": "1.4.0", + "用途": "数据分析", + "描述": "pandas是一个用于数据分析和数据操作的开源库。" + }, + { + "库名称": "Matplotlib", + "创建者": "John D. Hunter", + "首次发布年份": 2003, + "版本": "3.5.1", + "用途": "数据可视化", + "描述": "Matplotlib是一个用于在Python中创建静态、动画和交互式可视化的库。" + } + ] + ``` + +🎉 恭喜!🎉 + +[<< 第18天](../18_Day_Regular_expressions/18_regular_expressions_cn.md) | [第20天 >>](../20_Day_Python_package_manager/20_python_package_manager_cn.md) \ No newline at end of file diff --git a/Chinese/20_python_package_manager_cn.md b/Chinese/20_python_package_manager_cn.md new file mode 100644 index 000000000..a2c9bafaf --- /dev/null +++ b/Chinese/20_python_package_manager_cn.md @@ -0,0 +1,352 @@ +# 30天Python编程挑战:第20天 - PIP + +- [第20天](#-第20天) + - [Python PIP - Python包管理器](#python-pip---python包管理器) + - [什么是PIP?](#什么是pip) + - [安装PIP](#安装pip) + - [使用pip安装包](#使用pip安装包) + - [卸载包](#卸载包) + - [包列表](#包列表) + - [显示包信息](#显示包信息) + - [PIP Freeze](#pip-freeze) + - [从URL读取数据](#从url读取数据) + - [创建包](#创建包) + - [关于包的更多信息](#关于包的更多信息) + - [练习:第20天](#练习第20天) + +# 📘 第20天 + +## Python PIP - Python包管理器 + +### 什么是PIP? + +PIP代表首选安装程序(Preferred installer program)。我们使用_pip_来安装不同的Python包。 +包是一个Python模块,可以包含一个或多个模块或其他包。我们可以安装到应用程序中的模块或模块集合就是一个包。 +在编程中,我们不必编写每个实用程序,而是安装包并将它们导入到我们的应用程序中。 + +### 安装PIP + +如果你还没有安装pip,让我们现在安装它。转到你的终端或命令提示符,复制并粘贴: + +```sh +asabeneh@Asabeneh:~$ pip install pip +``` + +通过以下命令检查pip是否已安装: + +```sh +pip --version +``` + +```py +asabeneh@Asabeneh:~$ pip --version +pip 21.1.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.9.6) +``` + +如你所见,我正在使用pip 21.1.3版本,如果你看到的数字比这个稍低或稍高,说明你已经安装了pip。 + +让我们了解一下Python社区中用于不同目的的一些包。请注意,有很多可用于不同应用程序的包。 + +### 使用pip安装包 + +让我们尝试安装_numpy_,即数值Python。它是机器学习和数据科学社区中最流行的包之一。 + +- NumPy是Python科学计算的基础包。它包含以下内容: + - 强大的N维数组对象 + - 复杂的(广播)函数 + - 用于集成C/C++和Fortran代码的工具 + - 有用的线性代数、傅里叶变换和随机数功能 + +```sh +asabeneh@Asabeneh:~$ pip install numpy +``` + +让我们开始使用numpy。打开你的Python交互式shell,输入python,然后按如下方式导入numpy: + +```py +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import numpy +>>> numpy.version.version +'1.20.1' +>>> lst = [1, 2, 3,4, 5] +>>> np_arr = numpy.array(lst) +>>> np_arr +array([1, 2, 3, 4, 5]) +>>> len(np_arr) +5 +>>> np_arr * 2 +array([ 2, 4, 6, 8, 10]) +>>> np_arr + 2 +array([3, 4, 5, 6, 7]) +>>> +``` + +Pandas是一个开源的、BSD许可的库,为Python编程语言提供高性能、易用的数据结构和数据分析工具。让我们安装numpy的"大兄弟"_pandas_: + +```sh +asabeneh@Asabeneh:~$ pip install pandas +``` + +```py +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import pandas +``` + +这一节不是关于numpy或pandas的,我们在这里尝试学习如何安装包以及如何导入它们。如果需要,我们将在其他章节讨论不同的包。 + +让我们导入一个Web浏览器模块,它可以帮助我们打开任何网站。我们不需要安装这个模块,它已经默认安装在Python 3中。例如,如果你想随时打开任意数量的网站,或者如果你想安排某些事情,可以使用这个_webbrowser_模块。 + +```py +import webbrowser # web浏览器模块用于打开网站 + +# 网址列表:Python +url_lists = [ + 'http://www.python.org', + 'https://www.linkedin.com/in/asabeneh/', + 'https://github.com/Asabeneh', + 'https://twitter.com/Asabeneh', +] + +# 在不同的标签页中打开上面的网站列表 +for url in url_lists: + webbrowser.open_new_tab(url) +``` + +### 卸载包 + +如果你不想保留已安装的包,可以使用以下命令删除它们。 + +```sh +pip uninstall packagename +``` + +### 包列表 + +要查看我们机器上已安装的包,我们可以使用pip后跟list。 + +```sh +pip list +``` + +### 显示包信息 + +要显示有关包的信息: + +```sh +pip show packagename +``` + +```sh +asabeneh@Asabeneh:~$ pip show pandas +Name: pandas +Version: 1.2.3 +Summary: Powerful data structures for data analysis, time series, and statistics +Home-page: http://pandas.pydata.org +Author: None +Author-email: None +License: BSD +Location: /usr/local/lib/python3.7/site-packages +Requires: python-dateutil, pytz, numpy +Required-by: +``` + +如果我们想要更多的详细信息,只需添加--verbose + +```sh +asabeneh@Asabeneh:~$ pip show --verbose pandas +Name: pandas +Version: 1.2.3 +Summary: Powerful data structures for data analysis, time series, and statistics +Home-page: http://pandas.pydata.org +Author: None +Author-email: None +License: BSD +Location: /usr/local/lib/python3.7/site-packages +Requires: numpy, pytz, python-dateutil +Required-by: +Metadata-Version: 2.1 +Installer: pip +Classifiers: + Development Status :: 5 - Production/Stable + Environment :: Console + Operating System :: OS Independent + Intended Audience :: Science/Research + Programming Language :: Python + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Cython + Topic :: Scientific/Engineering +Entry-points: + [pandas_plotting_backends] + matplotlib = pandas:plotting._matplotlib +``` + +### PIP Freeze + +生成已安装的Python包及其版本,输出适合在requirements文件中使用。requirements.txt文件是一个包含Python项目中所有已安装的Python包的文件。 + +```sh +asabeneh@Asabeneh:~$ pip freeze +docutils==0.11 +Jinja2==2.7.2 +MarkupSafe==0.19 +Pygments==1.6 +Sphinx==1.2.2 +``` + +pip freeze给我们列出了使用的、已安装的包及其版本。我们将它与requirements.txt文件一起用于部署。 + +### 从URL读取数据 + +到目前为止,你已经熟悉了如何读取或写入位于本地机器上的文件。有时,我们想要使用url从网站或API读取数据。 +API代表应用程序编程接口。它是一种在服务器之间交换结构化数据的方式,主要是json数据。要打开网络连接,我们需要一个名为_requests_的包——它允许打开网络连接并实现CRUD(创建、读取、更新和删除)操作。在本节中,我们将只涵盖CRUD的读取或获取部分。 + +让我们安装_requests_: + +```py +asabeneh@Asabeneh:~$ pip install requests +``` + +我们将在_requests_模块中看到_get_、_status_code_、_headers_、_text_和_json_方法: + - _get()_:打开网络并从url获取数据——它返回一个响应对象 + - _status_code_:在我们获取数据后,我们可以检查操作的状态(成功、错误等) + - _headers_:检查头部类型 + - _text_:从获取的响应对象中提取文本 + - _json_:提取json数据 +让我们从这个网站读取一个txt文件,https://www.w3.org/TR/PNG/iso_8859-1.txt。 + +```py +import requests # 导入请求模块 + +url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt' # 来自网站的文本 + +response = requests.get(url) # 打开网络并获取数据 +print(response) +print(response.status_code) # 状态码,成功时为200 +print(response.headers) # 获取响应的头部信息 +print(response.text) # 获取文本数据 +``` + +让我们读取一个API并得到一个json数据: + +```py +import requests +url = 'https://restcountries.eu/rest/v2/all' # 包含关于250多个国家的信息的国家API +response = requests.get(url) # 打开网络并获取数据 +print(response) # 响应对象 +print(response.status_code) # 状态码,成功时为200 +countries = response.json() +print(countries[:1]) # 我们只打印第一个国家信息,原始数据太大 +``` + +我们用一个国家API示例获取了json数据。我们可以导入json模块,并使用json.loads(response.text)方法将文本转换为json格式。然而,我们也可以直接使用response.json()方法。 + +Let us see another example similar to the above but with a different API, world_bank_ethiopia data: +让我们看另一个类似于上面的例子,但使用不同的API,世界银行埃塞俄比亚数据: + +```py +import requests +from pprint import pp # 导入pretty print,以美观地显示 + +url = 'http://api.worldbank.org/countries/et?format=json' # 埃塞俄比亚经济数据API +response = requests.get(url) # 打开网络并获取数据 +print(response) # 响应对象 +print(response.status_code) # 状态码,成功时为200 +# 让我们改变响应的JSON格式 +ethiopia_data = response.json() +pp(ethiopia_data) # 用pretty print打印数据 +``` + +### 创建包 + +我们可以创建自己的包,上传到Python包管理器仓库,并从那里下载它。让我们创建一个非常简单的包来演示。创建一个名为mypackage的目录,在该目录中创建一个名为__init__.py的空文件和以下文件: + +```py +# mypackage/arithmetics.py +def add_numbers(*args): + total = 0 + for num in args: + total += num + return total + +def subtract(a, b): + return (a - b) + +def multiple(a, b): + return a * b + +def division(a, b): + return a / b + +def remainder(a, b): + return a % b + +def power(a, b): + return a ** b +``` + +```py +# mypackage/greet.py +def greet_person(firstname, lastname): + return f'{firstname} {lastname}, welcome to 30DaysOfPython Challenge!' +``` + +__init__.py在python 3.3及更高版本中并非绝对必要,但对于兼容性,最好加上。 + +现在,让我们使用刚刚创建的包: + +```py +from mypackage import arithmetics +print(arithmetics.add_numbers(1, 2, 3, 5)) +print(arithmetics.subtract(5, 3)) +print(arithmetics.multiple(5, 3)) +print(arithmetics.division(5, 3)) +print(arithmetics.remainder(5, 3)) +print(arithmetics.power(5, 3)) + +from mypackage import greet +print(greet.greet_person('张', '三')) +``` + +### 关于包的更多信息 + +- Python有许多不同目的的内置包和模块,但有些不包含在内置包中,我们需要安装它们。 +- 有多种方法可以安装包,但建议使用pip。 + - 使用 pip:pip是Python、PyPI和virtualenv推荐的安装和管理Python包的工具。 +- 如何列出已安装的包: + - pip list:列出机器中安装的所有包。 +- 使用requirements.txt进行开发环境和生产环境: + - 要生成已安装包的列表:pip freeze来本地生成已安装包的列表,以便用于开发环境和生产环境需求。 +- 如何卸载包: + - 要卸载,请使用pip:pip uninstall packagename。 + - 另一种方法:pip uninstall -r requirements.txt卸载在requirements.txt中列出的所有包。 +- 使用virtualenv: + - virtualenv是一个工具,用于创建隔离的Python环境。它创建一个在自己的目录树中包含所有必要的可执行文件,以使用指定版本的Python运行Python项目所需的包。 + - 原始的virtualenv工具可以通过 + - pip install virtualenv + - 来安装。 + +## 练习:第20天 + +1. 阅读关于虚拟环境的更多信息,尝试创建虚拟环境并安装至少一个包 + +2. 使用一个国家API,获取所有国家信息,并找出前十个人口最多的国家 + +3. 从国家API数据中找出官方语言是英语(eng)的所有国家 + +4. 从国家API数据中获取数据,根据国家的面积找出前十个最大的国家 + +5. 从国家API数据中找出所有从新列出的国家,按他们的首都排序 + +🎉 恭喜!🎉 + +[<< 第19天](../19_Day_File_handling/19_file_handling_cn.md) | [第21天 >>](../21_Day_Classes_and_objects/21_classes_and_objects_cn.md) \ No newline at end of file diff --git a/Chinese/21_classes_and_objects_cn.md b/Chinese/21_classes_and_objects_cn.md new file mode 100644 index 000000000..8bc5d2ef6 --- /dev/null +++ b/Chinese/21_classes_and_objects_cn.md @@ -0,0 +1,419 @@ +# 30天Python编程挑战:第21天 - 类和对象 + +- [第21天](#-第21天) + - [类和对象](#类和对象) + - [创建类](#创建类) + - [创建对象](#创建对象) + - [类构造函数](#类构造函数) + - [对象方法](#对象方法) + - [对象默认方法](#对象默认方法) + - [修改类默认值的方法](#修改类默认值的方法) + - [继承](#继承) + - [覆盖父类方法](#覆盖父类方法) + - [💻 练习:第21天](#-练习第21天) + - [练习:级别1](#练习级别1) + - [练习:级别2](#练习级别2) + - [练习:级别3](#练习级别3) + +# 📘 第21天 + +## 类和对象 + +Python是一种面向对象的编程语言。在Python中,一切都是对象,都有其属性和方法。在程序中使用的数字、字符串、列表、字典、元组、集合等都是相应内置类的对象。我们创建类来创建对象。类就像一个对象构造器,或者说是创建对象的"蓝图"。我们实例化一个类来创建一个对象。类定义了对象的属性和行为,而对象则代表了类。 + +从这个挑战的开始,我们就一直在不知不觉地使用类和对象。Python程序中的每个元素都是某个类的对象。 +让我们检查一下Python中的一切是否都是类: + +```py +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> num = 10 +>>> type(num) + +>>> string = 'string' +>>> type(string) + +>>> boolean = True +>>> type(boolean) + +>>> lst = [] +>>> type(lst) + +>>> tpl = () +>>> type(tpl) + +>>> set1 = set() +>>> type(set1) + +>>> dct = {} +>>> type(dct) + +``` + +### 创建类 + +要创建一个类,我们需要关键字**class**,后跟类名和冒号。类名应该使用**驼峰命名法(CamelCase)**。 + +```sh +# 语法 +class 类名: + 代码放在这里 +``` + +**示例:** + +```py +class Person: + pass +print(Person) +``` + +```sh +<__main__.Person object at 0x10804e510> +``` + +### 创建对象 + +我们可以通过调用类来创建对象。 + +```py +p = Person() +print(p) +``` + +### 类构造函数 + +在上面的例子中,我们已经从Person类创建了一个对象。然而,没有构造函数的类在实际应用中并不真正有用。让我们使用构造函数使我们的类更有用。与Java或JavaScript中的构造函数一样,Python也有一个内置的**__init__**()构造函数。**__init__**构造函数有一个self参数,它是当前类实例的引用。 +**示例:** + +```py +class Person: + def __init__ (self, name): + # self允许将参数附加到类 + self.name = name + +p = Person('Asabeneh') +print(p.name) +print(p) +``` + +```sh +# 输出 +Asabeneh +<__main__.Person object at 0x2abf46907e80> +``` + +让我们向构造函数添加更多参数。 + +```py +class Person: + def __init__(self, firstname, lastname, age, country, city): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + + +p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') +print(p.firstname) +print(p.lastname) +print(p.age) +print(p.country) +print(p.city) +``` + +```sh +# 输出 +Asabeneh +Yetayeh +250 +Finland +Helsinki +``` + +### 对象方法 + +对象可以有方法。方法是属于对象的函数。 + +**示例:** + +```py +class Person: + def __init__(self, firstname, lastname, age, country, city): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + def person_info(self): + return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' + +p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') +print(p.person_info()) +``` + +```sh +# 输出 +Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 +``` + +### 对象默认方法 + +有时,你可能希望为对象方法提供默认值。如果我们为构造函数中的参数提供默认值,可以避免在不带参数调用或实例化类时出现错误。让我们看看这是什么样子: + +**示例:** + +```py +class Person: + def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250, country='Finland', city='Helsinki'): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + + def person_info(self): + return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' + +p1 = Person() +print(p1.person_info()) +p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city') +print(p2.person_info()) +``` + +```sh +# 输出 +Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 +John Doe今年30岁。他住在Nomanland的Noman city。 +``` + +### 修改类默认值的方法 + +在下面的例子中,person类的所有构造函数参数都有默认值。此外,我们还有一个skills参数,可以通过方法访问。让我们创建一个add_skill方法,向skills列表添加技能。 + +```py +class Person: + def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250, country='Finland', city='Helsinki'): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + self.skills = [] + + def person_info(self): + return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' + def add_skill(self, skill): + self.skills.append(skill) + +p1 = Person() +print(p1.person_info()) +p1.add_skill('HTML') +p1.add_skill('CSS') +p1.add_skill('JavaScript') +p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city') +print(p2.person_info()) +print(p1.skills) +print(p2.skills) +``` + +```sh +# 输出 +Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 +John Doe今年30岁。他住在Nomanland的Noman city。 +['HTML', 'CSS', 'JavaScript'] +[] +``` + +### 继承 + +继承允许我们定义一个继承父类所有功能的类。它使代码可重用。 + +```py +# 语法 +class 子类名(父类名): + 代码放在这里 +``` + +让我们通过实际例子来看看继承的含义: + +```py +class Student(Person): + pass + + +s1 = Student('Eyob', 'Yetayeh', 30, 'Finland', 'Helsinki') +s2 = Student('Lidiya', 'Teklemariam', 28, 'Finland', 'Espoo') +print(s1.person_info()) +s1.add_skill('JavaScript') +s1.add_skill('React') +s1.add_skill('Python') +print(s1.skills) +print(s2.person_info()) +s2.add_skill('Organizing') +s2.add_skill('Marketing') +s2.add_skill('Digital Marketing') +print(s2.skills) +``` + +```sh +# 输出 +Eyob Yetayeh今年30岁。他住在Finland的Helsinki。 +['JavaScript', 'React', 'Python'] +Lidiya Teklemariam今年28岁。他住在Finland的Espoo。 +['Organizing', 'Marketing', 'Digital Marketing'] +``` + +我们没有在Student类中调用任何方法,但我们能够访问来自Parent类的所有方法。Student类继承了Person类的__init__构造函数和person_info方法。如果我们想要向子类添加一个特定于子类的新方法,我们必须编写子类并在子类中创建新的方法。 + +```py +class Student(Person): + def __init__ (self, firstname='Asabeneh', lastname='Yetayeh',age=250, country='Finland', city='Helsinki', gender='male'): + self.gender = gender + super().__init__(firstname, lastname,age, country, city) + def person_info(self): + gender = '他' if self.gender =='male' else '她' + return f'{self.firstname} {self.lastname}今年{self.age}岁。{gender}住在{self.country}的{self.city}。' + + +s1 = Student('Eyob', 'Yetayeh', 30, 'Finland', 'Helsinki','male') +s2 = Student('Lidiya', 'Teklemariam', 28, 'Finland', 'Espoo', 'female') +print(s1.person_info()) +s1.add_skill('JavaScript') +s1.add_skill('React') +s1.add_skill('Python') +print(s1.skills) +print(s2.person_info()) +s2.add_skill('Organizing') +s2.add_skill('Marketing') +s2.add_skill('Digital Marketing') +print(s2.skills) +``` + +```sh +# 输出 +Eyob Yetayeh今年30岁。他住在Finland的Helsinki。 +['JavaScript', 'React', 'Python'] +Lidiya Teklemariam今年28岁。她住在Finland的Espoo。 +['Organizing', 'Marketing', 'Digital Marketing'] +``` + +我们可以使用super()函数或父类名Person来自动继承父类的方法和属性。在上面的例子中,我们覆盖了父类方法。子类的person_info方法有不同的实现,即使方法名称与父类相同。 + +### 覆盖父类方法 + +如上所示,我们可以通过创建与父类方法名称相同的子类方法来覆盖父类方法。 + +## 💻 练习:第21天 + +### 练习:级别1 + +1. Python有一个名为_statistics_的模块,我们可以使用这个模块来计算统计数据。但是,让我们尝试开发一个可以计算均值、中位数、众数、标准差等统计数据的类。 + +```py +class Statistics: + def __init__(self, data=[]): + self.data = data + + def count(self): + # 你自己的实现 + pass + + def sum(self): + # 你自己的实现 + pass + + def min(self): + # 你自己的实现 + pass + + def max(self): + # 你自己的实现 + pass + + def range(self): + # 你自己的实现 + pass + + def mean(self): + # 你自己的实现 + pass + + def median(self): + # 你自己的实现 + pass + + def mode(self): + # 你自己的实现 + pass + + def standard_deviation(self): + # 你自己的实现 + pass + + def variance(self): + # 你自己的实现 + pass + + def frequency_distribution(self): + # 你自己的实现 + pass + + def describe(self): + # 你自己的实现 + pass +``` + +```py +# 测试代码 +data = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26] +statistics = Statistics(data) +print('Count:', statistics.count()) # 25 +print('Sum: ', statistics.sum()) # 730 +print('Min: ', statistics.min()) # 24 +print('Max: ', statistics.max()) # 38 +print('Range: ', statistics.range()) # 14 +print('Mean: ', statistics.mean()) # 29.2 +print('Median: ', statistics.median()) # 27 +print('Mode: ', statistics.mode()) # {'mode': 26, 'count': 5} +print('Standard Deviation: ', statistics.standard_deviation()) # 4.2 +print('Variance: ', statistics.variance()) # 17.5 +print('Frequency Distribution: ', statistics.frequency_distribution()) # [(24, 2), (25, 1), (26, 5), (27, 4), (29, 1), (31, 2), (32, 3), (33, 2), (34, 2), (37, 2), (38, 1)] +``` + +### 练习:级别2 + +1. 创建一个名为PersonAccount的类。它有firstname、lastname、incomes、expenses属性和添加收入、添加支出以及账户余额方法。 + +### 练习:级别3 + +1. 以下是使用函数的方法。让我们将其转换为类 + +```python +def print_products(*args, **kwargs): + for product in args: + print(product) + print(kwargs) + for key in kwargs: + print(f"{key}: {kwargs[key]}") + +print_products("apple", "banana", "orange", vegetable="tomato", juice="orange") +``` + +```sh +apple +banana +orange +{'vegetable': 'tomato', 'juice': 'orange'} +vegetable: tomato +juice: orange +``` + +1. 在一个名为PersonAccount的类中,我们有属性:firstname、lastname、incomes、expenses。设计一个类,用于计算一个人的净收入。 + +🎉 恭喜!🎉 + +[<< 第20天](../20_Day_Python_package_manager/20_python_package_manager_cn.md) | [第22天 >>](../22_Day_Web_scraping/22_web_scraping_cn.md) \ No newline at end of file diff --git a/Chinese/22_web_scraping_cn.md b/Chinese/22_web_scraping_cn.md new file mode 100644 index 000000000..ea1597371 --- /dev/null +++ b/Chinese/22_web_scraping_cn.md @@ -0,0 +1,89 @@ +# 30天Python编程挑战:第22天 - 网页抓取 + +- [第22天](#-第22天) + - [Python网页抓取](#python网页抓取) + - [什么是网页抓取](#什么是网页抓取) + - [💻 练习:第22天](#-练习第22天) + +# 📘 第22天 + +## Python网页抓取 + +### 什么是网页抓取 + +互联网充满了大量的数据,这些数据可以用于不同的目的。要收集这些数据,我们需要知道如何从网站上抓取数据。 + +网页抓取是从网站提取和收集数据,并将其存储在本地机器或数据库中的过程。 + +在本节中,我们将使用beautifulsoup和requests包来抓取数据。我们使用的是beautifulsoup 4版本。 + +要开始抓取网站,你需要_requests_、_beautifoulSoup4_和一个_网站_。 + +```sh +pip install requests +pip install beautifulsoup4 +``` + +要从网站抓取数据,需要基本了解HTML标签和CSS选择器。我们使用HTML标签、类或/和ID来定位网站上的内容。 +让我们导入requests和BeautifulSoup模块: + +```py +import requests +from bs4 import BeautifulSoup +``` + +让我们声明一个url变量,用于我们要抓取的网站。 + +```py +import requests +from bs4 import BeautifulSoup +url = 'https://archive.ics.uci.edu/ml/datasets.php' + +# 让我们使用requests的get方法从url获取数据 +response = requests.get(url) +# 检查状态 +status = response.status_code +print(status) # 200表示获取成功 +``` + +```sh +200 +``` + +使用beautifulSoup解析页面内容: + +```py +import requests +from bs4 import BeautifulSoup +url = 'https://archive.ics.uci.edu/ml/datasets.php' + +response = requests.get(url) +content = response.content # 我们从网站获取所有内容 +soup = BeautifulSoup(content, 'html.parser') # beautiful soup将给我们一个解析的机会 +print(soup.title) # UCI Machine Learning Repository: Data Sets +print(soup.title.get_text()) # UCI Machine Learning Repository: Data Sets +print(soup.body) # 给出网站上的整个页面 +print(response.status_code) + +tables = soup.find_all('table', {'cellpadding':'3'}) +# 我们定位cellpadding属性值为3的表格 +# 我们可以使用id、class或HTML标签进行选择,有关更多信息,请查看beautifulsoup文档 +table = tables[0] # 结果是一个列表,我们从中提取数据 +for td in table.find('tr').find_all('td'): + print(td.text) +``` + +如果你运行这段代码,你会发现提取工作只完成了一半。你可以继续完成它,因为这是练习1的一部分。 +参考[beautifulsoup文档](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start)获取更多信息。 + +🌕 你非常特别,你每天都在进步。你只剩下八天就要达到伟大的境界了。现在做一些练习来锻炼你的大脑和肌肉。 + +## 💻 练习:第22天 + +1. 抓取以下网站并将数据存储为json文件(url = 'http://www.bu.edu/president/boston-university-facts-stats/')。 +2. 提取此url中的表格(https://archive.ics.uci.edu/ml/datasets.php)并将其更改为json文件。 +3. 抓取总统表并将数据存储为json(https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States)。这个表格结构不是很规整,抓取可能需要很长时间。 + +🎉 恭喜!🎉 + +[<< 第21天](../21_Day_Classes_and_objects/21_classes_and_objects_cn.md) | [第23天 >>](../23_Day_Virtual_environment/23_virtual_environment_cn.md) \ No newline at end of file diff --git a/Chinese/23_virtual_environment_cn.md b/Chinese/23_virtual_environment_cn.md new file mode 100644 index 000000000..c233a8783 --- /dev/null +++ b/Chinese/23_virtual_environment_cn.md @@ -0,0 +1,97 @@ +# 30天Python编程挑战:第23天 - 虚拟环境 + +- [第23天](#-第23天) + - [设置虚拟环境](#设置虚拟环境) + - [💻 练习:第23天](#-练习第23天) + +# 📘 第23天 + +## 设置虚拟环境 + +开始项目时,最好有一个虚拟环境。虚拟环境可以帮助我们创建一个隔离或独立的环境。这将有助于避免不同项目之间的依赖冲突。如果你在终端上输入pip freeze,你将看到计算机上安装的所有包。如果我们使用virtualenv,我们将只能访问特定于该项目的包。打开你的终端并安装virtualenv: + +```sh +asabeneh@Asabeneh:~$ pip install virtualenv +``` + +在30DaysOfPython文件夹内创建一个flask_project文件夹。 + +安装virtualenv包后,进入项目文件夹并通过以下命令创建虚拟环境: + +对于Mac/Linux: +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ virtualenv venv +``` + +对于Windows: +```sh +C:\Users\User\Documents\30DaysOfPython\flask_project>python -m venv venv +``` + +我喜欢将新项目称为venv,但你可以随意命名。让我们使用ls(或Windows命令提示符的dir)命令检查venv是否已创建。 + +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ ls +venv/ +``` + +让我们通过在项目文件夹中编写以下命令来激活虚拟环境。 + +对于Mac/Linux: +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ source venv/bin/activate +``` + +Windows上虚拟环境的激活可能因Windows PowerShell和git bash而异。 + +对于Windows PowerShell: +```sh +C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\activate +``` + +对于Windows Git bash: +```sh +C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\. activate +``` + +输入激活命令后,你的项目目录将以venv开头。请参见下面的示例。 + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ +``` + +现在,让我们通过输入pip freeze来检查这个项目中可用的包。你不会看到任何包。 + +我们将做一个小型flask项目,所以让我们为这个项目安装flask包。 + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install Flask +``` + +现在,让我们输入pip freeze查看项目中已安装的包列表: + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip freeze +Click==7.0 +Flask==1.1.1 +itsdangerous==1.1.0 +Jinja2==2.10.3 +MarkupSafe==1.1.1 +Werkzeug==0.16.0 +``` + +完成后,你应该使用_deactivate_来关闭活动项目。 + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ deactivate +``` + +使用flask所需的模块已经安装好了。现在,你的项目目录已经准备好用于flask项目。你应该将venv包含在.gitignore文件中,以避免将其推送到GitHub。 + +## 💻 练习:第23天 + +1. 根据上面给出的示例创建一个带有虚拟环境的项目目录。 + +🎉 恭喜!🎉 + +[<< 第22天](../22_Day_Web_scraping/22_web_scraping_cn.md) | [第24天 >>](../24_Day_Statistics/24_statistics_cn.md) \ No newline at end of file diff --git a/Chinese/24_statistics_cn.md b/Chinese/24_statistics_cn.md new file mode 100644 index 000000000..7a54dcfad --- /dev/null +++ b/Chinese/24_statistics_cn.md @@ -0,0 +1,589 @@ +# 30天Python编程挑战:第24天 - 统计 + +- [第24天](#-第24天) + - [Python进行统计分析](#python进行统计分析) + - [统计学](#统计学) + - [数据](#数据) + - [统计模块](#统计模块) +- [NumPy](#numpy) + - [导入NumPy](#导入numpy) + - [使用NumPy创建数组](#使用numpy创建数组) + - [创建整型NumPy数组](#创建整型numpy数组) + - [创建浮点型NumPy数组](#创建浮点型numpy数组) + - [创建布尔型NumPy数组](#创建布尔型numpy数组) + - [使用NumPy创建多维数组](#使用numpy创建多维数组) + - [将NumPy数组转换为列表](#将numpy数组转换为列表) + - [从元组创建NumPy数组](#从元组创建numpy数组) + - [NumPy数组的形状](#numpy数组的形状) + - [NumPy数组的数据类型](#numpy数组的数据类型) + - [NumPy数组的大小](#numpy数组的大小) + - [使用NumPy进行数学运算](#使用numpy进行数学运算) + - [加法](#加法) + +# 📘 第24天 + +## Python进行统计分析 + +## 统计学 + +统计学是研究数据的_收集_、_组织_、_显示_、_分析_、_解释_和_呈现_的学科。 +统计学是数学的一个分支,建议作为数据科学和机器学习的先决条件。统计学是一个非常广泛的领域,但在本节中,我们将只关注最相关的部分。 +完成这个挑战后,你可以进入Web开发、数据分析、机器学习和数据科学的道路。无论你选择哪条路,在你的职业生涯中的某个时刻,你都会得到可能需要处理的数据。拥有一些统计知识将帮助你基于数据做出决策,正如他们所说的_数据会告诉我们_。 + +## 数据 + +什么是数据?数据是为某种目的收集和翻译的任何字符集,通常用于分析。它可以是任何字符,包括文本和数字、图片、声音或视频。如果数据没有放在上下文中,对人类或计算机来说都没有任何意义。为了从数据中获取意义,我们需要使用不同的工具来处理数据。 + +数据分析、数据科学或机器学习的工作流程都是从数据开始的。数据可以由某些数据源提供,也可以创建。有结构化和非结构化数据。 + +数据可以以小型或大型格式存在。我们将获得的大多数数据类型已在文件处理部分中介绍。 + +## 统计模块 + +Python的_statistics_模块提供了用于计算数值数据的数学统计的函数。该模块并不打算与第三方库如NumPy、SciPy或面向专业统计学家的专有全功能统计软件包(如Minitab、SAS和Matlab)竞争。它的目标是达到图形和科学计算器的水平。 + +# NumPy + +在第一部分中,我们将Python定义为一种优秀的通用编程语言,但在其他流行库(如numpy、scipy、matplotlib、pandas等)的帮助下,它成为了一个强大的科学计算环境。 + +NumPy是Python中科学计算的核心库。它提供了高性能的多维数组对象和用于处理这些数组的工具。 + +到目前为止,我们一直在使用vscode,但从现在开始,我建议使用Jupyter Notebook。要访问jupyter notebook,让我们安装[anaconda](https://www.anaconda.com/)。如果你使用anaconda,大多数常用的包都已包含在内,如果你已安装anaconda,就不需要再安装这些包。 + +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ pip install numpy +``` + +## 导入NumPy + +如果你喜欢[jupyter notebook](https://github.com/Asabeneh/data-science-for-everyone/blob/master/numpy/numpy.ipynb),可以使用它 + +```py +# 如何导入numpy +import numpy as np +# 如何检查numpy包的版本 +print('numpy:', np.__version__) +# 检查可用的方法 +print(dir(np)) +``` + +## 使用NumPy创建数组 + +### 创建整型NumPy数组 + +```py +# 创建Python列表 +python_list = [1,2,3,4,5] + +# 检查数据类型 +print('Type:', type (python_list)) # +# +print(python_list) # [1, 2, 3, 4, 5] + +two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]] + +print(two_dimensional_list) # [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + +# 从Python列表创建NumPy(数值Python)数组 + +numpy_array_from_list = np.array(python_list) +print(type (numpy_array_from_list)) # +print(numpy_array_from_list) # array([1, 2, 3, 4, 5]) +``` + +### 创建浮点型NumPy数组 + +使用浮点数据类型参数从列表创建浮点NumPy数组 + +```py +# Python列表 +python_list = [1,2,3,4,5] + +numy_array_from_list2 = np.array(python_list, dtype=float) +print(numy_array_from_list2) # array([1., 2., 3., 4., 5.]) +``` + +### 创建布尔型NumPy数组 + +从列表创建布尔NumPy数组 + +```py +numpy_bool_array = np.array([0, 1, -1, 0, 0], dtype=bool) +print(numpy_bool_array) # array([False, True, True, False, False]) +``` + +### 使用NumPy创建多维数组 + +一个NumPy数组可能有一个或多个行和列 + +```py +two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]] +numpy_two_dimensional_list = np.array(two_dimensional_list) +print(type (numpy_two_dimensional_list)) +print(numpy_two_dimensional_list) +``` + +```sh + +[[0 1 2] + [3 4 5] + [6 7 8]] +``` + +### 将NumPy数组转换为列表 + +```python +# 我们总是可以使用tolist()将数组转换回Python列表。 +np_to_list = numpy_array_from_list.tolist() +print(type (np_to_list)) +print('一维数组:', np_to_list) +print('二维数组: ', numpy_two_dimensional_list.tolist()) +``` + +```sh + +一维数组: [1, 2, 3, 4, 5] +二维数组: [[0, 1, 2], [3, 4, 5], [6, 7, 8]] +``` + +### 从元组创建NumPy数组 + +```py +# 从元组创建NumPy数组 +# 在Python中创建元组 +python_tuple = (1,2,3,4,5) +print(type (python_tuple)) # +print('python_tuple: ', python_tuple) # python_tuple: (1, 2, 3, 4, 5) + +numpy_array_from_tuple = np.array(python_tuple) +print(type (numpy_array_from_tuple)) # +print('numpy_array_from_tuple: ', numpy_array_from_tuple) # numpy_array_from_tuple: [1 2 3 4 5] +``` + +### NumPy数组的形状 + +shape方法以元组形式提供数组的形状。第一个是行,第二个是列。如果数组只是一维的,它返回数组的大小。 + +```py +nums = np.array([1, 2, 3, 4, 5]) +print(nums) +print('nums的形状: ', nums.shape) +print(numpy_two_dimensional_list) +print('numpy_two_dimensional_list的形状: ', numpy_two_dimensional_list.shape) +three_by_four_array = np.array([[0, 1, 2, 3], + [4,5,6,7], + [8,9,10, 11]]) +print(three_by_four_array.shape) +``` + +```sh +[1 2 3 4 5] +nums的形状: (5,) +[[0 1 2] + [3 4 5] + [6 7 8]] +numpy_two_dimensional_list的形状: (3, 3) +(3, 4) +``` + +### NumPy数组的数据类型 + +数据类型的类型:str, int, float, complex, bool, list, None + +```py +int_lists = [-3, -2, -1, 0, 1, 2,3] +int_array = np.array(int_lists) +float_array = np.array(int_lists, dtype=float) + +print(int_array) +print(int_array.dtype) +print(float_array) +print(float_array.dtype) +``` + +```sh +[-3 -2 -1 0 1 2 3] +int64 +[-3. -2. -1. 0. 1. 2. 3.] +float64 +``` + +### NumPy数组的大小 + +在NumPy中,要知道NumPy数组列表中的项目数,我们使用size + +```py +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +two_dimensional_list = np.array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + +print('大小:', numpy_array_from_list.size) # 5 +print('大小:', two_dimensional_list.size) # 9 +``` + +```sh +大小: 5 +大小: 9 +``` + +## 使用NumPy进行数学运算 + +NumPy数组与Python列表不完全相同。要对Python列表进行数学运算,我们必须遍历项目,但NumPy可以不通过循环就进行任何数学运算。 +数学运算: + +- 加法 (+) +- 减法 (-) +- 乘法 (*) +- 除法 (/) +- 模数 (%) +- 整除 (//) +- 指数 (**) + +### 加法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('加法: ', numpy_array_from_list + 2) +print('加法: ', np.add(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +加法: [3 4 5 6 7] +加法: [3 4 5 6 7] +``` + +### 减法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('减法: ', numpy_array_from_list - 2) +print('减法: ', np.subtract(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +减法: [-1 0 1 2 3] +减法: [-1 0 1 2 3] +``` + +### 乘法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('乘法: ', numpy_array_from_list * 2) +print('乘法: ', np.multiply(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +乘法: [ 2 4 6 8 10] +乘法: [ 2 4 6 8 10] +``` + +### 除法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('除法: ', numpy_array_from_list / 2) +print('除法: ', np.divide(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +除法: [0.5 1. 1.5 2. 2.5] +除法: [0.5 1. 1.5 2. 2.5] +``` + +### 模数 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('模数: ', numpy_array_from_list % 2) +print('模数: ', np.mod(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +模数: [1 0 1 0 1] +模数: [1 0 1 0 1] +``` + +### 整除 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('整除: ', numpy_array_from_list // 2) +print('整除: ', np.floor_divide(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +整除: [0 1 1 2 2] +整除: [0 1 1 2 2] +``` + +### 指数 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('指数: ', numpy_array_from_list ** 2) +print('指数: ', np.power(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +指数: [ 1 4 9 16 25] +指数: [ 1 4 9 16 25] +``` + +## 检查数据类型 + +```py +numpy_int_arr = np.array([1, 2, 3, 4]) +numpy_float_arr = np.array([1.1, 2.0, 3.2]) +numpy_bool_arr = np.array([-3, -2, 0, 1, 2, 3], dtype='bool') + +print(numpy_int_arr.dtype) +print(numpy_float_arr.dtype) +print(numpy_bool_arr.dtype) +``` + +```sh +int64 +float64 +bool +``` + +## 转换类型 + +我们可以使用astype将数据类型从一种类型转换为另一种类型。让我们将int类型转换为浮点数,浮点数转换为整数,整数转换为布尔型。 + +```py +numpy_int_arr = np.array([1, 2, 3, 4], dtype='float') +numpy_int_arr.astype('int').dtype +numpy_float_arr = np.array([1.1, 2.0, 3.2]) +numpy_float_arr.astype('int').dtype +numpy_int_arr = np.array([-3, -2, 0, 1, 2, 3]) +numpy_int_arr.astype('bool').dtype +``` + +```sh +int64 +int64 +bool +``` + +## 多维数组 + +NumPy的主要优点之一是处理多维数组。我们先构建多维数组。 + +```py +two_dimension_array = np.array([(1,2,3),(4,5,6), (7,8,9)]) +print(type (two_dimension_array)) +print(two_dimension_array) +print('形状: ', two_dimension_array.shape) +print('大小: ', two_dimension_array.size) +print('数据类型: ', two_dimension_array.dtype) +``` + +```sh + +[[1 2 3] + [4 5 6] + [7 8 9]] +形状: (3, 3) +大小: 9 +数据类型: int64 +``` + +### 从NumPy中获取项目 + +```py +# 二维数组 +two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]]) +first_row = two_dimension_array[0] +second_row = two_dimension_array[1] +third_row = two_dimension_array[2] +print('第一行:', first_row) +print('第二行:', second_row) +print('第三行: ', third_row) +``` + +```sh +第一行: [1 2 3] +第二行: [4 5 6] +第三行: [7 8 9] +``` + +现在让我们获取每一行的第一项: + +```py +first_column= two_dimension_array[:,0] +second_column = two_dimension_array[:,1] +third_column = two_dimension_array[:,2] +print('第一列:', first_column) +print('第二列:', second_column) +print('第三列: ', third_column) +``` + +```sh +第一列: [1 4 7] +第二列: [2 5 8] +第三列: [3 6 9] +``` + +## NumPy数组切片 + +切片NumPy数组与切片Python列表相似,只是它适用于两个维度(行和列)。让我们先看看如何从NumPy数组中切片项目。 + +```py +numpy_array_from_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) +print('原始数组:', numpy_array_from_list) + +# 第一个参数代表:起始位置 +# 第二个参数代表:停止位置 +# 第三个参数代表:步长 +print('第一个参数代表:起始位置') +print('第二个参数代表:停止位置') +print('第三个参数代表:步长') +# 使用正index +ten_first_items = numpy_array_from_list[0:10] +print('前10项:', ten_first_items) +first_five_items = numpy_array_from_list[:5] +print('前5项:', first_five_items) +last_five_items = numpy_array_from_list[5:] +print('后5项:', last_five_items) +# 使用负index +last_five_items = numpy_array_from_list[-5:] +print('后5项:', last_five_items) +``` + +```sh +原始数组: [ 1 2 3 4 5 6 7 8 9 10] +第一个参数代表:起始位置 +第二个参数代表:停止位置 +第三个参数代表:步长 +前10项: [ 1 2 3 4 5 6 7 8 9 10] +前5项: [1 2 3 4 5] +后5项: [ 6 7 8 9 10] +后5项: [ 6 7 8 9 10] +``` + +现在,让我们通过设置步长来访问每个2个项目: + +```py +every_two_item = numpy_array_from_list[::2] +print('每隔一项:', every_two_item) +``` + +```sh +每隔一项: [1 3 5 7 9] +``` + +让我们反转数组: + +```py +reversed_array = numpy_array_from_list[::-1] +print('反转数组:', reversed_array) +``` + +```sh +反转数组: [10 9 8 7 6 5 4 3 2 1] +``` + +我们可以在NumPy二维数组上使用切片: + +```py +two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]]) +print(two_dimension_array) +print(two_dimension_array[1, 1]) +print(two_dimension_array[1, 1:3]) +print(two_dimension_array[1:3, 1:3]) +``` + +```sh +[[1 2 3] + [4 5 6] + [7 8 9]] +5 +[5 6] +[[5 6] + [8 9]] +``` + +## NumPy连接数组 + +NumPy提供了连接数组的方法。 + +```py +first_array = np.array([1, 2, 3]) +second_array = np.array([4, 5, 6]) +third_array = np.array([7, 8, 9]) +print('第一个数组:', first_array) +print('第二个数组:', second_array) +print('第三个数组:', third_array) +``` + +```sh +第一个数组: [1 2 3] +第二个数组: [4 5 6] +第三个数组: [7 8 9] +``` + +### 水平连接 + +```py +horizontal_concat = np.hstack((first_array, second_array, third_array)) +print('水平连接:', horizontal_concat) +``` + +```sh +水平连接: [1 2 3 4 5 6 7 8 9] +``` + +### 垂直连接 + +```py +vertical_concat = np.vstack((first_array, second_array, third_array)) +print('垂直连接:', vertical_concat) +``` + +```sh +垂直连接: +[[1 2 3] + [4 5 6] + [7 8 9]] +``` + +## 常见NumPy函数 + +我们看看最常见的NumPy函数: + +### 最小值、最大值、平均值、中位数和百分位数 + +```py +numpy_array_from_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) +print('最小值:', numpy_array_from_list.min()) +print('最大值:', numpy_array_from_list.max()) +print('平均值:', numpy_array_from_list.mean()) +``` + +🎉 恭喜!🎉 + +[<< 第23天](../23_Day_Virtual_environment/23_virtual_environment_cn.md) | [第25天 >>](../25_Day_Pandas/25_pandas_cn.md) \ No newline at end of file diff --git a/Chinese/25_pandas_cn.md b/Chinese/25_pandas_cn.md new file mode 100644 index 000000000..c7aa8a017 --- /dev/null +++ b/Chinese/25_pandas_cn.md @@ -0,0 +1,551 @@ +# 30天Python编程挑战:第25天 - Pandas + +- [第25天](#-第25天) + - [Pandas](#pandas) + - [安装Pandas](#安装pandas) + - [导入Pandas](#导入pandas) + - [使用默认索引创建Pandas系列](#使用默认索引创建pandas系列) + - [使用自定义索引创建Pandas系列](#使用自定义索引创建pandas系列) + - [从字典创建Pandas系列](#从字典创建pandas系列) + - [创建常量Pandas系列](#创建常量pandas系列) + - [使用Linspace创建Pandas系列](#使用linspace创建pandas系列) + - [数据框(DataFrames)](#数据框dataframes) + - [从列表的列表创建数据框](#从列表的列表创建数据框) + - [使用字典创建数据框](#使用字典创建数据框) + - [从字典列表创建数据框](#从字典列表创建数据框) + - [使用Pandas读取CSV文件](#使用pandas读取csv文件) + - [数据探索](#数据探索) + - [修改数据框](#修改数据框) + - [创建数据框](#创建数据框) + - [添加新列](#添加新列) + - [修改列值](#修改列值) + - [格式化数据框列](#格式化数据框列) + - [检查列值的数据类型](#检查列值的数据类型) + - [布尔索引](#布尔索引) + - [练习:第25天](#练习第25天) + +# 📘 第25天 + +## Pandas + +Pandas是一个开源的、高性能的、易于使用的Python编程语言数据结构和数据分析工具。 +Pandas添加了设计用于处理表格数据的数据结构和工具,这些数据结构是*系列(Series)*和*数据框(Data Frames)*。 +Pandas提供了用于数据操作的工具: + +- 重塑 +- 合并 +- 排序 +- 切片 +- 聚合 +- 插补 +如果你使用的是anaconda,则不必安装pandas。 + +### 安装Pandas + +对于Mac: +```py +pip install conda +conda install pandas +``` + +对于Windows: +```py +pip install conda +pip install pandas +``` + +Pandas数据结构基于*系列(Series)*和*数据框(DataFrames)*。 + +*系列*是一个*列*,而数据框是由*系列*集合组成的*多维表*。为了创建pandas系列,我们应该使用numpy创建一维数组或Python列表。 +让我们看一个系列的例子: + +名称Pandas系列 + +![pandas series](../images/pandas-series-1.png) + +国家系列 + +![pandas series](../images/pandas-series-2.png) + +城市系列 + +![pandas series](../images/pandas-series-3.png) + +如你所见,pandas系列只是一列数据。如果我们想要有多列,我们使用数据框。下面的例子显示了pandas数据框。 + +让我们看一个pandas数据框的例子: + +![Pandas data frame](../images/pandas-dataframe-1.png) + +数据框是行和列的集合。看看下面的表格;它比上面的例子有更多的列: + +![Pandas data frame](../images/pandas-dataframe-2.png) + +接下来,我们将看到如何导入pandas以及如何使用pandas创建系列和数据框 + +### 导入Pandas + +```python +import pandas as pd # 将pandas导入为pd +import numpy as np # 将numpy导入为np +``` + +### 使用默认索引创建Pandas系列 + +```python +nums = [1, 2, 3, 4,5] +s = pd.Series(nums) +print(s) +``` + +```sh +0 1 +1 2 +2 3 +3 4 +4 5 +dtype: int64 +``` + +### 使用自定义索引创建Pandas系列 + +```python +nums = [1, 2, 3, 4, 5] +s = pd.Series(nums, index=[1, 2, 3, 4, 5]) +print(s) +``` + +```sh +1 1 +2 2 +3 3 +4 4 +5 5 +dtype: int64 +``` + +```python +fruits = ['Orange','Banana','Mango'] +fruits = pd.Series(fruits, index=[1, 2, 3]) +print(fruits) +``` + +```sh +1 Orange +2 Banana +3 Mango +dtype: object +``` + +### 从字典创建Pandas系列 + +```python +dct = {'name':'Asabeneh','country':'Finland','city':'Helsinki'} +``` + +```python +s = pd.Series(dct) +print(s) +``` + +```sh +name Asabeneh +country Finland +city Helsinki +dtype: object +``` + +### 创建常量Pandas系列 + +```python +s = pd.Series(10, index = [1, 2, 3]) +print(s) +``` + +```sh +1 10 +2 10 +3 10 +dtype: int64 +``` + +### 使用Linspace创建Pandas系列 + +```python +s = pd.Series(np.linspace(5, 20, 10)) # linspace(起始点, 终点, 项目数) +print(s) +``` + +```sh +0 5.000000 +1 6.666667 +2 8.333333 +3 10.000000 +4 11.666667 +5 13.333333 +6 15.000000 +7 16.666667 +8 18.333333 +9 20.000000 +dtype: float64 +``` + +## 数据框(DataFrames) + +Pandas数据框可以以不同的方式创建: + +- 从列表的列表创建 +- 从字典创建 +- 从字典的列表创建 +- 从CSV文件创建 + +### 从列表的列表创建数据框 + +```python +data = [ + ['Asabeneh', 'Finland', 'Helsinki'], + ['David', 'UK', 'London'], + ['John', 'Sweden', 'Stockholm'] +] +df = pd.DataFrame(data, columns=['Name', 'Country', 'City']) +print(df) +``` + +```sh + Name Country City +0 Asabeneh Finland Helsinki +1 David UK London +2 John Sweden Stockholm +``` + +### 使用字典创建数据框 + +```python +data = {'Name': ['Asabeneh', 'David', 'John'], 'Country':[ + 'Finland', 'UK', 'Sweden'], 'City': ['Helsinki', 'London', 'Stockholm']} +df = pd.DataFrame(data) +print(df) +``` + +```sh + Name Country City +0 Asabeneh Finland Helsinki +1 David UK London +2 John Sweden Stockholm +``` + +### 从字典列表创建数据框 + +```python +data = [ + {'Name': 'Asabeneh', 'Country': 'Finland', 'City': 'Helsinki'}, + {'Name': 'David', 'Country': 'UK', 'City': 'London'}, + {'Name': 'John', 'Country': 'Sweden', 'City': 'Stockholm'}] +df = pd.DataFrame(data) +print(df) +``` + +```sh + Name Country City +0 Asabeneh Finland Helsinki +1 David UK London +2 John Sweden Stockholm +``` + +## 使用Pandas读取CSV文件 + +让我们在数据目录中读取文件,将通过将文件路径作为参数传递给pd.read_csv()函数来读取weight-height.csv文件。让我们使用head()方法查看前五行。 + +```python +import pandas as pd + +df = pd.read_csv('./data/weight-height.csv') +print(df.head()) # 默认为前五行 +``` + +```sh + Gender Height Weight +0 Male 73.847017 241.893563 +1 Male 68.781904 162.310473 +2 Male 74.110105 212.740856 +3 Male 71.730978 220.042470 +4 Male 69.881796 206.349801 +``` + +让我们使用tail()方法查看最后五行: + +```python +print(df.tail()) # 最后五行 +``` + +```sh + Gender Height Weight +9995 Female 66.172652 136.777454 +9996 Female 67.067155 170.867906 +9997 Female 63.867992 128.475319 +9998 Female 69.034243 163.852461 +9999 Female 61.944246 113.649103 +``` + +### 数据探索 + +让我们使用shape属性获取行和列的数量: +```python +print(df.shape) # 行和列的数量 +``` + +```sh +(10000, 3) +``` + +如你所见,该数据集有10000行和3列。让我们获取有关数据的更多信息: + +```python +print(df.columns) # 列名 +print(df.head(10)) # 前10行 +print(df.tail(10)) # 最后10行 +print(df['Gender'].value_counts()) # 计算每个值有多少个 +print(df.describe()) # 数据统计概要 +``` + +```sh +Index(['Gender', 'Height', 'Weight'], dtype='object') + Gender Height Weight +0 Male 73.847017 241.893563 +1 Male 68.781904 162.310473 +2 Male 74.110105 212.740856 +3 Male 71.730978 220.042470 +4 Male 69.881796 206.349801 +5 Male 68.767792 152.212156 +6 Male 67.961960 183.927889 +7 Male 68.563817 175.929316 +8 Male 71.267570 196.028855 +9 Male 72.040119 205.801386 + Gender Height Weight +9990 Female 64.744846 139.725595 +9991 Female 62.109532 132.451630 +9992 Female 62.593008 130.727432 +9993 Female 62.100222 131.220717 +9994 Female 63.421888 133.330246 +9995 Female 66.172652 136.777454 +9996 Female 67.067155 170.867906 +9997 Female 63.867992 128.475319 +9998 Female 69.034243 163.852461 +9999 Female 61.944246 113.649103 +Gender +Male 5000 +Female 5000 +Name: count, dtype: int64 + Height Weight +count 10000.000000 10000.000000 +mean 66.367560 161.440357 +std 3.847528 32.108439 +min 54.263133 64.700127 +25% 63.505620 135.818051 +50% 66.318070 161.212928 +75% 69.174262 187.169525 +max 78.998742 269.989699 +``` + +## 修改数据框 + +### 创建数据框 + +首先,让我们使用前面学到的内容创建一个数据框: + +```python +# 导入pandas包 +import pandas as pd +# 导入numpy包 +import numpy as np +# 数据 +data = [ + {"Name": "张三", "Country":"中国", "City":"上海"}, + {"Name": "李四", "Country":"中国", "City":"北京"}, + {"Name": "王五", "Country":"中国", "City":"广州"}] +# 创建一个数据框 +df = pd.DataFrame(data) +print(df) +``` + +```sh + Name Country City +0 张三 中国 上海 +1 李四 中国 北京 +2 王五 中国 广州 +``` + +### 添加新列 + +让我们向DataFrame添加权重列: + +```python +weights = [74, 78, 69] +df['Weight'] = weights +df +``` + +```sh + Name Country City Weight +0 张三 中国 上海 74 +1 李四 中国 北京 78 +2 王五 中国 广州 69 +``` + +让我们添加一个高度列: + +```python +heights = [173, 175, 169] +df['Height'] = heights +df +``` + +```sh + Name Country City Weight Height +0 张三 中国 上海 74 173 +1 李四 中国 北京 78 175 +2 王五 中国 广州 69 169 +``` + +### 修改列值 + +我们可以通过三种方式修改列: + +1. 直接在列名中写入新数据: + +```python +df['Name'] = ['赵六', '钱七', '孙八'] +df +``` + +```sh + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 钱七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +``` + +2. 通过索引进行修改: + +```python +df.loc[1, 'Name'] = '小七' +df +``` + +```sh + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 小七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +``` + +通过iloc索引: + +```python +print('原始数据:\n', df) +df.iloc[1, 0] = '阿七' +print('修改后的数据:\n', df) +``` + +```sh +原始数据: + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 小七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +修改后的数据: + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 阿七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +``` + +### 格式化数据框列 + +让我们使用格式进行修改。强大公式是BMI:体重(kg)/ 身高²(m)。让我们添加一个BMI列: + +```python +# 添加身高、体重和BMI列 +df['BMI'] = np.round(df['Weight'] / ((df['Height'] * 0.01) ** 2), 2) # 保留两位小数 + +print(df) +``` + +```sh + Name Country City Weight Height BMI +0 赵六 中国 上海 74 173 24.73 +1 阿七 中国 北京 78 175 25.47 +2 孙八 中国 广州 69 169 24.16 +``` + +## 检查列值的数据类型 + +我们可以使用dtypes属性检查DataFrame中列的数据类型: + +```python +print(df.dtypes) +``` + +```sh +Name object +Country object +City object +Weight int64 +Height int64 +BMI float64 +dtype: object +``` + +### 布尔索引 + +布尔索引或布尔掩码允许您使用条件选择DataFrame中的特定行: + +```python +# 创建一个数据框 +df = pd.DataFrame({ + 'name': ['张三', '李四', '王五', '赵六'], + 'country': ['中国', '美国', '英国', '西班牙'], + 'age': [25, 15, 22, 28], + '在职': [True, False, True, False] +}) + +print(df) +``` + +```sh + name country age 在职 +0 张三 中国 25 True +1 李四 美国 15 False +2 王五 英国 22 True +3 赵六 西班牙 28 False +``` + +让我们筛选出年龄大于20岁且在职的人员: + +```python +print(df[(df['age'] > 20) & (df['在职'] == True)]) +``` + +```sh + name country age 在职 +0 张三 中国 25 True +2 王五 英国 22 True +``` + +## 练习:第25天 + +1. 阅读[hacker_news.csv](../data/hacker_news.csv)文件并获取前五行 +2. 获取标题列 +3. 获取行数、列数 +4. 获取前十行和最后十行 +5. 获取第二行和第四行从第二列到第四列的数据 +6. 获取主题为Python的行 +7. 获取Python主题行的数量 +8. 获取投票数超过200的所有行 +9. 按投票数排序数据框 +10. 按投票数进行降序排序 +11. 过滤掉Python主题并按票数排序 + +🎉 恭喜!🎉 + +[<< 第24天](../24_Day_Statistics/24_statistics_cn.md) | [第26天 >>](../26_Day_Python_web/26_python_web_cn.md) \ No newline at end of file diff --git a/Chinese/26_python_web_cn.md b/Chinese/26_python_web_cn.md new file mode 100644 index 000000000..8d5989c45 --- /dev/null +++ b/Chinese/26_python_web_cn.md @@ -0,0 +1,817 @@ +# 30天Python编程挑战:第26天 - Python网络编程 + +- [第26天](#-第26天) + - [Python网络编程](#python网络编程) + - [Flask](#flask) + - [文件夹结构](#文件夹结构) + - [设置项目目录](#设置项目目录) + - [创建路由](#创建路由) + - [创建模板](#创建模板) + - [Python脚本](#python脚本) + - [导航](#导航) + - [创建布局](#创建布局) + - [提供静态文件](#提供静态文件) + - [部署](#部署) + - [创建Heroku账户](#创建heroku账户) + - [登录Heroku](#登录heroku) + - [创建requirements和Procfile](#创建requirements和procfile) + - [将项目推送到Heroku](#将项目推送到heroku) + - [练习:第26天](#练习第26天) + +# 📘 第26天 + +## Python网络编程 + +Python是一种通用编程语言,可以用于多种场合。在本节中,我们将看到如何使用Python进行网络开发。Python有许多Web框架。Django和Flask是最流行的框架。今天,我们将学习如何使用Flask进行Web开发。 + +### Flask + +Flask是用Python编写的Web开发框架。Flask使用Jinja2模板引擎。Flask也可以与其他现代前端库(如React)一起使用。 + +如果你还没有安装virtualenv包,请先安装它。虚拟环境将允许隔离项目依赖与本地机器依赖。 + +#### 文件夹结构 + +完成所有步骤后,你的项目文件结构应该如下所示: + +```sh +├── Procfile +├── app.py +├── env +│ ├── bin +├── requirements.txt +├── static +│ └── css +│ └── main.css +└── templates + ├── about.html + ├── home.html + ├── layout.html + ├── post.html + └── result.html +``` + +### 设置项目目录 + +按照以下步骤开始使用Flask。 + +步骤1:使用以下命令安装virtualenv。 + +```sh +pip install virtualenv +``` + +步骤2: + +```sh +asabeneh@Asabeneh:~/Desktop$ mkdir python_for_web +asabeneh@Asabeneh:~/Desktop$ cd python_for_web/ +asabeneh@Asabeneh:~/Desktop/python_for_web$ virtualenv venv +asabeneh@Asabeneh:~/Desktop/python_for_web$ source venv/bin/activate +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install Flask +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze +Click==7.0 +Flask==1.1.1 +itsdangerous==1.1.0 +Jinja2==2.10.3 +MarkupSafe==1.1.1 +Werkzeug==0.16.0 +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ +``` + +我们创建了一个名为python_for_web的项目目录。在项目中,我们创建了一个虚拟环境*venv*,它可以是任何名称,但我喜欢称它为_venv_。然后我们激活了虚拟环境。我们使用pip freeze检查项目目录中安装的包。pip freeze的结果是空的,因为还没有安装包。 + +现在,让我们在项目目录中创建app.py文件并编写以下代码。app.py文件将是项目中的主文件。以下代码包含flask模块和os模块。 + +### 创建路由 + +主页路由。 + +```py +# 导入flask +from flask import Flask +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + return '

欢迎

' + +@app.route('/about') +def about(): + return '

关于我们

' + + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +要运行flask应用程序,在主flask应用程序目录中输入python app.py。 + +运行_python app.py_后,检查本地主机5000端口。 + +让我们添加额外的路由。 +创建关于路由 + +```py +# 导入flask +from flask import Flask +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + return '

欢迎

' + +@app.route('/about') +def about(): + return '

关于我们

' + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +现在,我们在上面的代码中添加了关于路由。如果我们想渲染HTML文件而不是字符串呢?使用*render_template*函数可以渲染HTML文件。让我们在项目目录中创建一个名为templates的文件夹,并在其中创建home.html和about.html。让我们也从flask导入*render_template*函数。 + +### 创建模板 + +在templates文件夹内创建HTML文件。 + +home.html + +```html + + + + + + 主页 + + + +

欢迎回家

+ + +``` + +about.html + +```html + + + + + + 关于 + + + +

关于我们

+ + +``` + +### Python脚本 + +app.py + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + return render_template('home.html') + +@app.route('/about') +def about(): + return render_template('about.html') + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +正如你所看到的,为了访问不同的页面或进行导航,我们需要一个导航。让我们为每个页面添加一个链接,或者创建一个我们用于每个页面的布局。 + +### 导航 + +```html + +``` + +现在,我们可以使用上面的链接在页面之间导航。让我们创建一个额外的页面来处理表单数据。你可以给它取任何名字,我喜欢称它为post.html。 + +我们可以使用Jinja2模板引擎向HTML文件注入数据。 + +```py +# 导入flask +from flask import Flask, render_template, request, redirect, url_for +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + techs = ['HTML', 'CSS', 'Flask', 'Python'] + name = '30天Python编程挑战' + return render_template('home.html', techs=techs, name=name, title='主页') + +@app.route('/about') +def about(): + name = '30天Python编程挑战' + return render_template('about.html', name=name, title='关于我们') + +@app.route('/post') +def post(): + name = '编程语言文章' + path = request.path + return render_template('post.html', name=name, path=path, title='文章') + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +home.html + +```html + + + + + + {{title}} + + + + +

欢迎回到{{name}}

+
    + {% for tech in techs %} +
  • {{tech}}
  • + {% endfor %} +
+ + +``` + +about.html + +```html + + + + + + {{title}} + + + + +

关于{{name}}

+ + +``` + +post.html + +```html + + + + + + {{title}} + + + + +

{{name}}

+

当前路径: {{path}}

+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + +``` + +现在,让我们添加一个接收表单数据的路由。我们使用POST方法,因为我们将收到表单数据。 + +```py +# 导入flask +from flask import Flask, render_template, request, redirect, url_for +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home(): + techs = ['HTML', 'CSS', 'Flask', 'Python'] + name = '30天Python编程挑战' + return render_template('home.html', techs=techs, name=name, title='主页') + +@app.route('/about') +def about(): + name = '30天Python编程挑战' + return render_template('about.html', name=name, title='关于我们') + +@app.route('/post') +def post(): + name = '文章' + return render_template('post.html', name=name, title='文章') + + +@app.route('/result', methods=['POST']) +def result(): + first_name = request.form['first_name'] + last_name = request.form['last_name'] + old_job = request.form['old_job'] + current_job = request.form['current_job'] + country = request.form['country'] + print(first_name, last_name, old_job, current_job, country) + result_data = { + 'first_name':first_name, + 'last_name':last_name, + 'old_job': old_job, + 'current_job': current_job, + 'country':country + } + return render_template('result.html', result_data = result_data, title= '结果') + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +result.html + +```html + + + + + + {{title}} + + + + +

表单数据

+ +
    +
  • 第一名字: {{result_data.first_name}}
  • +
  • 姓氏: {{result_data.last_name}}
  • +
  • 旧工作: {{result_data.old_job}}
  • +
  • 当前工作: {{result_data.current_job}}
  • +
  • 国家: {{result_data.country}}
  • +
+ + +``` + +在现实世界中,我们不会在所有页面中重复HTML代码。而是创建一个布局并将其继承到其他文件中。让我们使用继承(模板)。现在,我们需要创建的不是三个不同的文件,而是一个名为layout.html的布局文件。然后其他文件将继承它。 + +### 创建布局 + +layout.html + +```html + + + + + + + + {% if title %} + 30天Python - {{ title}} + {% else %} + 30天Python + {% endif %} + + + +
+ +
+
+ {% block content %} {% endblock %} +
+ + +``` + +在上面的布局中,我们创建了一个可以被所有继承布局的页面使用的公共布局。在布局内部,我们可以看到导航链接。我们使用{% block content %}{% endblock %}标记以允许子模板添加内容。 + +home.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

欢迎回到{{name}}

+

+ 这个项目是通过使用以下技术构建的: + Flask, Python + and HTML CSS +

+
    + {% for tech in techs %} +
  • {{tech}}
  • + + {% endfor %} +
+
+ +{% endblock %} +``` + +about.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

关于{{name}}

+

+ 这个挑战是一个30天编程挑战,旨在帮助你学习Python编程语言,通过每天解决一个Python问题。 +

+
+{% endblock %} +``` + +post.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

{{name}}

+

{{path}}

+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +{% endblock %} +``` + +result.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

表单数据

+
    +
  • 第一名字: {{result_data.first_name}}
  • +
  • 姓氏: {{result_data.last_name}}
  • +
  • 旧工作: {{result_data.old_job}}
  • +
  • 当前工作: {{result_data.current_job}}
  • +
  • 国家: {{result_data.country}}
  • +
+
+ +{% endblock %} +``` + +#### 提供静态文件 + +以下是main.css文件,我们将把它放在static/css目录中: + +```css +/* === GENERAL === */ +body { + margin: 0; + padding: 0; + font-family: "Lato", sans-serif; + background-color: #f0f8ea; +} + +.container { + max-width: 80%; + margin: auto; + padding: 30px; +} + +ul { + list-style-type: none; + padding: 0; +} + +.tech { + color: #5bbc2e; +} + +/* === HEADER === */ +header { + background-color: #5bbc2e; +} + +.menu-container { + display: flex; + justify-content: space-between; + padding: 20px 30px; +} + +.brand-name { + color: white; + font-weight: 800; + font-size: 24px; +} + +.nav-lists { + display: flex; +} + +.nav-list { + margin-right: 15px; +} + +.nav-link { + text-decoration: none; + color: white; + font-weight: 300; +} + +/* === FORM === */ + +form { + margin: 30px 0; + border: 1px solid #ddd; + padding: 30px; + border-radius: 10px; +} + +form > div { + margin-bottom: 15px; +} + +input { + width: 100%; + padding: 10px; + border: 1px solid #ddd; + border-radius: 5px; + outline: 0; + font-size: 16px; + box-sizing: border-box; + margin-top: 5px; +} + +button { + padding: 12px 24px; + border: 0; + background-color: #5bbc2e; + color: white; + border-radius: 10px; + font-size: 16px; + outline: 0; + cursor: pointer; +} + +button:hover { + background-color: #4b9c25; +} +``` + +### 部署 + +#### 创建Heroku账户 + +Heroku提供了一个免费的托管服务。如果你想要部署一个应用程序,你应该有一个Heroku账户。 + +#### 登录Heroku + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku login +heroku: Press any key to open up the browser to login or q to exit: +Opening browser to https://cli-auth.heroku.com/auth/cli/browser/ec0972d5-d8c6-4adf-b004-a42a22dd09a8 +Logging in... done +Logged in as asabeneh@gmail.com +asabeneh@Asabeneh:~/Desktop/python_for_web$ +``` + +#### 创建requirements和Procfile + +在部署应用程序之前,我们需要告诉Heroku哪些依赖包需要安装,以及如何运行应用程序。Heroku使用requirements.txt文件获取应用程序依赖包的信息。使用pip freeze命令列出所有依赖包及其版本,并将其写入requirements.txt。 + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze +Click==7.0 +Flask==1.1.1 +itsdangerous==1.1.0 +Jinja2==2.10.3 +MarkupSafe==1.1.1 +Werkzeug==0.16.0 +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze > requirements.txt +``` + +Procfile告诉Heroku如何运行应用程序。在本例中,我们使用Gunicorn作为WSGI HTTP服务器,用于运行Python Web应用程序。我们需要将Gunicorn添加到我们的依赖包中。 + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install gunicorn +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze > requirements.txt +``` + +现在,让我们创建一个Procfile,并添加以下内容: + +```sh +web: gunicorn app:app +``` + +#### 将项目推送到Heroku + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku create 30-days-of-python-app +Creating ⬢ 30-days-of-python-app... done +https://30-days-of-python-app.herokuapp.com/ | https://git.heroku.com/30-days-of-python-app.git +asabeneh@Asabeneh:~/Desktop/python_for_web$ git init +Initialized empty Git repository in /home/asabeneh/Desktop/python_for_web/.git/ +asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku git:remote -a 30-days-of-python-app +set git remote heroku to https://git.heroku.com/30-days-of-python-app.git +asabeneh@Asabeneh:~/Desktop/python_for_web$ echo -e "venv\n.vscode" > .gitignore +asabeneh@Asabeneh:~/Desktop/python_for_web$ git add . +asabeneh@Asabeneh:~/Desktop/python_for_web$ git commit -m "first python web app" +[master (root-commit) 9dfcc6a] first python web app + 9 files changed, 403 insertions(+) + create mode 100644 .gitignore + create mode 100644 Procfile + create mode 100644 app.py + create mode 100644 requirements.txt + create mode 100644 static/css/main.css + create mode 100644 templates/about.html + create mode 100644 templates/home.html + create mode 100644 templates/layout.html + create mode 100644 templates/post.html + create mode 100644 templates/result.html +asabeneh@Asabeneh:~/Desktop/python_for_web$ git push heroku master +Enumerating objects: 14, done. +Counting objects: 100% (14/14), done. +Delta compression using up to 2 threads +Compressing objects: 100% (12/12), done. +Writing objects: 100% (14/14), 6.08 KiB | 1.52 MiB/s, done. +Total 14 (delta 2), reused 0 (delta 0) +remote: Compressing source files... done. +remote: Building source: +remote: +remote: -----> Python app detected +remote: -----> Installing python-3.6.10 +remote: -----> Installing pip +remote: -----> Installing dependencies with Pipenv 2018.5.18… +remote: Installing dependencies from Pipfile.lock (872ae5)… +remote: -----> Installing SQLite3 +remote: -----> $ python manage.py collectstatic --noinput +remote: Traceback (most recent call last): +remote: File "manage.py", line 10, in +remote: from app import app +remote: ModuleNotFoundError: No module named 'app' +remote: +remote: ! Error while running '$ python manage.py collectstatic --noinput'. +remote: See traceback above for details. +remote: +remote: You may need to update application code to resolve this error. +remote: Or, you can disable collectstatic for this application: +remote: +remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 +remote: +remote: https://devcenter.heroku.com/articles/django-assets +remote: -----> Discovering process types +remote: Procfile declares types -> web +remote: +remote: -----> Compressing... +remote: Done: 55.7M +remote: -----> Launching... +remote: Released v3 +remote: https://30-days-of-python-app.herokuapp.com/ deployed to Heroku +remote: +remote: Verifying deploy... done. +To https://git.heroku.com/30-days-of-python-app.git + * [new branch] master -> master +asabeneh@Asabeneh:~/Desktop/python_for_web$ +``` + +如你所见,我们已经成功地创建了第一个网络应用程序、对其进行部署,并将其托管在Heroku上。您可以使用此[链接](https://30-days-of-python-app.herokuapp.com/)尝试本应用程序。 + +事不宜迟,让我们做一些练习,巩固所学到的知识。 + +## 练习:第26天 + +1. 创建一个名为"成绩计算器"的Flask应用程序。用户可以输入他们的分数、科目名称,然后应用程序应根据分数显示不同的消息: + - 如果分数≥90,显示"优秀!你的[科目]成绩是[分数]"。 + - 如果80≤分数<90,显示"很好!你的[科目]成绩是[分数]"。 + - 如果70≤分数<80,显示"一般!你的[科目]成绩是[分数]"。 + - 如果60≤分数<70,显示"及格!你的[科目]成绩是[分数]"。 + - 如果分数<60,显示"你需要更加努力!你的[科目]成绩是[分数]"。 + +2. 创建一个"体重指数计算器"应用程序,计算体重指数(BMI),公式为体重(kg)/(身高(m)²)。根据BMI值显示不同的健康状态: + - BMI<18.5:"体重过轻" + - 18.5≤BMI<24.9:"健康体重" + - 25≤BMI<29.9:"超重" + - BMI≥30:"肥胖" + +3. 创建一个博客应用程序,用户可以添加、编辑和删除博客文章。 + +4. 创建一个"任务管理器"应用程序,用户可以添加、查看和删除任务。 + +🎉 恭喜!🎉 + +[<< 第25天](../25_Day_Pandas/25_pandas_cn.md) | [第27天 >>](../27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) \ No newline at end of file diff --git a/Chinese/27_python_with_mongodb_cn.md b/Chinese/27_python_with_mongodb_cn.md new file mode 100644 index 000000000..2bf2f0f39 --- /dev/null +++ b/Chinese/27_python_with_mongodb_cn.md @@ -0,0 +1,632 @@ +# 30天Python编程挑战:第27天 - Python与MongoDB + +- [第27天](#-第27天) +- [Python与MongoDB](#python与mongodb) + - [MongoDB](#mongodb) + - [SQL与NoSQL的比较](#sql与nosql的比较) + - [获取连接字符串(MongoDB URI)](#获取连接字符串mongodb-uri) + - [将Flask应用程序连接到MongoDB集群](#将flask应用程序连接到mongodb集群) + - [创建数据库和集合](#创建数据库和集合) + - [向集合中插入多个文档](#向集合中插入多个文档) + - [MongoDB查找](#mongodb查找) + - [使用查询进行查找](#使用查询进行查找) + - [使用修饰符的查询查找](#使用修饰符的查询查找) + - [限制文档数量](#限制文档数量) + - [使用排序进行查找](#使用排序进行查找) + - [使用查询进行更新](#使用查询进行更新) + - [删除文档](#删除文档) + - [删除集合](#删除集合) + - [💻 练习:第27天](#-练习第27天) + +# 📘 第27天 + +# Python与MongoDB + +Python是一种后端技术,可以与不同的数据库应用程序连接。它可以连接到SQL和NoSQL数据库。在本节中,我们将Python与MongoDB数据库连接,MongoDB是一种NoSQL数据库。 + +## MongoDB + +MongoDB是一种NoSQL数据库。MongoDB以类似JSON的文档形式存储数据,这使得MongoDB非常灵活和可扩展。让我们看看SQL和NoSQL数据库的不同术语。下表将展示SQL与NoSQL数据库之间的区别。 + +### SQL与NoSQL的比较 + +![SQL与NoSQL](../images/mongoDB/sql-vs-nosql.png) + +在本节中,我们将重点关注NoSQL数据库MongoDB。通过点击注册按钮,然后在下一页点击注册,让我们在[mongoDB](https://www.mongodb.com/)上注册。 + +![MongoDB注册页面](../images/mongoDB/mongodb-signup-page.png) + +完成表格并点击继续 + +![MongoDB注册](../images/mongoDB/mongodb-register.png) + +选择免费计划 + +![MongoDB免费计划](../images/mongoDB/mongodb-free.png) + +选择最近的免费区域,并为你的集群命名。 + +![MongoDB集群名称](../images/mongoDB/mongodb-cluster-name.png) + +现在,一个免费的沙箱已创建 + +![MongoDB沙箱](../images/mongoDB/mongodb-sandbox.png) + +允许所有本地主机访问 + +![MongoDB允许IP访问](../images/mongoDB/mongodb-allow-ip-access.png) + +添加用户和密码 + +![MongoDB添加用户](../images/mongoDB/mongodb-add-user.png) + +创建MongoDB URI链接 + +![MongoDB创建URI](../images/mongoDB/mongodb-create-uri.png) + +选择Python 3.6或更高版本的驱动程序 + +![MongoDB Python驱动程序](../images/mongoDB/mongodb-python-driver.png) + +### 获取连接字符串(MongoDB URI) + +复制连接字符串链接,你将获得类似这样的内容: + +```sh +mongodb+srv://asabeneh:@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority +``` + +不要担心这个URL,它是连接你的应用程序与mongoDB的一种方式。 +让我们用你添加用户时使用的密码替换密码占位符。 + +**示例:** + +```sh +mongodb+srv://asabeneh:123123123@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority +``` + +现在,我已经替换了所有内容,密码是123123123,数据库名称是*thirty_days_python*。这只是一个示例,你的密码必须比示例密码更强。 + +Python需要mongoDB驱动程序才能访问mongoDB数据库。我们将使用_pymongo_和_dnspython_来连接我们的应用程序与mongoDB基础。在你的项目目录中安装pymongo和dnspython。 + +```sh +pip install pymongo dnspython +``` + +要使用mongodb+srv://URI,必须安装"dnspython"模块。dnspython是用于Python的DNS工具包。它支持几乎所有记录类型。 + +### 将Flask应用程序连接到MongoDB集群 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +print(client.list_database_names()) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +当我们运行上面的代码时,我们会得到默认的mongoDB数据库。 + +```sh +['admin', 'local'] +``` + +### 创建数据库和集合 + +让我们创建一个数据库,如果数据库和集合在mongoDB中不存在,它们将被创建。让我们创建一个名为*thirty_days_of_python*的数据库和*students*集合。 + +创建数据库的方法: + +```sh +db = client.name_of_databse # 我们可以这样创建数据库,或者使用第二种方式 +db = client['name_of_database'] +``` + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +# 创建数据库 +db = client.thirty_days_of_python +# 创建students集合并插入文档 +db.students.insert_one({'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}) +print(client.list_database_names()) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +在创建数据库后,我们还创建了一个students集合,并使用*insert_one()*方法插入了一个文档。 +现在,数据库*thirty_days_of_python*和*students*集合已经创建,并且文档已经插入。 +检查你的mongoDB集群,你将看到数据库和集合。在集合内部,将有一个文档。 + +```sh +['thirty_days_of_python', 'admin', 'local'] +``` + +如果你在mongoDB集群上看到这个,这意味着你已经成功创建了一个数据库和一个集合。 + +![创建数据库和集合](../images/mongoDB/mongodb-creating_database.png) + +如果你看到上图,文档已经创建,并带有一个长ID作为主键。每次我们创建一个文档,mongoDB都会为它创建一个唯一的ID。 + +### 向集合中插入多个文档 + +*insert_one()*方法一次插入一个项目,如果我们想一次插入多个文档,我们可以使用*insert_many()*方法或for循环。 +我们可以使用for循环一次插入多个文档。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) + +students = [ + {'name':'David','country':'UK','city':'London','age':34}, + {'name':'John','country':'Sweden','city':'Stockholm','age':28}, + {'name':'Sami','country':'Finland','city':'Helsinki','age':25}, + ] +for student in students: + db.students.insert_one(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +### MongoDB查找 + +*find()*和*findOne()*方法是在mongoDB数据库集合中查找数据的常用方法。它类似于MySQL数据库中的SELECT语句。 +让我们使用_find_one()_方法来获取数据库集合中的一个文档。 + +- \*find_one({"\_id": ObjectId("id"}): 如果没有提供id,则获取第一次出现的文档 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +student = db.students.find_one() +print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Helsinki', 'city': 'Helsinki', 'age': 250} +``` + +上面的查询返回第一个条目,但我们可以使用特定的\_id来定位特定的文档。让我们做一个例子,使用David的id来获取David对象。 +'\_id':ObjectId('5df68a23f106fe2d315bbc8c') + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +from bson.objectid import ObjectId # id对象 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +student = db.students.find_one({'_id':ObjectId('5df68a23f106fe2d315bbc8c')}) +print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +``` + +我们已经看到如何使用上面的例子来使用_find_one()_。让我们进一步了解_find()_ + +- _find()_: 如果我们不传递查询对象,返回集合中的所有出现。该对象是pymongo.cursor对象。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +students = db.students.find() +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +我们可以通过在_find({}, {})_中传递第二个对象来指定要返回的字段。0表示不包含,1表示包含,但我们不能混合使用0和1,除了\_id。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +students = db.students.find({}, {"_id":0, "name": 1, "country":1}) # 0表示不包含,1表示包含 +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'name': 'Asabeneh', 'country': 'Finland'} +{'name': 'David', 'country': 'UK'} +{'name': 'John', 'country': 'Sweden'} +{'name': 'Sami', 'country': 'Finland'} +``` + +### 使用查询进行查找 + +在mongoDB中,find接受一个查询对象。我们可以传递一个查询对象,我们可以过滤我们想要过滤的文档。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = { + "country":"Finland" +} +students = db.students.find(query) + +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +带有修饰符的查询 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = { + "city":"Helsinki" +} +students = db.students.find(query) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +### 使用修饰符的查询查找 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +query = { + "country":"Finland", + "city":"Helsinki" +} +students = db.students.find(query) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +带有修饰符的查询 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +query = {"age":{"$gt":30}} +students = db.students.find(query) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +``` + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +query = {"age":{"$lt":30}} +students = db.students.find(query) +for student in students: + print(student) +``` + +```sh +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +### 限制文档数量 + +我们可以使用_limit()_方法来限制我们返回的文档数量。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +db.students.find().limit(3) +``` + +### 使用排序进行查找 + +默认情况下,排序是升序的。我们可以通过添加-1参数将排序更改为降序。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +students = db.students.find().sort('name') +for student in students: + print(student) + +students = db.students.find().sort('name',-1) +for student in students: + print(student) + +students = db.students.find().sort('age') +for student in students: + print(student) + +students = db.students.find().sort('age',-1) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +升序 + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +降序 + +```sh +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +``` + +### 使用查询进行更新 + +我们将使用*update_one()*方法来更新一个项目。它接受两个对象,一个是查询,另一个是新对象。 +第一个人,Asabeneh得到了一个非常不合理的年龄。让我们更新Asabeneh的年龄。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = {'age':250} +new_value = {'$set':{'age':38}} + +db.students.update_one(query, new_value) +# 让我们检查结果,看看年龄是否被修改 +for student in db.students.find(): + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +当我们想要一次更新多个文档时,我们使用*upate_many()*方法。 + +### 删除文档 + +方法*delete_one()*删除一个文档。*delete_one()*方法接受一个查询对象参数。它只删除第一次出现的文档。 +让我们从集合中删除一个John。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = {'name':'John'} +db.students.delete_one(query) + +for student in db.students.find(): + print(student) +# 让我们检查结果,看看年龄是否被修改 +for student in db.students.find(): + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +如你所见,John已经从集合中删除。 + +当我们想要删除多个文档时,我们使用*delete_many()*方法,它接受一个查询对象。如果我们将一个空的查询对象传递给*delete_many({})*,它将删除集合中的所有文档。 + +### 删除集合 + +使用_drop()_方法,我们可以从数据库中删除一个集合。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +db.students.drop() +``` + +现在,我们已经从数据库中删除了students集合。 + +## 💻 练习:第27天 + +🎉 恭喜!🎉 + +[<< 第26天](../26_Day_Python_web/26_python_web_cn.md) | [第28天 >>](../28_Day_API/28_API_cn.md) \ No newline at end of file diff --git a/Chinese/28_API_cn.md b/Chinese/28_API_cn.md new file mode 100644 index 000000000..4ed2d183b --- /dev/null +++ b/Chinese/28_API_cn.md @@ -0,0 +1,143 @@ +# 30天Python编程挑战:第28天 - API + +- [第28天](#-第28天) +- [应用程序编程接口(API)](#应用程序编程接口api) + - [API](#api) + - [构建API](#构建api) + - [HTTP(超文本传输协议)](#http超文本传输协议) + - [HTTP的结构](#http的结构) + - [初始请求行(状态行)](#初始请求行状态行) + - [初始响应行(状态行)](#初始响应行状态行) + - [头字段](#头字段) + - [消息体](#消息体) + - [请求方法](#请求方法) + - [💻 练习:第28天](#-练习第28天) + +# 📘 第28天 + +# 应用程序编程接口(API) + +## API + +API是应用程序编程接口(Application Programming Interface)的缩写。我们在本节中将介绍的API类型是Web API。 +Web API是定义好的接口,通过这些接口在企业和使用其资产的应用程序之间进行交互,这也是一种服务级别协议(SLA),用于指定功能提供者并为其API用户公开服务路径或URL。 + +在Web开发的上下文中,API被定义为一组规范,如超文本传输协议(HTTP)请求消息,以及响应消息结构的定义,通常采用XML或JavaScript对象表示法(JSON)格式。 + +Web API已经从基于简单对象访问协议(SOAP)的Web服务和面向服务的架构(SOA)转向更直接的表征状态转移(REST)风格的Web资源。 + +社交媒体服务和Web API已经允许Web社区在社区和不同平台之间共享内容和数据。 + +使用API,在一个地方创建的内容可以动态地在Web上的多个位置发布和更新。 + +例如,Twitter的REST API允许开发人员访问核心Twitter数据,而搜索API提供了开发人员与Twitter搜索和趋势数据互动的方法。 + +许多应用程序提供API端点。一些API的例子,如国家[API](https://restcountries.eu/rest/v2/all),[猫品种API](https://api.thecatapi.com/v1/breeds)。 + +在本节中,我们将介绍一个RESTful API,它使用HTTP请求方法来GET、PUT、POST和DELETE数据。 + +## 构建API + +RESTful API是一种应用程序编程接口(API),使用HTTP请求来GET、PUT、POST和DELETE数据。在前几节中,我们学习了Python、Flask和MongoDB。我们将利用我们获得的知识,使用Python Flask和MongoDB数据库开发一个RESTful API。每个具有CRUD(创建、读取、更新、删除)操作的应用程序都有一个API,用于从数据库创建数据、获取数据、更新数据或删除数据。 + +要构建API,了解HTTP协议和HTTP请求、响应周期是很好的。 + +## HTTP(超文本传输协议) + +HTTP是客户端和服务器之间建立的通信协议。在这种情况下,客户端是浏览器,服务器是你访问数据的地方。HTTP是一种网络协议,用于传递资源,这些资源可以是万维网上的文件,无论是HTML文件、图像文件、查询结果、脚本或其他文件类型。 + +浏览器是HTTP客户端,因为它向HTTP服务器(Web服务器)发送请求,而HTTP服务器再向客户端发送响应。 + +## HTTP的结构 + +HTTP使用客户端-服务器模型。HTTP客户端打开一个连接并向HTTP服务器发送请求消息,HTTP服务器返回响应消息,即请求的资源。当请求响应周期完成时,服务器关闭连接。 + +![HTTP请求响应周期](../images/http_request_response_cycle.png) + +请求和响应消息的格式类似。两种消息都有 + +- 一个初始行 +- 零个或多个头行 +- 一个空行(即单独的CRLF) +- 一个可选的消息体(例如文件、查询数据或查询输出) + +让我们通过导航此站点来看一个请求和响应消息的示例:https://thirtydaysofpython-v1-final.herokuapp.com/ 。这个网站已部署在Heroku免费dyno上,在某些月份可能由于高请求量而无法工作。支持这项工作可以让服务器始终运行。 + +![请求和响应头](../images/request_response_header.png) + +## 初始请求行(状态行) + +初始请求行与响应不同。 +请求行有三个部分,用空格分隔: + +- 方法名(GET、POST、HEAD) +- 请求资源的路径 +- 使用的HTTP版本。例如 GET / HTTP/1.1 + +GET是最常见的HTTP方法,用于获取或读取资源,而POST是常见的请求方法,用于创建资源。 + +### 初始响应行(状态行) + +初始响应行,称为状态行,也有三个用空格分隔的部分: + +- HTTP版本 +- 响应状态码,给出请求的结果,以及描述状态码的原因。状态行的例子有: + HTTP/1.0 200 OK + 或者 + HTTP/1.0 404 Not Found + 注意: + +最常见的状态码是: +200 OK:请求成功,并且生成的资源(例如文件或脚本输出)在消息体中返回。 +500 服务器错误 +完整的HTTP状态码列表可以在[这里](https://httpstatuses.com/)找到。也可以在[这里](https://httpstatusdogs.com/)找到。 + +### 头字段 + +正如你在上面的截图中看到的,头行提供了有关请求或响应的信息,或者有关在消息体中发送的对象的信息。 + +```sh +GET / HTTP/1.1 +Host: thirtydaysofpython-v1-final.herokuapp.com +Connection: keep-alive +Pragma: no-cache +Cache-Control: no-cache +Upgrade-Insecure-Requests: 1 +User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36 +Sec-Fetch-User: ?1 +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 +Sec-Fetch-Site: same-origin +Sec-Fetch-Mode: navigate +Referer: https://thirtydaysofpython-v1-final.herokuapp.com/post +Accept-Encoding: gzip, deflate, br +Accept-Language: en-GB,en;q=0.9,fi-FI;q=0.8,fi;q=0.7,en-CA;q=0.6,en-US;q=0.5,fr;q=0.4 +``` + +### 消息体 + +HTTP消息可能在头行之后发送数据体。在响应中,这是请求的资源返回给客户端的地方(消息体最常用的用途),或者如果出现错误,这里可能是解释性文本。在请求中,这是用户输入的数据或上传的文件发送到服务器的地方。 + +如果HTTP消息包含一个消息体,通常在消息中有描述该消息体的头行。特别是: + +Content-Type: 头给出消息体中数据的MIME类型(text/html,application/json,text/plain,text/css,image/gif)。 +Content-Length: 头给出消息体中的字节数。 + +### 请求方法 + +GET、POST、PUT和DELETE是我们将实现API或CRUD操作应用程序的HTTP请求方法。 + +1. GET:GET方法用于使用给定的URI从给定服务器检索和获取信息。使用GET的请求应该只检索数据,而不应该对数据有任何其他影响。 + +2. POST:POST请求用于创建数据并将数据发送到服务器,例如使用HTML表单创建新帖子、上传文件等。 + +3. PUT:用上传的内容替换目标资源的所有当前表示,我们使用它来修改或更新数据。 + +4. DELETE:删除数据 + +## 💻 练习:第28天 + +1. 阅读有关API和HTTP的资料 + +🎉 恭喜!🎉 + +[<< 第27天](../27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) | [第29天 >>](../29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file diff --git a/Chinese/29_building_API_cn.md b/Chinese/29_building_API_cn.md new file mode 100644 index 000000000..704a8dc36 --- /dev/null +++ b/Chinese/29_building_API_cn.md @@ -0,0 +1,460 @@ +# 30天Python编程挑战:第29天 - 构建API + +- [第29天](#第29天) +- [构建API](#构建api) + - [API的结构](#api的结构) + - [使用GET获取数据](#使用get获取数据) + - [通过ID获取文档](#通过id获取文档) + - [使用POST创建数据](#使用post创建数据) + - [使用PUT更新](#使用put更新) + - [使用Delete删除文档](#使用delete删除文档) +- [💻 练习:第29天](#-练习第29天) + +## 第29天 + +## 构建API + +在本节中,我们将介绍一个RESTful API,它使用HTTP请求方法来GET、PUT、POST和DELETE数据。 + +RESTful API是一种应用程序编程接口(API),使用HTTP请求来GET、PUT、POST和DELETE数据。在前几节中,我们学习了Python、Flask和MongoDB。我们将利用我们获得的知识,使用Python Flask和MongoDB开发一个RESTful API。每个具有CRUD(创建、读取、更新、删除)操作的应用程序都有一个API,用于从数据库创建数据、获取数据、更新数据或删除数据。 + +浏览器只能处理GET请求。因此,我们必须有一个工具,可以帮助我们处理所有请求方法(GET、POST、PUT、DELETE)。 + +API示例: + +- 国家API:https://restcountries.eu/rest/v2/all +- 猫品种API:https://api.thecatapi.com/v1/breeds + +[Postman](https://www.getpostman.com/)是API开发领域非常流行的工具。所以,如果你想完成本节内容,你需要[下载Postman](https://www.getpostman.com/)。Postman的替代品是[Insomnia](https://insomnia.rest/download)。 + +![Postman](../images/postman.png) + +### API的结构 + +API端点是一个可以帮助检索、创建、更新或删除资源的URL。结构如下所示: +示例: +https://api.twitter.com/1.1/lists/members.json +返回指定列表的成员。只有当经过身份验证的用户拥有指定列表时,才会显示私人列表成员。 +公司名称后跟版本,然后是API的目的。 +方法: +HTTP方法和URL + +API使用以下HTTP方法进行对象操作: + +```sh +GET 用于对象检索 +POST 用于对象创建和对象操作 +PUT 用于对象更新 +DELETE 用于对象删除 +``` + +让我们构建一个收集关于30DaysOfPython学生信息的API。我们将收集姓名、国家、城市、出生日期、技能和个人简介。 + +为了实现这个API,我们将使用: + +- Postman +- Python +- Flask +- MongoDB + +### 使用GET获取数据 + +在这一步中,让我们使用虚拟数据并将其作为json返回。为了将其作为json返回,我们将使用json模块和Response模块。 + +```py +# 导入flask + +from flask import Flask, Response +import json + +app = Flask(__name__) + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + student_list = [ + { + 'name':'Asabeneh', + 'country':'Finland', + 'city':'Helsinki', + 'skills':['HTML', 'CSS','JavaScript','Python'] + }, + { + 'name':'David', + 'country':'UK', + 'city':'London', + 'skills':['Python','MongoDB'] + }, + { + 'name':'John', + 'country':'Sweden', + 'city':'Stockholm', + 'skills':['Java','C#'] + } + ] + return Response(json.dumps(student_list), mimetype='application/json') + + +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +当你在浏览器上请求http://localhost:5000/api/v1.0/students URL时,你将获得以下内容: + +![在浏览器上的GET](../images/get_on_browser.png) + +当你在Postman上请求http://localhost:5000/api/v1.0/students URL时,你将获得以下内容: + +![在Postman上的GET](../images/get_on_postman.png) + +我们不再显示虚拟数据,而是将Flask应用程序与MongoDB连接,并从MongoDB数据库获取数据。 + +```py +# 导入flask + +from flask import Flask, Response +import json +import pymongo + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') + + +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +通过连接Flask,我们可以从thirty_days_of_python数据库中获取学生集合数据。 + +```sh +[ + { + "_id": { + "$oid": "5df68a21f106fe2d315bbc8b" + }, + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "age": 38 + }, + { + "_id": { + "$oid": "5df68a23f106fe2d315bbc8c" + }, + "name": "David", + "country": "UK", + "city": "London", + "age": 34 + }, + { + "_id": { + "$oid": "5df68a23f106fe2d315bbc8e" + }, + "name": "Sami", + "country": "Finland", + "city": "Helsinki", + "age": 25 + } +] +``` + +### 通过ID获取文档 + +我们可以使用ID访问单个文档,让我们使用ID访问Asabeneh。 +http://localhost:5000/api/v1.0/students/5df68a21f106fe2d315bbc8b + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') + +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +[ + { + "_id": { + "$oid": "5df68a21f106fe2d315bbc8b" + }, + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "age": 38 + } +] +``` + +### 使用POST创建数据 + +我们使用POST请求方法创建数据 + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo +from datetime import datetime + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students', methods = ['POST']) +def create_student (): + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.insert_one(student) + return ; +def update_student (id): +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +### 使用PUT更新 + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo +from datetime import datetime + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students', methods = ['POST']) +def create_student (): + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.insert_one(student) + return +@app.route('/api/v1.0/students/', methods = ['PUT']) # 这个装饰器创建主页路由 +def update_student (id): + query = {"_id":ObjectId(id)} + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.update_one(query, student) + # return Response(dumps({"result":"a new student has been created"}), mimetype='application/json') + return +def update_student (id): +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +### 使用Delete删除文档 + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo +from datetime import datetime + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students', methods = ['POST']) +def create_student (): + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.insert_one(student) + return +@app.route('/api/v1.0/students/', methods = ['PUT']) # 这个装饰器创建主页路由 +def update_student (id): + query = {"_id":ObjectId(id)} + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.update_one(query, student) + # return Response(dumps({"result":"a new student has been created"}), mimetype='application/json') + return ; +@app.route('/api/v1.0/students/', methods = ['DELETE']) +def delete_student (id): + db.students.delete_one({"_id":ObjectId(id)}) + return +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +## 💻 练习:第29天 + +1. 实现上述示例并开发[这个](https://thirtydayofpython-api.herokuapp.com/) + +🎉 恭喜!🎉 + +[<< 第28天](../28_Day_API/28_API_cn.md) | [第30天 >>](../30_Day_Conclusions/30_conclusions_cn.md) \ No newline at end of file diff --git a/Chinese/30_conclusions_cn.md b/Chinese/30_conclusions_cn.md new file mode 100644 index 000000000..25f26b309 --- /dev/null +++ b/Chinese/30_conclusions_cn.md @@ -0,0 +1,22 @@ +# 30天Python编程挑战:第30天 - 总结 + +- [第30天](#第30天) + - [总结](#总结) + - [感言](#感言) + +# 第30天 + +## 总结 + +在准备这些材料的过程中,我学到了很多,你们也激励我做得更多。恭喜你达到这个水平。如果你完成了所有的练习和项目,现在你有能力走向数据分析、数据科学、机器学习或网络开发的道路。[支持作者提供更多教育材料](https://www.paypal.com/paypalme/asabeneh)。 + +## 感言 + +现在是时候表达你对作者和30天Python挑战的想法了。你可以在这个[链接](https://www.asabeneh.com/testimonials)上留下你的感言。 + +提供反馈: +http://thirtydayofpython-api.herokuapp.com/feedback + +🎉 恭喜!🎉 + +[<< 第29天](../29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file From 59675e027b87cd76808143ebedbdf340250ead81 Mon Sep 17 00:00:00 2001 From: hoshino <19860620884@163.com> Date: Wed, 19 Mar 2025 19:52:03 +0800 Subject: [PATCH 50/63] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E4=BA=86=E8=B7=B3?= =?UTF-8?q?=E8=BD=AC=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Chinese/15_python_type_errors_cn.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Chinese/15_python_type_errors_cn.md b/Chinese/15_python_type_errors_cn.md index 13c9cc87f..9e709144f 100644 --- a/Chinese/15_python_type_errors_cn.md +++ b/Chinese/15_python_type_errors_cn.md @@ -341,4 +341,4 @@ ZeroDivisionError: division by zero 🎉 恭喜!🎉 -[<< 第14天](../14_Day_Higher_order_functions/14_higher_order_functions_cn.md) | [第16天 >>](../16_Day_Python_date_time/16_python_datetime_cn.md) \ No newline at end of file +[<< 第14天](14_higher_order_functions.md) | [第16天 >>](16_python_datetime_cn.md) \ No newline at end of file From 929319725378dbabd209fdf60ee83df42731469d Mon Sep 17 00:00:00 2001 From: hoshino <19860620884@163.com> Date: Wed, 19 Mar 2025 21:15:14 +0800 Subject: [PATCH 51/63] =?UTF-8?q?=E6=9B=B4=E6=94=B9=E4=BA=86=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E7=9A=84=E5=BC=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Chinese/15_python_type_errors_cn.md | 2 +- Chinese/16_python_datetime_cn.md | 2 +- Chinese/17_exception_handling_cn.md | 2 +- Chinese/18_regular_expressions_cn.md | 2 +- Chinese/19_file_handling_cn.md | 2 +- Chinese/20_python_package_manager_cn.md | 2 +- Chinese/21_classes_and_objects_cn.md | 2 +- Chinese/22_web_scraping_cn.md | 2 +- Chinese/23_virtual_environment_cn.md | 2 +- Chinese/24_statistics_cn.md | 2 +- Chinese/25_pandas_cn.md | 2 +- Chinese/26_python_web_cn.md | 2 +- Chinese/27_python_with_mongodb_cn.md | 2 +- Chinese/28_API_cn.md | 2 +- Chinese/29_building_API_cn.md | 2 +- Chinese/30_conclusions_cn.md | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Chinese/15_python_type_errors_cn.md b/Chinese/15_python_type_errors_cn.md index 9e709144f..6b6f46ebd 100644 --- a/Chinese/15_python_type_errors_cn.md +++ b/Chinese/15_python_type_errors_cn.md @@ -341,4 +341,4 @@ ZeroDivisionError: division by zero 🎉 恭喜!🎉 -[<< 第14天](14_higher_order_functions.md) | [第16天 >>](16_python_datetime_cn.md) \ No newline at end of file +[<< 第14天](./14_higher_order_functions.md) | [第16天 >>](./16_python_datetime_cn.md) \ No newline at end of file diff --git a/Chinese/16_python_datetime_cn.md b/Chinese/16_python_datetime_cn.md index c833d4210..6c9aae0c7 100644 --- a/Chinese/16_python_datetime_cn.md +++ b/Chinese/16_python_datetime_cn.md @@ -189,4 +189,4 @@ t3 = 86 days, 22:56:50 🎉 恭喜!🎉 -[<< 第15天](../15_Day_Python_type_errors/15_python_type_errors_cn.md) | [第17天 >>](../17_Day_Exception_handling/17_exception_handling_cn.md) \ No newline at end of file +[<< 第15天](./15_Day_Python_type_errors/15_python_type_errors_cn.md) | [第17天 >>](./17_Day_Exception_handling/17_exception_handling_cn.md) \ No newline at end of file diff --git a/Chinese/17_exception_handling_cn.md b/Chinese/17_exception_handling_cn.md index 9fab14e9f..4542c7f11 100644 --- a/Chinese/17_exception_handling_cn.md +++ b/Chinese/17_exception_handling_cn.md @@ -282,4 +282,4 @@ print(fruits_and_veges) 🎉 恭喜!🎉 -[<< 第16天](../16_Day_Python_date_time/16_python_datetime_cn.md) | [第18天 >>](../18_Day_Regular_expressions/18_regular_expressions_cn.md) \ No newline at end of file +[<< 第16天](./16_Day_Python_date_time/16_python_datetime_cn.md) | [第18天 >>](./18_Day_Regular_expressions/18_regular_expressions_cn.md) \ No newline at end of file diff --git a/Chinese/18_regular_expressions_cn.md b/Chinese/18_regular_expressions_cn.md index c9987be10..d7d0ee55b 100644 --- a/Chinese/18_regular_expressions_cn.md +++ b/Chinese/18_regular_expressions_cn.md @@ -414,4 +414,4 @@ alex@yahoo 🎉 恭喜!🎉 -[<< 第17天](../17_Day_Exception_handling/17_exception_handling_cn.md) | [第19天 >>](../19_Day_File_handling/19_file_handling_cn.md) \ No newline at end of file +[<< 第17天](./17_Day_Exception_handling/17_exception_handling_cn.md) | [第19天 >>](./19_Day_File_handling/19_file_handling_cn.md) \ No newline at end of file diff --git a/Chinese/19_file_handling_cn.md b/Chinese/19_file_handling_cn.md index 3c8e147e6..4c15062b6 100644 --- a/Chinese/19_file_handling_cn.md +++ b/Chinese/19_file_handling_cn.md @@ -546,4 +546,4 @@ Python 🎉 恭喜!🎉 -[<< 第18天](../18_Day_Regular_expressions/18_regular_expressions_cn.md) | [第20天 >>](../20_Day_Python_package_manager/20_python_package_manager_cn.md) \ No newline at end of file +[<< 第18天](./18_Day_Regular_expressions/18_regular_expressions_cn.md) | [第20天 >>](./20_Day_Python_package_manager/20_python_package_manager_cn.md) \ No newline at end of file diff --git a/Chinese/20_python_package_manager_cn.md b/Chinese/20_python_package_manager_cn.md index a2c9bafaf..a0fd023b8 100644 --- a/Chinese/20_python_package_manager_cn.md +++ b/Chinese/20_python_package_manager_cn.md @@ -349,4 +349,4 @@ print(greet.greet_person('张', '三')) 🎉 恭喜!🎉 -[<< 第19天](../19_Day_File_handling/19_file_handling_cn.md) | [第21天 >>](../21_Day_Classes_and_objects/21_classes_and_objects_cn.md) \ No newline at end of file +[<< 第19天](./19_Day_File_handling/19_file_handling_cn.md) | [第21天 >>](./21_Day_Classes_and_objects/21_classes_and_objects_cn.md) \ No newline at end of file diff --git a/Chinese/21_classes_and_objects_cn.md b/Chinese/21_classes_and_objects_cn.md index 8bc5d2ef6..5e09256aa 100644 --- a/Chinese/21_classes_and_objects_cn.md +++ b/Chinese/21_classes_and_objects_cn.md @@ -416,4 +416,4 @@ juice: orange 🎉 恭喜!🎉 -[<< 第20天](../20_Day_Python_package_manager/20_python_package_manager_cn.md) | [第22天 >>](../22_Day_Web_scraping/22_web_scraping_cn.md) \ No newline at end of file +[<< 第20天](./20_Day_Python_package_manager/20_python_package_manager_cn.md) | [第22天 >>](./22_Day_Web_scraping/22_web_scraping_cn.md) \ No newline at end of file diff --git a/Chinese/22_web_scraping_cn.md b/Chinese/22_web_scraping_cn.md index ea1597371..0d4c2721f 100644 --- a/Chinese/22_web_scraping_cn.md +++ b/Chinese/22_web_scraping_cn.md @@ -86,4 +86,4 @@ for td in table.find('tr').find_all('td'): 🎉 恭喜!🎉 -[<< 第21天](../21_Day_Classes_and_objects/21_classes_and_objects_cn.md) | [第23天 >>](../23_Day_Virtual_environment/23_virtual_environment_cn.md) \ No newline at end of file +[<< 第21天](./21_Day_Classes_and_objects/21_classes_and_objects_cn.md) | [第23天 >>](./23_Day_Virtual_environment/23_virtual_environment_cn.md) \ No newline at end of file diff --git a/Chinese/23_virtual_environment_cn.md b/Chinese/23_virtual_environment_cn.md index c233a8783..a93dd34db 100644 --- a/Chinese/23_virtual_environment_cn.md +++ b/Chinese/23_virtual_environment_cn.md @@ -94,4 +94,4 @@ Werkzeug==0.16.0 🎉 恭喜!🎉 -[<< 第22天](../22_Day_Web_scraping/22_web_scraping_cn.md) | [第24天 >>](../24_Day_Statistics/24_statistics_cn.md) \ No newline at end of file +[<< 第22天](./22_Day_Web_scraping/22_web_scraping_cn.md) | [第24天 >>](./24_Day_Statistics/24_statistics_cn.md) \ No newline at end of file diff --git a/Chinese/24_statistics_cn.md b/Chinese/24_statistics_cn.md index 7a54dcfad..982216e3a 100644 --- a/Chinese/24_statistics_cn.md +++ b/Chinese/24_statistics_cn.md @@ -586,4 +586,4 @@ print('平均值:', numpy_array_from_list.mean()) 🎉 恭喜!🎉 -[<< 第23天](../23_Day_Virtual_environment/23_virtual_environment_cn.md) | [第25天 >>](../25_Day_Pandas/25_pandas_cn.md) \ No newline at end of file +[<< 第23天](./23_Day_Virtual_environment/23_virtual_environment_cn.md) | [第25天 >>](./25_Day_Pandas/25_pandas_cn.md) \ No newline at end of file diff --git a/Chinese/25_pandas_cn.md b/Chinese/25_pandas_cn.md index c7aa8a017..f8abe23b8 100644 --- a/Chinese/25_pandas_cn.md +++ b/Chinese/25_pandas_cn.md @@ -548,4 +548,4 @@ print(df[(df['age'] > 20) & (df['在职'] == True)]) 🎉 恭喜!🎉 -[<< 第24天](../24_Day_Statistics/24_statistics_cn.md) | [第26天 >>](../26_Day_Python_web/26_python_web_cn.md) \ No newline at end of file +[<< 第24天](./24_Day_Statistics/24_statistics_cn.md) | [第26天 >>](./26_Day_Python_web/26_python_web_cn.md) \ No newline at end of file diff --git a/Chinese/26_python_web_cn.md b/Chinese/26_python_web_cn.md index 8d5989c45..63bbdab18 100644 --- a/Chinese/26_python_web_cn.md +++ b/Chinese/26_python_web_cn.md @@ -814,4 +814,4 @@ asabeneh@Asabeneh:~/Desktop/python_for_web$ 🎉 恭喜!🎉 -[<< 第25天](../25_Day_Pandas/25_pandas_cn.md) | [第27天 >>](../27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) \ No newline at end of file +[<< 第25天](./25_Day_Pandas/25_pandas_cn.md) | [第27天 >>](./27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) \ No newline at end of file diff --git a/Chinese/27_python_with_mongodb_cn.md b/Chinese/27_python_with_mongodb_cn.md index 2bf2f0f39..c6bb1eeec 100644 --- a/Chinese/27_python_with_mongodb_cn.md +++ b/Chinese/27_python_with_mongodb_cn.md @@ -629,4 +629,4 @@ db.students.drop() 🎉 恭喜!🎉 -[<< 第26天](../26_Day_Python_web/26_python_web_cn.md) | [第28天 >>](../28_Day_API/28_API_cn.md) \ No newline at end of file +[<< 第26天](./26_Day_Python_web/26_python_web_cn.md) | [第28天 >>](./28_Day_API/28_API_cn.md) \ No newline at end of file diff --git a/Chinese/28_API_cn.md b/Chinese/28_API_cn.md index 4ed2d183b..32b6d415c 100644 --- a/Chinese/28_API_cn.md +++ b/Chinese/28_API_cn.md @@ -140,4 +140,4 @@ GET、POST、PUT和DELETE是我们将实现API或CRUD操作应用程序的HTTP 🎉 恭喜!🎉 -[<< 第27天](../27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) | [第29天 >>](../29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file +[<< 第27天](./27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) | [第29天 >>](./29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file diff --git a/Chinese/29_building_API_cn.md b/Chinese/29_building_API_cn.md index 704a8dc36..07cb454ad 100644 --- a/Chinese/29_building_API_cn.md +++ b/Chinese/29_building_API_cn.md @@ -457,4 +457,4 @@ if __name__ == '__main__': 🎉 恭喜!🎉 -[<< 第28天](../28_Day_API/28_API_cn.md) | [第30天 >>](../30_Day_Conclusions/30_conclusions_cn.md) \ No newline at end of file +[<< 第28天](./28_Day_API/28_API_cn.md) | [第30天 >>](./30_Day_Conclusions/30_conclusions_cn.md) \ No newline at end of file diff --git a/Chinese/30_conclusions_cn.md b/Chinese/30_conclusions_cn.md index 25f26b309..dbec8a5ba 100644 --- a/Chinese/30_conclusions_cn.md +++ b/Chinese/30_conclusions_cn.md @@ -19,4 +19,4 @@ http://thirtydayofpython-api.herokuapp.com/feedback 🎉 恭喜!🎉 -[<< 第29天](../29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file +[<< 第29天](./29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file From 1f756dc8c54852bd7142ff04e1199f80f4a608da Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Wed, 4 Jun 2025 23:54:55 +0300 Subject: [PATCH 52/63] Create FUNDING.yml --- .github/FUNDING.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..aa0584d57 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,6 @@ +# These are supported funding model platforms + +github: [] +open_collective: 30DaysOfPython +thanks_dev: +custom: [] From fa17e3261d955f29182f26c9ce06021ad8983856 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Thu, 5 Jun 2025 00:44:26 +0300 Subject: [PATCH 53/63] Update FUNDING.yml --- .github/FUNDING.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index aa0584d57..a9ccc188b 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,6 +1,3 @@ -# These are supported funding model platforms - -github: [] -open_collective: 30DaysOfPython +github: [Asabeneh] thanks_dev: custom: [] From e1f5cfd1b65e3d9e2266a541390430dd67d43e84 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Thu, 5 Jun 2025 00:46:25 +0300 Subject: [PATCH 54/63] Update FUNDING.yml --- .github/FUNDING.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index a9ccc188b..24ce4e569 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,3 +1,3 @@ -github: [Asabeneh] +github: [30DaysOfPython] thanks_dev: custom: [] From 2a97b72bc09b8375bc5e30c9d1ccc3a084a909db Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Thu, 5 Jun 2025 00:49:42 +0300 Subject: [PATCH 55/63] Update FUNDING.yml --- .github/FUNDING.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 24ce4e569..a9ccc188b 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,3 +1,3 @@ -github: [30DaysOfPython] +github: [Asabeneh] thanks_dev: custom: [] From 3b0232a62c0c39df00db2f5a82f36425773caf27 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Mon, 29 Sep 2025 18:12:00 +0300 Subject: [PATCH 56/63] contributor section added --- images/wispr_flow_logo.svg | 8 ++++++++ readme.md | 39 +++++++++++++++++++++++++++++--------- 2 files changed, 38 insertions(+), 9 deletions(-) create mode 100644 images/wispr_flow_logo.svg diff --git a/images/wispr_flow_logo.svg b/images/wispr_flow_logo.svg new file mode 100644 index 000000000..1e5343cae --- /dev/null +++ b/images/wispr_flow_logo.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/readme.md b/readme.md index 95bae55af..82220dc05 100644 --- a/readme.md +++ b/readme.md @@ -1,7 +1,5 @@ # 🐍 30 Days Of Python - Learn with Asabeneh by joining the upcoming [CODING BOOTCAMP](https://docs.google.com/forms/d/e/1FAIpQLSf0oNIYR9XU1DCctfl-pY36KbWse-SQX5aQaUgetqSinFYnmQ/viewform) - |# Day | Topics | |------|:---------------------------------------------------------:| | 01 | [Introduction](./readme.md)| @@ -35,14 +33,34 @@ | 29 | [Building API](./29_Day_Building_API/29_building_API.md)| | 30 | [Conclusions](./30_Day_Conclusions/30_conclusions.md)| - Learn with Asabeneh by joining the upcoming [CODING BOOTCAMP](https://docs.google.com/forms/d/e/1FAIpQLSf0oNIYR9XU1DCctfl-pY36KbWse-SQX5aQaUgetqSinFYnmQ/viewform) +🧡🧡🧡 HAPPY CODING 🧡🧡🧡 -🧡🧡🧡 HAPPY CODING 🧡🧡🧡 +## 💖 Sponsors -
-Support the author to create more educational materials
-Paypal Logo -
+Our amazing sponsors for supporting my open-source contribution and the **30 Days of Challenge** series! + +### Current Sponsor + +

+ + Wispr Flow Logo + +

+ +

Dictation that understands code

+ + Ship 4x faster with developer-first dictation that works in every app. + + +--- + +### 🙌 Become a Sponsor + +You can support this project by becoming a sponsor on **[GitHub Sponsors](https://github.com/sponsors/asabeneh)** or through [PayPal](https://www.paypal.me/asabeneh). + +Every contribution, big or small, makes a huge difference. Thank you for your support! 🌟 + +---

30 Days Of Python: Day 1 - Introduction

@@ -67,6 +85,9 @@ ![30DaysOfPython](./images/30DaysOfPython_banner3@2x.png) - [🐍 30 Days Of Python](#-30-days-of-python) + - [💖 Sponsors](#-sponsors) + - [Current Sponsor](#current-sponsor) + - [🙌 Become a Sponsor](#-become-a-sponsor) - [📘 Day 1](#-day-1) - [Welcome](#welcome) - [Introduction](#introduction) @@ -105,7 +126,7 @@ If you would like to actively engage in the challenge, you may join the [30DaysO ## Introduction -Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of the Python programming language was derived from a British sketch comedy series, *Monty Python's Flying Circus*. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, and many hands on exercises and projects. +Python is a high-level programming language for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer, Guido van Rossum. The name of the Python programming language was derived from a British sketch comedy series, _Monty Python's Flying Circus_. The first version was released on February 20, 1991. This 30 days of Python challenge will help you learn the latest version of Python, Python 3 step by step. The topics are broken down into 30 days, where each day contains several topics with easy-to-understand explanations, real-world examples, and many hands on exercises and projects. This challenge is designed for beginners and professionals who want to learn python programming language. It may take 30 to 100 days to complete the challenge. People who actively participate in the telegram group have a high probability of completing the challenge. From df8b764e20d18906837a2ae1d675f5ebd3ec4a01 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Tue, 30 Sep 2025 00:43:59 +0300 Subject: [PATCH 57/63] Wispr flow logo changed --- images/Wispr_Flow-logo.png | Bin 0 -> 13516 bytes readme.md | 13 +++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) create mode 100644 images/Wispr_Flow-logo.png diff --git a/images/Wispr_Flow-logo.png b/images/Wispr_Flow-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..db238931621ecb208a59a7c7357642ad8b9f0b35 GIT binary patch literal 13516 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 literal 0 HcmV?d00001 diff --git a/readme.md b/readme.md index 82220dc05..edf7875a4 100644 --- a/readme.md +++ b/readme.md @@ -41,16 +41,17 @@ Our amazing sponsors for supporting my open-source contribution and the **30 Day ### Current Sponsor +---

- - Wispr Flow Logo - + + Wispr Flow Logo +

Dictation that understands code

- - Ship 4x faster with developer-first dictation that works in every app. - +

+ Ship 4x faster with developer-first dictation that works in every app. +

--- From 36942a63e8d72eb1c4b0da8b26c03537e6e5a833 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Tue, 30 Sep 2025 01:50:16 +0300 Subject: [PATCH 58/63] night mode added --- images/Wispr_Flow-Logo-white.png | Bin 0 -> 12940 bytes readme.md | 31 ++++++++++++++++++++++--------- 2 files changed, 22 insertions(+), 9 deletions(-) create mode 100644 images/Wispr_Flow-Logo-white.png diff --git a/images/Wispr_Flow-Logo-white.png b/images/Wispr_Flow-Logo-white.png new file mode 100644 index 0000000000000000000000000000000000000000..744cd11ae075da252163c03b164ec5cca92e8755 GIT binary patch literal 12940 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 B6G{L8 literal 0 HcmV?d00001 diff --git a/readme.md b/readme.md index edf7875a4..f93436632 100644 --- a/readme.md +++ b/readme.md @@ -42,17 +42,29 @@ Our amazing sponsors for supporting my open-source contribution and the **30 Day ### Current Sponsor --- -

- - Wispr Flow Logo - -

+
+

💖 Sponsors

-

Dictation that understands code

-

- Ship 4x faster with developer-first dictation that works in every app. -

+

Our amazing sponsors for supporting my open-source contribution and the 30 Days of Challenge series!

+

Current Sponsor

+
+
+ + + + + + Wispr Flow Logo + + + +

Dictation that understands code

+

Ship 4x faster with developer-first dictation that works in every app.

+
--- ### 🙌 Become a Sponsor @@ -88,6 +100,7 @@ Every contribution, big or small, makes a huge difference. Thank you for your su - [🐍 30 Days Of Python](#-30-days-of-python) - [💖 Sponsors](#-sponsors) - [Current Sponsor](#current-sponsor) + - [](#) - [🙌 Become a Sponsor](#-become-a-sponsor) - [📘 Day 1](#-day-1) - [Welcome](#welcome) From 685b08f446b9236833b5d440dd49c6bab1b2d70e Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Tue, 30 Sep 2025 01:51:24 +0300 Subject: [PATCH 59/63] night mode added --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index f93436632..2e119bab6 100644 --- a/readme.md +++ b/readme.md @@ -65,6 +65,7 @@ Our amazing sponsors for supporting my open-source contribution and the **30 Day

Dictation that understands code

Ship 4x faster with developer-first dictation that works in every app.

+ --- ### 🙌 Become a Sponsor @@ -100,7 +101,6 @@ Every contribution, big or small, makes a huge difference. Thank you for your su - [🐍 30 Days Of Python](#-30-days-of-python) - [💖 Sponsors](#-sponsors) - [Current Sponsor](#current-sponsor) - - [](#) - [🙌 Become a Sponsor](#-become-a-sponsor) - [📘 Day 1](#-day-1) - [Welcome](#welcome) From 402dde515d6b4e5d27935eb1fe2aca8773ddcb2d Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Wed, 1 Oct 2025 21:29:54 +0300 Subject: [PATCH 60/63] duplicate content removed --- readme.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/readme.md b/readme.md index 2e119bab6..2d75f551b 100644 --- a/readme.md +++ b/readme.md @@ -35,12 +35,6 @@ 🧡🧡🧡 HAPPY CODING 🧡🧡🧡 -## 💖 Sponsors - -Our amazing sponsors for supporting my open-source contribution and the **30 Days of Challenge** series! - -### Current Sponsor - ---

💖 Sponsors

@@ -99,8 +93,6 @@ Every contribution, big or small, makes a huge difference. Thank you for your su ![30DaysOfPython](./images/30DaysOfPython_banner3@2x.png) - [🐍 30 Days Of Python](#-30-days-of-python) - - [💖 Sponsors](#-sponsors) - - [Current Sponsor](#current-sponsor) - [🙌 Become a Sponsor](#-become-a-sponsor) - [📘 Day 1](#-day-1) - [Welcome](#welcome) From 360f12791f945b6c961466788ca6ac05a014e59b Mon Sep 17 00:00:00 2001 From: Rakel Date: Fri, 10 Oct 2025 13:49:50 +0900 Subject: [PATCH 61/63] Fix Chinese navigation links after Day 7 --- Chinese/07_sets.md | 4 +- Chinese/08_dictionaries.md | 4 +- Chinese/09_conditionals.md | 4 +- Chinese/10_loops.md | 4 +- Chinese/11_functions.md | 4 +- Chinese/12_modules.md | 4 +- Chinese/13_list_comprehension.md | 4 +- Chinese/14_higher_order_functions.md | 4 +- Chinese/15_python_type_errors_cn.md | 688 +++++----- Chinese/16_python_datetime_cn.md | 384 +++--- Chinese/17_exception_handling_cn.md | 570 ++++---- Chinese/18_regular_expressions_cn.md | 834 ++++++------ Chinese/19_file_handling_cn.md | 1098 +++++++-------- Chinese/20_python_package_manager_cn.md | 704 +++++----- Chinese/21_classes_and_objects_cn.md | 838 ++++++------ Chinese/22_web_scraping_cn.md | 178 +-- Chinese/23_virtual_environment_cn.md | 194 +-- Chinese/24_statistics_cn.md | 1178 ++++++++-------- Chinese/25_pandas_cn.md | 1102 +++++++-------- Chinese/26_python_web_cn.md | 1634 +++++++++++------------ Chinese/27_python_with_mongodb_cn.md | 1264 +++++++++--------- Chinese/28_API_cn.md | 286 ++-- Chinese/29_building_API_cn.md | 920 ++++++------- Chinese/30_conclusions_cn.md | 44 +- Chinese/README.md | 48 +- 25 files changed, 5998 insertions(+), 5998 deletions(-) diff --git a/Chinese/07_sets.md b/Chinese/07_sets.md index 21c8cf091..540f706b6 100644 --- a/Chinese/07_sets.md +++ b/Chinese/07_sets.md @@ -14,7 +14,7 @@
-[<< 第 6 天](../06_Day_Tuples/06_tuples.md) | [第 8 天 >>](../08_Day_Dictionaries/08_dictionaries.md) +[<< 第 6 天](./06_tuples.md) | [第 8 天 >>](./08_dictionaries.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -428,4 +428,4 @@ age = [22, 19, 24, 25, 26, 24, 25, 24] 🎉 恭喜! 🎉 -[<< 第 6 天](../06_Day_Tuples/06_tuples.md) | [第 8 天 >>](../08_Day_Dictionaries/08_dictionaries.md) +[<< 第 6 天](./06_tuples.md) | [第 8 天 >>](./08_dictionaries.md) diff --git a/Chinese/08_dictionaries.md b/Chinese/08_dictionaries.md index 7b5084297..bfaee625d 100644 --- a/Chinese/08_dictionaries.md +++ b/Chinese/08_dictionaries.md @@ -14,7 +14,7 @@
-[<< 第 7 天 ](../07_Day_Sets/07_sets.md) | [第 9 天 >>](../09_Day_Conditionals/09_conditionals.md) +[<< 第 7 天](./07_sets.md) | [第 9 天 >>](./09_conditionals.md) ![30 天 Python 学习](../images/30DaysOfPython_banner3@2x.png) @@ -340,4 +340,4 @@ print(values) # dict_values(['value1', 'value2', 'value3', 'value4']) 🎉 恭喜你! 🎉 -[<< 第 7 天 ](../07_Day_Sets/07_sets.md) | [第 9 天 >>](../09_Day_Conditionals/09_conditionals.md) +[<< 第 7 天](./07_sets.md) | [第 9 天 >>](./09_conditionals.md) diff --git a/Chinese/09_conditionals.md b/Chinese/09_conditionals.md index fb69fde31..cf378a694 100644 --- a/Chinese/09_conditionals.md +++ b/Chinese/09_conditionals.md @@ -14,7 +14,7 @@
-[<< 第 8 天](../08_Day_Dictionaries/08_dictionaries.md) | [第 10 天 >>](../10_Day_Loops/10_loops.md) +[<< 第 8 天](./08_dictionaries.md) | [第 10 天 >>](./10_loops.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -281,4 +281,4 @@ Asabeneh Yetayeh住在芬兰。他已婚。 🎉 恭喜! 🎉 -[<< 第 8 天](../08_Day_Dictionaries/08_dictionaries.md) | [第 10 天 >>](../10_Day_Loops/10_loops.md) +[<< 第 8 天](./08_dictionaries.md) | [第 10 天 >>](./10_loops.md) diff --git a/Chinese/10_loops.md b/Chinese/10_loops.md index 40484074a..70da66b16 100644 --- a/Chinese/10_loops.md +++ b/Chinese/10_loops.md @@ -14,7 +14,7 @@ -[<<第九天](../Chinese/09_conditionals.md) | [第十一天>>](../Chinese/11_functions.md) +[<< 第 9 天](./09_conditionals.md) | [第 11 天 >>](./11_functions.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -448,4 +448,4 @@ for number in range(6): 🎉 恭喜! 🎉 -[<< Day 9](./09_conditionals.md) | [Day 11 >>](./11_functions.md) \ No newline at end of file +[<< 第 9 天](./09_conditionals.md) | [第 11 天 >>](./11_functions.md) \ No newline at end of file diff --git a/Chinese/11_functions.md b/Chinese/11_functions.md index a7d8a4c76..0c44d1b24 100644 --- a/Chinese/11_functions.md +++ b/Chinese/11_functions.md @@ -14,7 +14,7 @@ -[<< 第 10 天](../10_Day_Loops/10_loops.md) | [第 12 天 >>](../12_Day_Modules/12_modules.md) +[<< 第 10 天](./10_loops.md) | [第 12 天 >>](./12_modules.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -455,4 +455,4 @@ print(sum_all_numbers(100)) # 5050 🎉 恭喜! 🎉 -[<< 第 10 天](../10_Day_Loops/10_loops.md) | [第 12 天 >>](../12_Day_Modules/12_modules.md) +[<< 第 10 天](./10_loops.md) | [第 12 天 >>](./12_modules.md) diff --git a/Chinese/12_modules.md b/Chinese/12_modules.md index 1632a36c0..0899109e0 100644 --- a/Chinese/12_modules.md +++ b/Chinese/12_modules.md @@ -15,7 +15,7 @@ -[<< 第 11 天](../11_Day_Functions/11_functions.md) | [第 13 天>>](../13_Day_List_comprehension/13_list_comprehension.md) +[<< 第 11 天](./11_functions.md) | [第 13 天 >>](./13_list_comprehension.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -300,4 +300,4 @@ print(rgb_color_gen()) 🎉 恭喜! 🎉 -[<< 第 11 天](../11_Day_Functions/11_functions.md) | [第 13 天>>](../13_Day_List_comprehension/13_list_comprehension.md) +[<< 第 11 天](./11_functions.md) | [第 13 天 >>](./13_list_comprehension.md) diff --git a/Chinese/13_list_comprehension.md b/Chinese/13_list_comprehension.md index d2b9887b0..205d11067 100644 --- a/Chinese/13_list_comprehension.md +++ b/Chinese/13_list_comprehension.md @@ -15,7 +15,7 @@ -[<< 第 12 天](../12_Day_Modules/12_modules.md) | [第 14 天>>](../14_Day_Higher_order_functions/14_higher_order_functions.md) +[<< 第 12 天](./12_modules.md) | [第 14 天 >>](./14_higher_order_functions.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -205,4 +205,4 @@ print(two_power_of_five) # 32 🎉 祝贺你!🎉 -[<< 第 12 天](../12_Day_Modules/12_modules.md) | [第 14 天>>](../14_Day_Higher_order_functions/14_higher_order_functions.md) +[<< 第 12 天](./12_modules.md) | [第 14 天 >>](./14_higher_order_functions.md) diff --git a/Chinese/14_higher_order_functions.md b/Chinese/14_higher_order_functions.md index be1b415dd..2e7575f32 100644 --- a/Chinese/14_higher_order_functions.md +++ b/Chinese/14_higher_order_functions.md @@ -14,7 +14,7 @@ -[<< 第 13 天](../13_Day_List_comprehension/13_list_comprehension.md) | [第 15 天>>](../15_Day_Python_type_errors/15_python_type_errors.md) +[<< 第 13 天](./13_list_comprehension.md) | [第 15 天 >>](./15_python_type_errors_cn.md) ![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png) @@ -365,4 +365,4 @@ numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 🎉 恭喜你! 🎉 -[<< 第 13 天](../13_Day_List_comprehension/13_list_comprehension.md) | [第 15 天>>](../15_Day_Python_type_errors/15_python_type_errors.md) +[<< 第 13 天](./13_list_comprehension.md) | [第 15 天 >>](./15_python_type_errors_cn.md) diff --git a/Chinese/15_python_type_errors_cn.md b/Chinese/15_python_type_errors_cn.md index 6b6f46ebd..891465924 100644 --- a/Chinese/15_python_type_errors_cn.md +++ b/Chinese/15_python_type_errors_cn.md @@ -1,344 +1,344 @@ -# 30天Python编程挑战:第15天 - Python类型错误 - -- [Day 15](#day-15) - - [Python错误类型](#python错误类型) - - [SyntaxError (语法错误)](#syntaxerror-语法错误) - - [NameError (名称错误)](#nameerror-名称错误) - - [IndexError (索引错误)](#indexerror-索引错误) - - [ModuleNotFoundError (模块未找到错误)](#modulenotfounderror-模块未找到错误) - - [AttributeError (属性错误)](#attributeerror-属性错误) - - [KeyError (键错误)](#keyerror-键错误) - - [TypeError (类型错误)](#typeerror-类型错误) - - [ImportError (导入错误)](#importerror-导入错误) - - [ValueError (值错误)](#valueerror-值错误) - - [ZeroDivisionError (零除错误)](#zerodivisionerror-零除错误) - - [💻 练习 - 第15天](#-练习---第15天) - -# 📘 Day 15 - -## Python错误类型 - -当我们编写代码时,常常会出现打字错误或其他常见错误。如果我们的代码运行失败,Python解释器会显示一条消息,提供有关问题发生位置和错误类型的反馈信息。有时它还会给我们提供可能的修复建议。了解编程语言中不同类型的错误将帮助我们快速调试代码,并使我们在编程技能上有所提高。 - -让我们一一查看最常见的错误类型。首先,让我们打开Python交互式shell。转到你的计算机终端并输入'python'。Python交互式shell将会被打开。 - -### SyntaxError (语法错误) - -**示例1: SyntaxError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> print 'hello world' - File "", line 1 - print 'hello world' - ^ -SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')? ->>> -``` - -如你所见,我们犯了一个语法错误,因为我们忘记用括号括起字符串,而Python已经提出了解决方案。让我们修复它。 - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> print 'hello world' - File "", line 1 - print 'hello world' - ^ -SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')? ->>> print('hello world') -hello world ->>> -``` - -错误是一个_SyntaxError_。修复后,我们的代码顺利执行。让我们看看更多的错误类型。 - -### NameError (名称错误) - -**示例1: NameError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> print(age) -Traceback (most recent call last): - File "", line 1, in -NameError: name 'age' is not defined ->>> -``` - -从上面的消息可以看出,名称age没有被定义。是的,确实如此,我们没有定义age变量,但我们试图像已经声明了一样打印它。现在,让我们通过声明变量并为其赋值来修复这个问题。 - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> print(age) -Traceback (most recent call last): - File "", line 1, in -NameError: name 'age' is not defined ->>> age = 25 ->>> print(age) -25 ->>> -``` - -错误类型是_NameError_。我们通过定义变量名来调试了错误。 - -### IndexError (索引错误) - -**示例1: IndexError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> numbers = [1, 2, 3, 4, 5] ->>> numbers[5] -Traceback (most recent call last): - File "", line 1, in -IndexError: list index out of range ->>> -``` - -在上面的例子中,Python抛出了一个_IndexError_,因为列表的索引只有0到4,所以索引5超出了范围。 - -### ModuleNotFoundError (模块未找到错误) - -**示例1: ModuleNotFoundError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> import maths -Traceback (most recent call last): - File "", line 1, in -ModuleNotFoundError: No module named 'maths' ->>> -``` - -在上面的例子中,我故意在math后面添加了一个多余的s,结果抛出了_ModuleNotFoundError_。让我们通过从math中删除多余的s来修复它。 - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> import maths -Traceback (most recent call last): - File "", line 1, in -ModuleNotFoundError: No module named 'maths' ->>> import math ->>> -``` - -我们修复了它,所以让我们使用math模块中的一些函数。 - -### AttributeError (属性错误) - -**示例1: AttributeError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> import maths -Traceback (most recent call last): - File "", line 1, in -ModuleNotFoundError: No module named 'maths' ->>> import math ->>> math.PI -Traceback (most recent call last): - File "", line 1, in -AttributeError: module 'math' has no attribute 'PI' ->>> -``` - -如你所见,我又犯了一个错误!我试图从math模块调用PI函数,而不是pi。这抛出了一个属性错误,表示该函数在模块中不存在。让我们通过将PI更改为pi来修复它。 - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> import maths -Traceback (most recent call last): - File "", line 1, in -ModuleNotFoundError: No module named 'maths' ->>> import math ->>> math.PI -Traceback (most recent call last): - File "", line 1, in -AttributeError: module 'math' has no attribute 'PI' ->>> math.pi -3.141592653589793 ->>> -``` - -现在,当我们从math模块调用pi时,我们得到了结果。 - -### KeyError (键错误) - -**示例1: KeyError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> users = {'name':'Asab', 'age':250, 'country':'Finland'} ->>> users['name'] -'Asab' ->>> users['county'] -Traceback (most recent call last): - File "", line 1, in -KeyError: 'county' ->>> -``` - -如你所见,在用于获取字典值的键中有一个拼写错误。这是一个键错误,修复方法很简单。让我们来做这个! - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> user = {'name':'Asab', 'age':250, 'country':'Finland'} ->>> user['name'] -'Asab' ->>> user['county'] -Traceback (most recent call last): - File "", line 1, in -KeyError: 'county' ->>> user['country'] -'Finland' ->>> -``` - -我们调试了错误,我们的代码运行并得到了结果。 - -### TypeError (类型错误) - -**示例1: TypeError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> 4 + '3' -Traceback (most recent call last): - File "", line 1, in -TypeError: unsupported operand type(s) for +: 'int' and 'str' ->>> -``` - -在上面的例子中,出现了TypeError,因为我们不能将数字与字符串相加。第一个解决方案是将字符串转换为int或float。另一个解决方案是将数字转换为字符串(那么结果将是'43')。让我们采用第一种修复方式。 - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> 4 + '3' -Traceback (most recent call last): - File "", line 1, in -TypeError: unsupported operand type(s) for +: 'int' and 'str' ->>> 4 + int('3') -7 ->>> 4 + float('3') -7.0 ->>> -``` - -错误已消除,我们得到了预期的结果。 - -### ImportError (导入错误) - -**示例1: ImportError** - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> from math import power -Traceback (most recent call last): - File "", line 1, in -ImportError: cannot import name 'power' from 'math' ->>> -``` - -math模块中没有名为power的函数,它的名字是不同的:_pow_。让我们纠正它: - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> from math import power -Traceback (most recent call last): - File "", line 1, in -ImportError: cannot import name 'power' from 'math' ->>> from math import pow ->>> pow(2,3) -8.0 ->>> -``` - -### ValueError (值错误) - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> int('12a') -Traceback (most recent call last): - File "", line 1, in -ValueError: invalid literal for int() with base 10: '12a' ->>> -``` - -在这种情况下,我们无法将给定的字符串转换为数字,因为其中有字母'a'。 - -### ZeroDivisionError (零除错误) - -```python -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> 1/0 -Traceback (most recent call last): - File "", line 1, in -ZeroDivisionError: division by zero ->>> -``` - -我们不能用零去除一个数字。 - -我们已经介绍了一些Python错误类型,如果你想了解更多,请查看Python文档中关于Python错误类型的内容。 -如果你擅长阅读错误类型,那么你将能够快速修复你的bug,你也将成为一个更好的程序员。 - -🌕 你正在进步。你已经完成了一半的道路,正走向伟大。现在做一些练习来锻炼你的大脑和肌肉。 - -## 💻 练习 - 第15天 - -1. 打开你的Python交互式shell,尝试本节中介绍的所有示例。 - -🎉 恭喜!🎉 - -[<< 第14天](./14_higher_order_functions.md) | [第16天 >>](./16_python_datetime_cn.md) \ No newline at end of file +# 30天Python编程挑战:第15天 - Python类型错误 + +- [Day 15](#day-15) + - [Python错误类型](#python错误类型) + - [SyntaxError (语法错误)](#syntaxerror-语法错误) + - [NameError (名称错误)](#nameerror-名称错误) + - [IndexError (索引错误)](#indexerror-索引错误) + - [ModuleNotFoundError (模块未找到错误)](#modulenotfounderror-模块未找到错误) + - [AttributeError (属性错误)](#attributeerror-属性错误) + - [KeyError (键错误)](#keyerror-键错误) + - [TypeError (类型错误)](#typeerror-类型错误) + - [ImportError (导入错误)](#importerror-导入错误) + - [ValueError (值错误)](#valueerror-值错误) + - [ZeroDivisionError (零除错误)](#zerodivisionerror-零除错误) + - [💻 练习 - 第15天](#-练习---第15天) + +# 📘 Day 15 + +## Python错误类型 + +当我们编写代码时,常常会出现打字错误或其他常见错误。如果我们的代码运行失败,Python解释器会显示一条消息,提供有关问题发生位置和错误类型的反馈信息。有时它还会给我们提供可能的修复建议。了解编程语言中不同类型的错误将帮助我们快速调试代码,并使我们在编程技能上有所提高。 + +让我们一一查看最常见的错误类型。首先,让我们打开Python交互式shell。转到你的计算机终端并输入'python'。Python交互式shell将会被打开。 + +### SyntaxError (语法错误) + +**示例1: SyntaxError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print 'hello world' + File "", line 1 + print 'hello world' + ^ +SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')? +>>> +``` + +如你所见,我们犯了一个语法错误,因为我们忘记用括号括起字符串,而Python已经提出了解决方案。让我们修复它。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print 'hello world' + File "", line 1 + print 'hello world' + ^ +SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')? +>>> print('hello world') +hello world +>>> +``` + +错误是一个_SyntaxError_。修复后,我们的代码顺利执行。让我们看看更多的错误类型。 + +### NameError (名称错误) + +**示例1: NameError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print(age) +Traceback (most recent call last): + File "", line 1, in +NameError: name 'age' is not defined +>>> +``` + +从上面的消息可以看出,名称age没有被定义。是的,确实如此,我们没有定义age变量,但我们试图像已经声明了一样打印它。现在,让我们通过声明变量并为其赋值来修复这个问题。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> print(age) +Traceback (most recent call last): + File "", line 1, in +NameError: name 'age' is not defined +>>> age = 25 +>>> print(age) +25 +>>> +``` + +错误类型是_NameError_。我们通过定义变量名来调试了错误。 + +### IndexError (索引错误) + +**示例1: IndexError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> numbers = [1, 2, 3, 4, 5] +>>> numbers[5] +Traceback (most recent call last): + File "", line 1, in +IndexError: list index out of range +>>> +``` + +在上面的例子中,Python抛出了一个_IndexError_,因为列表的索引只有0到4,所以索引5超出了范围。 + +### ModuleNotFoundError (模块未找到错误) + +**示例1: ModuleNotFoundError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> +``` + +在上面的例子中,我故意在math后面添加了一个多余的s,结果抛出了_ModuleNotFoundError_。让我们通过从math中删除多余的s来修复它。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> import math +>>> +``` + +我们修复了它,所以让我们使用math模块中的一些函数。 + +### AttributeError (属性错误) + +**示例1: AttributeError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> import math +>>> math.PI +Traceback (most recent call last): + File "", line 1, in +AttributeError: module 'math' has no attribute 'PI' +>>> +``` + +如你所见,我又犯了一个错误!我试图从math模块调用PI函数,而不是pi。这抛出了一个属性错误,表示该函数在模块中不存在。让我们通过将PI更改为pi来修复它。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import maths +Traceback (most recent call last): + File "", line 1, in +ModuleNotFoundError: No module named 'maths' +>>> import math +>>> math.PI +Traceback (most recent call last): + File "", line 1, in +AttributeError: module 'math' has no attribute 'PI' +>>> math.pi +3.141592653589793 +>>> +``` + +现在,当我们从math模块调用pi时,我们得到了结果。 + +### KeyError (键错误) + +**示例1: KeyError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> users = {'name':'Asab', 'age':250, 'country':'Finland'} +>>> users['name'] +'Asab' +>>> users['county'] +Traceback (most recent call last): + File "", line 1, in +KeyError: 'county' +>>> +``` + +如你所见,在用于获取字典值的键中有一个拼写错误。这是一个键错误,修复方法很简单。让我们来做这个! + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> user = {'name':'Asab', 'age':250, 'country':'Finland'} +>>> user['name'] +'Asab' +>>> user['county'] +Traceback (most recent call last): + File "", line 1, in +KeyError: 'county' +>>> user['country'] +'Finland' +>>> +``` + +我们调试了错误,我们的代码运行并得到了结果。 + +### TypeError (类型错误) + +**示例1: TypeError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> 4 + '3' +Traceback (most recent call last): + File "", line 1, in +TypeError: unsupported operand type(s) for +: 'int' and 'str' +>>> +``` + +在上面的例子中,出现了TypeError,因为我们不能将数字与字符串相加。第一个解决方案是将字符串转换为int或float。另一个解决方案是将数字转换为字符串(那么结果将是'43')。让我们采用第一种修复方式。 + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> 4 + '3' +Traceback (most recent call last): + File "", line 1, in +TypeError: unsupported operand type(s) for +: 'int' and 'str' +>>> 4 + int('3') +7 +>>> 4 + float('3') +7.0 +>>> +``` + +错误已消除,我们得到了预期的结果。 + +### ImportError (导入错误) + +**示例1: ImportError** + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> from math import power +Traceback (most recent call last): + File "", line 1, in +ImportError: cannot import name 'power' from 'math' +>>> +``` + +math模块中没有名为power的函数,它的名字是不同的:_pow_。让我们纠正它: + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> from math import power +Traceback (most recent call last): + File "", line 1, in +ImportError: cannot import name 'power' from 'math' +>>> from math import pow +>>> pow(2,3) +8.0 +>>> +``` + +### ValueError (值错误) + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> int('12a') +Traceback (most recent call last): + File "", line 1, in +ValueError: invalid literal for int() with base 10: '12a' +>>> +``` + +在这种情况下,我们无法将给定的字符串转换为数字,因为其中有字母'a'。 + +### ZeroDivisionError (零除错误) + +```python +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> 1/0 +Traceback (most recent call last): + File "", line 1, in +ZeroDivisionError: division by zero +>>> +``` + +我们不能用零去除一个数字。 + +我们已经介绍了一些Python错误类型,如果你想了解更多,请查看Python文档中关于Python错误类型的内容。 +如果你擅长阅读错误类型,那么你将能够快速修复你的bug,你也将成为一个更好的程序员。 + +🌕 你正在进步。你已经完成了一半的道路,正走向伟大。现在做一些练习来锻炼你的大脑和肌肉。 + +## 💻 练习 - 第15天 + +1. 打开你的Python交互式shell,尝试本节中介绍的所有示例。 + +🎉 恭喜!🎉 + +[<< 第 14 天](./14_higher_order_functions.md) | [第 16 天 >>](./16_python_datetime_cn.md) \ No newline at end of file diff --git a/Chinese/16_python_datetime_cn.md b/Chinese/16_python_datetime_cn.md index 6c9aae0c7..c497146ec 100644 --- a/Chinese/16_python_datetime_cn.md +++ b/Chinese/16_python_datetime_cn.md @@ -1,192 +1,192 @@ -# 30天Python编程挑战:第16天 - Python日期时间 - -- [第16天](#-第16天) - - [Python *datetime*](#python-datetime) - - [获取 *datetime* 信息](#获取-datetime-信息) - - [使用 *strftime* 格式化日期输出](#使用-strftime-格式化日期输出) - - [使用 *strptime* 将字符串转换为时间](#使用-strptime-将字符串转换为时间) - - [从 *datetime* 使用 *date*](#从-datetime-使用-date) - - [使用Time对象表示时间](#使用time对象表示时间) - - [计算两个时间点之间的差异](#计算两个时间点之间的差异) - - [使用 *timedelta* 计算两个时间点之间的差异](#使用-timedelta-计算两个时间点之间的差异) - - [💻 练习 - 第16天](#-练习---第16天) - -# 📘 第16天 - -## Python *datetime* - -Python有一个 _datetime_ 模块用于处理日期和时间。 - -```py -import datetime -print(dir(datetime)) -['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo'] -``` - -通过dir或help内置命令,可以了解特定模块中可用的函数。如你所见,datetime模块中有许多函数,但我们将重点关注 _date_、_datetime_、_time_ 和 _timedelta_。让我们一个一个地看。 - -### 获取 *datetime* 信息 - -```py -from datetime import datetime -now = datetime.now() -print(now) # 2021-07-08 07:34:46.549883 -day = now.day # 8 -month = now.month # 7 -year = now.year # 2021 -hour = now.hour # 7 -minute = now.minute # 38 -second = now.second -timestamp = now.timestamp() -print(day, month, year, hour, minute) -print('timestamp', timestamp) -print(f'{day}/{month}/{year}, {hour}:{minute}') # 8/7/2021, 7:38 -``` - -时间戳或Unix时间戳是从1970年1月1日UTC开始经过的秒数。 - -### 使用 *strftime* 格式化日期输出 - -```py -from datetime import datetime -new_year = datetime(2020, 1, 1) -print(new_year) # 2020-01-01 00:00:00 -day = new_year.day -month = new_year.month -year = new_year.year -hour = new_year.hour -minute = new_year.minute -second = new_year.second -print(day, month, year, hour, minute) #1 1 2020 0 0 -print(f'{day}/{month}/{year}, {hour}:{minute}') # 1/1/2020, 0:0 - -``` - -使用 *strftime* 方法格式化日期时间,相关文档可以在[这里](https://strftime.org/)找到。 - -```py -from datetime import datetime -# 当前日期和时间 -now = datetime.now() -t = now.strftime("%H:%M:%S") -print("时间:", t) -time_one = now.strftime("%m/%d/%Y, %H:%M:%S") -# mm/dd/YY H:M:S 格式 -print("时间一:", time_one) -time_two = now.strftime("%d/%m/%Y, %H:%M:%S") -# dd/mm/YY H:M:S 格式 -print("时间二:", time_two) -``` - -```sh -时间: 01:05:01 -时间一: 12/05/2019, 01:05:01 -时间二: 05/12/2019, 01:05:01 -``` - -以下是我们用来格式化时间的所有 _strftime_ 符号。这个模块的所有格式示例。 - -![strftime](../images/strftime.png) - -### 使用 *strptime* 将字符串转换为时间 -这里有一个[文档](https://www.programiz.com/python-programming/datetime/strptimet),有助于理解格式。 - -```py -from datetime import datetime -date_string = "5 December, 2019" -print("date_string =", date_string) -date_object = datetime.strptime(date_string, "%d %B, %Y") -print("date_object =", date_object) -``` - -```sh -date_string = 5 December, 2019 -date_object = 2019-12-05 00:00:00 -``` - -### 从 *datetime* 使用 *date* - -```py -from datetime import date -d = date(2020, 1, 1) -print(d) -print('当前日期:', d.today()) # 2019-12-05 -# 今天的日期对象 -today = date.today() -print("当前年份:", today.year) # 2019 -print("当前月份:", today.month) # 12 -print("当前日:", today.day) # 5 -``` - -### 使用Time对象表示时间 - -```py -from datetime import time -# time(hour = 0, minute = 0, second = 0) -a = time() -print("a =", a) -# time(hour, minute 和 second) -b = time(10, 30, 50) -print("b =", b) -# time(hour, minute 和 second) -c = time(hour=10, minute=30, second=50) -print("c =", c) -# time(hour, minute, second, microsecond) -d = time(10, 30, 50, 200555) -print("d =", d) -``` - -输出: -a = 00:00:00 -b = 10:30:50 -c = 10:30:50 -d = 10:30:50.200555 - -### 计算两个时间点之间的差异 - -```py -today = date(year=2019, month=12, day=5) -new_year = date(year=2020, month=1, day=1) -time_left_for_newyear = new_year - today -# 距离新年的时间: 27 days, 0:00:00 -print('距离新年的时间: ', time_left_for_newyear) - -t1 = datetime(year = 2019, month = 12, day = 5, hour = 0, minute = 59, second = 0) -t2 = datetime(year = 2020, month = 1, day = 1, hour = 0, minute = 0, second = 0) -diff = t2 - t1 -print('距离新年的时间:', diff) # 距离新年的时间: 26 days, 23: 01: 00 -``` - -### 使用 *timedelta* 计算两个时间点之间的差异 - -```py -from datetime import timedelta -t1 = timedelta(weeks=12, days=10, hours=4, seconds=20) -t2 = timedelta(days=7, hours=5, minutes=3, seconds=30) -t3 = t1 - t2 -print("t3 =", t3) -``` - -```sh -date_string = 5 December, 2019 -date_object = 2019-12-05 00:00:00 -t3 = 86 days, 22:56:50 -``` - -🌕 你太了不起了。你在通往卓越的道路上已经前进了16步。现在做一些练习锻炼你的大脑和肌肉。 - -## 💻 练习 - 第16天 - -1. 从datetime模块获取当前的日、月、年、小时、分钟和时间戳 -2. 使用此格式格式化当前日期:"%m/%d/%Y, %H:%M:%S" -3. 今天是2019年12月5日。将此时间字符串转换为时间。 -4. 计算现在和新年之间的时间差。 -5. 计算1970年1月1日和现在之间的时间差。 -6. 思考,你可以将datetime模块用于什么?例如: - - 时间序列分析 - - 获取应用程序中任何活动的时间戳 - - 在博客上添加帖子 - -🎉 恭喜!🎉 - -[<< 第15天](./15_Day_Python_type_errors/15_python_type_errors_cn.md) | [第17天 >>](./17_Day_Exception_handling/17_exception_handling_cn.md) \ No newline at end of file +# 30天Python编程挑战:第16天 - Python日期时间 + +- [第16天](#-第16天) + - [Python *datetime*](#python-datetime) + - [获取 *datetime* 信息](#获取-datetime-信息) + - [使用 *strftime* 格式化日期输出](#使用-strftime-格式化日期输出) + - [使用 *strptime* 将字符串转换为时间](#使用-strptime-将字符串转换为时间) + - [从 *datetime* 使用 *date*](#从-datetime-使用-date) + - [使用Time对象表示时间](#使用time对象表示时间) + - [计算两个时间点之间的差异](#计算两个时间点之间的差异) + - [使用 *timedelta* 计算两个时间点之间的差异](#使用-timedelta-计算两个时间点之间的差异) + - [💻 练习 - 第16天](#-练习---第16天) + +# 📘 第16天 + +## Python *datetime* + +Python有一个 _datetime_ 模块用于处理日期和时间。 + +```py +import datetime +print(dir(datetime)) +['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo'] +``` + +通过dir或help内置命令,可以了解特定模块中可用的函数。如你所见,datetime模块中有许多函数,但我们将重点关注 _date_、_datetime_、_time_ 和 _timedelta_。让我们一个一个地看。 + +### 获取 *datetime* 信息 + +```py +from datetime import datetime +now = datetime.now() +print(now) # 2021-07-08 07:34:46.549883 +day = now.day # 8 +month = now.month # 7 +year = now.year # 2021 +hour = now.hour # 7 +minute = now.minute # 38 +second = now.second +timestamp = now.timestamp() +print(day, month, year, hour, minute) +print('timestamp', timestamp) +print(f'{day}/{month}/{year}, {hour}:{minute}') # 8/7/2021, 7:38 +``` + +时间戳或Unix时间戳是从1970年1月1日UTC开始经过的秒数。 + +### 使用 *strftime* 格式化日期输出 + +```py +from datetime import datetime +new_year = datetime(2020, 1, 1) +print(new_year) # 2020-01-01 00:00:00 +day = new_year.day +month = new_year.month +year = new_year.year +hour = new_year.hour +minute = new_year.minute +second = new_year.second +print(day, month, year, hour, minute) #1 1 2020 0 0 +print(f'{day}/{month}/{year}, {hour}:{minute}') # 1/1/2020, 0:0 + +``` + +使用 *strftime* 方法格式化日期时间,相关文档可以在[这里](https://strftime.org/)找到。 + +```py +from datetime import datetime +# 当前日期和时间 +now = datetime.now() +t = now.strftime("%H:%M:%S") +print("时间:", t) +time_one = now.strftime("%m/%d/%Y, %H:%M:%S") +# mm/dd/YY H:M:S 格式 +print("时间一:", time_one) +time_two = now.strftime("%d/%m/%Y, %H:%M:%S") +# dd/mm/YY H:M:S 格式 +print("时间二:", time_two) +``` + +```sh +时间: 01:05:01 +时间一: 12/05/2019, 01:05:01 +时间二: 05/12/2019, 01:05:01 +``` + +以下是我们用来格式化时间的所有 _strftime_ 符号。这个模块的所有格式示例。 + +![strftime](../images/strftime.png) + +### 使用 *strptime* 将字符串转换为时间 +这里有一个[文档](https://www.programiz.com/python-programming/datetime/strptimet),有助于理解格式。 + +```py +from datetime import datetime +date_string = "5 December, 2019" +print("date_string =", date_string) +date_object = datetime.strptime(date_string, "%d %B, %Y") +print("date_object =", date_object) +``` + +```sh +date_string = 5 December, 2019 +date_object = 2019-12-05 00:00:00 +``` + +### 从 *datetime* 使用 *date* + +```py +from datetime import date +d = date(2020, 1, 1) +print(d) +print('当前日期:', d.today()) # 2019-12-05 +# 今天的日期对象 +today = date.today() +print("当前年份:", today.year) # 2019 +print("当前月份:", today.month) # 12 +print("当前日:", today.day) # 5 +``` + +### 使用Time对象表示时间 + +```py +from datetime import time +# time(hour = 0, minute = 0, second = 0) +a = time() +print("a =", a) +# time(hour, minute 和 second) +b = time(10, 30, 50) +print("b =", b) +# time(hour, minute 和 second) +c = time(hour=10, minute=30, second=50) +print("c =", c) +# time(hour, minute, second, microsecond) +d = time(10, 30, 50, 200555) +print("d =", d) +``` + +输出: +a = 00:00:00 +b = 10:30:50 +c = 10:30:50 +d = 10:30:50.200555 + +### 计算两个时间点之间的差异 + +```py +today = date(year=2019, month=12, day=5) +new_year = date(year=2020, month=1, day=1) +time_left_for_newyear = new_year - today +# 距离新年的时间: 27 days, 0:00:00 +print('距离新年的时间: ', time_left_for_newyear) + +t1 = datetime(year = 2019, month = 12, day = 5, hour = 0, minute = 59, second = 0) +t2 = datetime(year = 2020, month = 1, day = 1, hour = 0, minute = 0, second = 0) +diff = t2 - t1 +print('距离新年的时间:', diff) # 距离新年的时间: 26 days, 23: 01: 00 +``` + +### 使用 *timedelta* 计算两个时间点之间的差异 + +```py +from datetime import timedelta +t1 = timedelta(weeks=12, days=10, hours=4, seconds=20) +t2 = timedelta(days=7, hours=5, minutes=3, seconds=30) +t3 = t1 - t2 +print("t3 =", t3) +``` + +```sh +date_string = 5 December, 2019 +date_object = 2019-12-05 00:00:00 +t3 = 86 days, 22:56:50 +``` + +🌕 你太了不起了。你在通往卓越的道路上已经前进了16步。现在做一些练习锻炼你的大脑和肌肉。 + +## 💻 练习 - 第16天 + +1. 从datetime模块获取当前的日、月、年、小时、分钟和时间戳 +2. 使用此格式格式化当前日期:"%m/%d/%Y, %H:%M:%S" +3. 今天是2019年12月5日。将此时间字符串转换为时间。 +4. 计算现在和新年之间的时间差。 +5. 计算1970年1月1日和现在之间的时间差。 +6. 思考,你可以将datetime模块用于什么?例如: + - 时间序列分析 + - 获取应用程序中任何活动的时间戳 + - 在博客上添加帖子 + +🎉 恭喜!🎉 + +[<< 第 15 天](./15_python_type_errors_cn.md) | [第 17 天 >>](./17_exception_handling_cn.md) \ No newline at end of file diff --git a/Chinese/17_exception_handling_cn.md b/Chinese/17_exception_handling_cn.md index 4542c7f11..28076693b 100644 --- a/Chinese/17_exception_handling_cn.md +++ b/Chinese/17_exception_handling_cn.md @@ -1,285 +1,285 @@ -# 30天Python编程挑战:第17天 - 异常处理 - -- [第17天](#-第17天) - - [异常处理](#异常处理) - - [Python中的打包和解包参数](#python中的打包和解包参数) - - [解包](#解包) - - [解包列表](#解包列表) - - [解包字典](#解包字典) - - [打包](#打包) - - [打包列表](#打包列表) - - [打包字典](#打包字典) - - [Python中的展开](#python中的展开) - - [枚举](#枚举) - - [Zip](#zip) - - [练习:第17天](#练习第17天) - -# 📘 第17天 - -## 异常处理 - -Python使用 _try_ 和 _except_ 优雅地处理错误。优雅的退出(或优雅的错误处理)是一种简单的编程习惯 - 程序检测到严重的错误条件并"优雅地退出",即以受控的方式处理结果。通常,程序会在优雅退出时向终端或日志打印描述性错误消息,这使我们的应用程序更加健壮。异常的原因通常是程序本身之外的因素,例如错误的输入、错误的文件名、找不到文件、IO设备故障等。优雅的错误处理可以防止我们的应用程序崩溃。 - -我们在前一部分已经介绍了不同类型的Python _错误_。如果我们在程序中使用 _try_ 和 _except_,那么这些块中就不会引发错误。 - -![Try and Except](../images/try_except.png) - -```py -try: - # 如果一切正常,执行这个块中的代码 -except: - # 如果出错,执行这个块中的代码 -``` - -**示例:** - -```py -try: - print(10 + '5') -except: - print('出现了一些错误') -``` - -在上面的例子中,第二个操作数是一个字符串。我们可以将其更改为float或int,使其能够与数字相加。但如果不做任何更改,第二个块 _except_ 将被执行。 - -**示例:** - -```py -try: - name = input('输入你的名字:') - year_born = input('你出生的年份:') - age = 2019 - year_born - print(f'你是{name}. 你的年龄是{age}.') -except: - print('出现了一些错误') -``` - -```sh -出现了一些错误 -``` - -在上面的例子中,异常块将运行,但我们不知道具体的问题是什么。为了分析问题,我们可以使用不同的错误类型配合except。 - -在下面的例子中,它将处理错误,并且告诉我们引发了什么类型的错误。 - -```py -try: - name = input('输入你的名字:') - year_born = input('你出生的年份:') - age = 2019 - year_born - print(f'你是{name}. 你的年龄是{age}.') -except TypeError: - print('发生了类型错误') -except ValueError: - print('发生了值错误') -except ZeroDivisionError: - print('发生了除零错误') -``` - -```sh -输入你的名字:Asabeneh -你出生的年份:1920 -发生了类型错误 -``` - -在上述代码中,输出将是 _TypeError_。 -现在,让我们添加一个额外的块: - -```py -try: - name = input('输入你的名字:') - year_born = input('你出生的年份:') - age = 2019 - int(year_born) - print(f'你是{name}. 你的年龄是{age}.') -except TypeError: - print('发生了类型错误') -except ValueError: - print('发生了值错误') -except ZeroDivisionError: - print('发生了除零错误') -else: - print('我通常与try块一起运行') -finally: - print('我总是运行。') -``` - -```sh -输入你的名字:Asabeneh -你出生的年份:1920 -你是Asabeneh. 你的年龄是99. -我通常与try块一起运行 -我总是运行。 -``` - -也可以将上述代码简化如下: - -```py -try: - name = input('输入你的名字:') - year_born = input('你出生的年份:') - age = 2019 - int(year_born) - print(f'你是{name}. 你的年龄是{age}.') -except Exception as e: - print(e) -``` - -## Python中的打包和解包参数 - -我们使用两个操作符: - -- \* 用于元组 -- \*\* 用于字典 - -让我们看一个例子。假设函数只接受参数,但我们有一个列表。我们可以解包列表并将其转换为参数。 - -### 解包 - -#### 解包列表 - -```py -def sum_of_five_nums(a, b, c, d, e): - return a + b + c + d + e - -lst = [1, 2, 3, 4, 5] -print(sum_of_five_nums(lst)) # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e' -``` - -当我们运行这段代码时,会引发错误,因为这个函数接受数字(而不是列表)作为参数。让我们解包/解构这个列表。 - -```py -def sum_of_five_nums(a, b, c, d, e): - return a + b + c + d + e - -lst = [1, 2, 3, 4, 5] -print(sum_of_five_nums(*lst)) # 15 -``` - -我们也可以在内置的range函数中使用解包,该函数需要一个起始和结束参数。 - -```py -numbers = range(2, 7) # 正常调用,使用单独的参数 -print(list(numbers)) # [2, 3, 4, 5, 6] -args = [2, 7] -numbers = range(*args) # 使用从列表解包的参数调用 -print(numbers) # [2, 3, 4, 5,6] -``` - -列表或元组也可以这样解包: - -```py -countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] -fin, sw, nor, *rest = countries -print(fin, sw, nor, rest) # Finland Sweden Norway ['Denmark', 'Iceland'] -numbers = [1, 2, 3, 4, 5, 6, 7] -one, *middle, last = numbers -print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7 -``` - -#### 解包字典 - -```py -def unpacking_person_info(name, country, city, age): - return f'{name}住在{country}的{city}。他{age}岁。' -dct = {'name':'Asabeneh', 'country':'Finland', 'city':'Helsinki', 'age':250} -print(unpacking_person_info(**dct)) # Asabeneh住在Finland的Helsinki。他250岁。 -``` - -### 打包 - -有时候我们不知道需要向Python函数传递多少个参数。我们可以使用打包方法让我们的函数接受无限数量或任意数量的参数。 - -### 打包列表 - -```py -def sum_all(*args): - s = 0 - for i in args: - s += i - return s -print(sum_all(1, 2, 3)) # 6 -print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28 -``` - -#### 打包字典 - -```py -def packing_person_info(**kwargs): - # 检查kwargs的类型,它是一个字典类型 - # print(type(kwargs)) - # 打印字典项 - for key in kwargs: - print(f"{key} = {kwargs[key]}") - return kwargs - -print(packing_person_info(name="Asabeneh", - country="Finland", city="Helsinki", age=250)) -``` - -```sh -name = Asabeneh -country = Finland -city = Helsinki -age = 250 -{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -``` - -## Python中的展开 - -与JavaScript类似,Python中也可以进行展开操作。让我们通过下面的例子来看看: - -```py -lst_one = [1, 2, 3] -lst_two = [4, 5, 6, 7] -lst = [0, *lst_one, *lst_two] -print(lst) # [0, 1, 2, 3, 4, 5, 6, 7] -``` - -## 枚举 - -如果我们对列表的索引感兴趣,我们使用enumerate内置函数。 - -```py -for index, item in enumerate([20, 30, 40]): - print(index, item) -``` - -```py -for index, i in enumerate(countries): - print('hi') - if i == 'Finland': - print('国家 {i} 位于索引 {index}') -``` - -```sh -0 20 -1 30 -2 40 -``` - -## Zip - -有时,我们可能需要将列表组合起来。看看以下示例: - -```py -fruits = ['banana', 'orange', 'mango', 'lemon', 'lime'] -vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] -fruits_and_veges = [] -for f, v in zip(fruits, vegetables): - fruits_and_veges.append({'fruit':f, 'veg':v}) - -print(fruits_and_veges) -``` - -```sh -[{'fruit': 'banana', 'veg': 'Tomato'}, {'fruit': 'orange', 'veg': 'Potato'}, {'fruit': 'mango', 'veg': 'Cabbage'}, {'fruit': 'lemon', 'veg': 'Onion'}, {'fruit': 'lime', 'veg': 'Carrot'}] -``` - -## 练习:第17天 - -1. 为名为 _countries_data.py_ 的文件中的数据创建一个名为 _countries.py_ 的函数。 - - 创建一个函数,找出十大使用的语言 - - 创建一个函数,找出十大人口最多的国家 - -🎉 恭喜!🎉 - -[<< 第16天](./16_Day_Python_date_time/16_python_datetime_cn.md) | [第18天 >>](./18_Day_Regular_expressions/18_regular_expressions_cn.md) \ No newline at end of file +# 30天Python编程挑战:第17天 - 异常处理 + +- [第17天](#-第17天) + - [异常处理](#异常处理) + - [Python中的打包和解包参数](#python中的打包和解包参数) + - [解包](#解包) + - [解包列表](#解包列表) + - [解包字典](#解包字典) + - [打包](#打包) + - [打包列表](#打包列表) + - [打包字典](#打包字典) + - [Python中的展开](#python中的展开) + - [枚举](#枚举) + - [Zip](#zip) + - [练习:第17天](#练习第17天) + +# 📘 第17天 + +## 异常处理 + +Python使用 _try_ 和 _except_ 优雅地处理错误。优雅的退出(或优雅的错误处理)是一种简单的编程习惯 - 程序检测到严重的错误条件并"优雅地退出",即以受控的方式处理结果。通常,程序会在优雅退出时向终端或日志打印描述性错误消息,这使我们的应用程序更加健壮。异常的原因通常是程序本身之外的因素,例如错误的输入、错误的文件名、找不到文件、IO设备故障等。优雅的错误处理可以防止我们的应用程序崩溃。 + +我们在前一部分已经介绍了不同类型的Python _错误_。如果我们在程序中使用 _try_ 和 _except_,那么这些块中就不会引发错误。 + +![Try and Except](../images/try_except.png) + +```py +try: + # 如果一切正常,执行这个块中的代码 +except: + # 如果出错,执行这个块中的代码 +``` + +**示例:** + +```py +try: + print(10 + '5') +except: + print('出现了一些错误') +``` + +在上面的例子中,第二个操作数是一个字符串。我们可以将其更改为float或int,使其能够与数字相加。但如果不做任何更改,第二个块 _except_ 将被执行。 + +**示例:** + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - year_born + print(f'你是{name}. 你的年龄是{age}.') +except: + print('出现了一些错误') +``` + +```sh +出现了一些错误 +``` + +在上面的例子中,异常块将运行,但我们不知道具体的问题是什么。为了分析问题,我们可以使用不同的错误类型配合except。 + +在下面的例子中,它将处理错误,并且告诉我们引发了什么类型的错误。 + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - year_born + print(f'你是{name}. 你的年龄是{age}.') +except TypeError: + print('发生了类型错误') +except ValueError: + print('发生了值错误') +except ZeroDivisionError: + print('发生了除零错误') +``` + +```sh +输入你的名字:Asabeneh +你出生的年份:1920 +发生了类型错误 +``` + +在上述代码中,输出将是 _TypeError_。 +现在,让我们添加一个额外的块: + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - int(year_born) + print(f'你是{name}. 你的年龄是{age}.') +except TypeError: + print('发生了类型错误') +except ValueError: + print('发生了值错误') +except ZeroDivisionError: + print('发生了除零错误') +else: + print('我通常与try块一起运行') +finally: + print('我总是运行。') +``` + +```sh +输入你的名字:Asabeneh +你出生的年份:1920 +你是Asabeneh. 你的年龄是99. +我通常与try块一起运行 +我总是运行。 +``` + +也可以将上述代码简化如下: + +```py +try: + name = input('输入你的名字:') + year_born = input('你出生的年份:') + age = 2019 - int(year_born) + print(f'你是{name}. 你的年龄是{age}.') +except Exception as e: + print(e) +``` + +## Python中的打包和解包参数 + +我们使用两个操作符: + +- \* 用于元组 +- \*\* 用于字典 + +让我们看一个例子。假设函数只接受参数,但我们有一个列表。我们可以解包列表并将其转换为参数。 + +### 解包 + +#### 解包列表 + +```py +def sum_of_five_nums(a, b, c, d, e): + return a + b + c + d + e + +lst = [1, 2, 3, 4, 5] +print(sum_of_five_nums(lst)) # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e' +``` + +当我们运行这段代码时,会引发错误,因为这个函数接受数字(而不是列表)作为参数。让我们解包/解构这个列表。 + +```py +def sum_of_five_nums(a, b, c, d, e): + return a + b + c + d + e + +lst = [1, 2, 3, 4, 5] +print(sum_of_five_nums(*lst)) # 15 +``` + +我们也可以在内置的range函数中使用解包,该函数需要一个起始和结束参数。 + +```py +numbers = range(2, 7) # 正常调用,使用单独的参数 +print(list(numbers)) # [2, 3, 4, 5, 6] +args = [2, 7] +numbers = range(*args) # 使用从列表解包的参数调用 +print(numbers) # [2, 3, 4, 5,6] +``` + +列表或元组也可以这样解包: + +```py +countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] +fin, sw, nor, *rest = countries +print(fin, sw, nor, rest) # Finland Sweden Norway ['Denmark', 'Iceland'] +numbers = [1, 2, 3, 4, 5, 6, 7] +one, *middle, last = numbers +print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7 +``` + +#### 解包字典 + +```py +def unpacking_person_info(name, country, city, age): + return f'{name}住在{country}的{city}。他{age}岁。' +dct = {'name':'Asabeneh', 'country':'Finland', 'city':'Helsinki', 'age':250} +print(unpacking_person_info(**dct)) # Asabeneh住在Finland的Helsinki。他250岁。 +``` + +### 打包 + +有时候我们不知道需要向Python函数传递多少个参数。我们可以使用打包方法让我们的函数接受无限数量或任意数量的参数。 + +### 打包列表 + +```py +def sum_all(*args): + s = 0 + for i in args: + s += i + return s +print(sum_all(1, 2, 3)) # 6 +print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28 +``` + +#### 打包字典 + +```py +def packing_person_info(**kwargs): + # 检查kwargs的类型,它是一个字典类型 + # print(type(kwargs)) + # 打印字典项 + for key in kwargs: + print(f"{key} = {kwargs[key]}") + return kwargs + +print(packing_person_info(name="Asabeneh", + country="Finland", city="Helsinki", age=250)) +``` + +```sh +name = Asabeneh +country = Finland +city = Helsinki +age = 250 +{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +``` + +## Python中的展开 + +与JavaScript类似,Python中也可以进行展开操作。让我们通过下面的例子来看看: + +```py +lst_one = [1, 2, 3] +lst_two = [4, 5, 6, 7] +lst = [0, *lst_one, *lst_two] +print(lst) # [0, 1, 2, 3, 4, 5, 6, 7] +``` + +## 枚举 + +如果我们对列表的索引感兴趣,我们使用enumerate内置函数。 + +```py +for index, item in enumerate([20, 30, 40]): + print(index, item) +``` + +```py +for index, i in enumerate(countries): + print('hi') + if i == 'Finland': + print('国家 {i} 位于索引 {index}') +``` + +```sh +0 20 +1 30 +2 40 +``` + +## Zip + +有时,我们可能需要将列表组合起来。看看以下示例: + +```py +fruits = ['banana', 'orange', 'mango', 'lemon', 'lime'] +vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] +fruits_and_veges = [] +for f, v in zip(fruits, vegetables): + fruits_and_veges.append({'fruit':f, 'veg':v}) + +print(fruits_and_veges) +``` + +```sh +[{'fruit': 'banana', 'veg': 'Tomato'}, {'fruit': 'orange', 'veg': 'Potato'}, {'fruit': 'mango', 'veg': 'Cabbage'}, {'fruit': 'lemon', 'veg': 'Onion'}, {'fruit': 'lime', 'veg': 'Carrot'}] +``` + +## 练习:第17天 + +1. 为名为 _countries_data.py_ 的文件中的数据创建一个名为 _countries.py_ 的函数。 + - 创建一个函数,找出十大使用的语言 + - 创建一个函数,找出十大人口最多的国家 + +🎉 恭喜!🎉 + +[<< 第 16 天](./16_python_datetime_cn.md) | [第 18 天 >>](./18_regular_expressions_cn.md) \ No newline at end of file diff --git a/Chinese/18_regular_expressions_cn.md b/Chinese/18_regular_expressions_cn.md index d7d0ee55b..53189a2e3 100644 --- a/Chinese/18_regular_expressions_cn.md +++ b/Chinese/18_regular_expressions_cn.md @@ -1,417 +1,417 @@ -# 30天Python编程挑战:第18天 - 正则表达式 - -- [第18天](#-第18天) - - [正则表达式](#正则表达式) - - [*re* 模块](#re-模块) - - [*re* 模块中的方法](#re-模块中的方法) - - [匹配](#匹配) - - [搜索](#搜索) - - [使用 *findall* 搜索所有匹配项](#使用-findall-搜索所有匹配项) - - [替换子字符串](#替换子字符串) - - [使用RegEx拆分文本](#使用regex拆分文本) - - [编写RegEx模式](#编写regex模式) - - [方括号](#方括号) - - [RegEx中的转义字符(\\)](#regex中的转义字符) - - [一次或多次(+)](#一次或多次) - - [句点(.)](#句点) - - [零次或多次(*)](#零次或多次) - - [零次或一次(?)](#零次或一次) - - [RegEx中的量词](#regex中的量词) - - [脱字符(^)](#脱字符) - - [💻 练习:第18天](#-练习第18天) - - [练习:级别1](#练习级别1) - - [练习:级别2](#练习级别2) - - [练习:级别3](#练习级别3) - -# 📘 第18天 - -## 正则表达式 - -正则表达式(RegEx)是一种特殊的文本字符串,有助于在数据中查找模式。RegEx可用于检查不同数据类型中是否存在某种模式。要在Python中使用RegEx,首先我们应该导入RegEx模块,该模块被称为*re*。 - -### *re* 模块 - -导入模块后,我们可以使用它来检测或查找模式。 - -```py -import re -``` - -### *re* 模块中的方法 - -要查找模式,我们使用不同的*re*字符集,这些字符集允许在字符串中搜索匹配项。 - -- *re.match()*:只在字符串的第一行开头搜索,如果找到则返回匹配的对象,否则返回None。 -- *re.search*:如果字符串中的任何地方(包括多行字符串)有匹配项,则返回匹配对象。 -- *re.findall*:返回包含所有匹配项的列表。 -- *re.split*:接受一个字符串,在匹配点处分割,返回一个列表。 -- *re.sub*:替换字符串中的一个或多个匹配项。 - -#### 匹配 - -```py -# 语法 -re.match(substring, string, re.I) -# substring是一个字符串或模式,string是我们查找模式的文本,re.I是忽略大小写 -``` - -```py -import re - -txt = 'I love to teach python and javaScript' -# 它返回一个带有span和match的对象 -match = re.match('I love to teach', txt, re.I) -print(match) # -# 我们可以使用span获取匹配的起始和结束位置,作为元组 -span = match.span() -print(span) # (0, 15) -# 让我们从span中找到起始和结束位置 -start, end = span -print(start, end) # 0, 15 -substring = txt[start:end] -print(substring) # I love to teach -``` - -从上面的例子可以看出,我们正在寻找的模式(或我们正在寻找的子字符串)是*I love to teach*。match函数**只有**在文本以该模式开头时才会返回一个对象。 - -```py -import re - -txt = 'I love to teach python and javaScript' -match = re.match('I like to teach', txt, re.I) -print(match) # None -``` - -该字符串不以*I like to teach*开头,因此没有匹配,match方法返回None。 - -#### 搜索 - -```py -# 语法 -re.match(substring, string, re.I) -# substring是一个模式,string是我们查找模式的文本,re.I是忽略大小写标志 -``` - -```py -import re - -txt = '''Python is the most beautiful language that a human being has ever created. -I recommend python for a first programming language''' - -# 它返回一个带有span和match的对象 -match = re.search('first', txt, re.I) -print(match) # -# 我们可以使用span获取匹配的起始和结束位置,作为元组 -span = match.span() -print(span) # (100, 105) -# 让我们从span中找到起始和结束位置 -start, end = span -print(start, end) # 100 105 -substring = txt[start:end] -print(substring) # first -``` - -如你所见,search比match好得多,因为它可以在整个文本中查找模式。Search返回找到的第一个匹配项的匹配对象,否则返回*None*。更好的*re*函数是*findall*。此函数检查整个字符串中的模式,并将所有匹配项作为列表返回。 - -#### 使用 *findall* 搜索所有匹配项 - -*findall()* 将所有匹配项作为列表返回 - -```py -txt = '''Python is the most beautiful language that a human being has ever created. -I recommend python for a first programming language''' - -# 它返回一个列表 -matches = re.findall('language', txt, re.I) -print(matches) # ['language', 'language'] -``` - -如你所见,单词*language*在字符串中被找到了两次。让我们再练习一些。 -现在我们将在字符串中查找Python和python这两个单词: - -```py -txt = '''Python is the most beautiful language that a human being has ever created. -I recommend python for a first programming language''' - -# 它返回一个列表 -matches = re.findall('python', txt, re.I) -print(matches) # ['Python', 'python'] - -``` - -由于我们使用*re.I*,所以包含了大小写字母。如果我们没有re.I标志,那么我们将不得不以不同的方式编写我们的模式。让我们来看看: - -```py -txt = '''Python is the most beautiful language that a human being has ever created. -I recommend python for a first programming language''' - -matches = re.findall('Python|python', txt) -print(matches) # ['Python', 'python'] - -# -matches = re.findall('[Pp]ython', txt) -print(matches) # ['Python', 'python'] - -``` - -#### 替换子字符串 - -```py -txt = '''Python is the most beautiful language that a human being has ever created. -I recommend python for a first programming language''' - -match_replaced = re.sub('Python|python', 'JavaScript', txt, re.I) -print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created. -# 或者 -match_replaced = re.sub('[Pp]ython', 'JavaScript', txt, re.I) -print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created. -``` - -让我们再添加一个例子。除非我们删除%符号,否则以下字符串真的很难阅读。用空字符串替换%将清理文本。 - -```py - -txt = '''%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing. -T%he%re i%s n%o%th%ing as r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing p%e%o%ple. -I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs. -D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher?''' - -matches = re.sub('%', '', txt) -print(matches) -``` - -```sh -I am teacher and I love teaching. -There is nothing as rewarding as educating and empowering people. -I found teaching more interesting than any other jobs. Does this motivate you to be a teacher? -``` - -## 使用RegEx拆分文本 - -```py -txt = '''I am teacher and I love teaching. -There is nothing as rewarding as educating and empowering people. -I found teaching more interesting than any other jobs. -Does this motivate you to be a teacher?''' -print(re.split('\n', txt)) # 使用\n分割 - 行尾符号 -``` - -```sh -['I am teacher and I love teaching.', 'There is nothing as rewarding as educating and empowering people.', 'I found teaching more interesting than any other jobs.', 'Does this motivate you to be a teacher?'] -``` - -## 编写RegEx模式 - -要声明字符串变量,我们使用单引号或双引号。要声明RegEx变量,使用*r''*。 -以下模式仅识别小写的apple,要使其不区分大小写,我们应该重写模式或添加标志。 - -```py -import re - -regex_pattern = r'apple' -txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. ' -matches = re.findall(regex_pattern, txt) -print(matches) # ['apple'] - -# 要使其不区分大小写,添加标志' -matches = re.findall(regex_pattern, txt, re.I) -print(matches) # ['Apple', 'apple'] -# 或者我们可以使用一组字符方法 -regex_pattern = r'[Aa]pple' # 这意味着第一个字母可以是Apple或apple -matches = re.findall(regex_pattern, txt) -print(matches) # ['Apple', 'apple'] - -``` - -* []: 一组字符 - - [a-c] 表示,a或b或c - - [a-z] 表示,从a到z的任何字母 - - [A-Z] 表示,从A到Z的任何字符 - - [0-3] 表示,0或1或2或3 - - [0-9] 表示从0到9的任何数字 - - [A-Za-z0-9] 任何单个字符,即a到z,A到Z或0到9 - -### 方括号 - -让我们使用方括号练习更多的模式。记得,我们使用*re.I*作为标志,使搜索不区分大小写。 - -```py -regex_pattern = r'[Aa]pple|[Bb]anana' # 这意味着Apple或apple或Banana或banana -txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.' -matches = re.findall(regex_pattern, txt) -print(matches) # ['Apple', 'banana', 'apple', 'banana'] - -``` - -使用方括号和管道。 -```py -regex_pattern = r'[a-zA-Z0-9]' # 这个方括号表示 a 到 z, A 到 Z, 0 到 9 -txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.' -matches = re.findall(regex_pattern, txt) -print(matches) # ['A', 'p', 'p', 'l', 'e', 'a', 'n', 'd', 'b', 'a', 'n', 'a', 'n', 'a', 'a', 'r', 'e',...] - -regex_pattern = r'\d' # d 是一个特殊字符,表示数字 -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -matches = re.findall(regex_pattern, txt) -print(matches) # ['6', '2', '0', '1', '9', '8', '2', '0', '2', '1'] - -regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -matches = re.findall(regex_pattern, txt) -print(matches) # ['6', '2019', '8', '2021'] -``` - -### RegEx中的转义字符(\\) - -```py -regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -matches = re.findall(regex_pattern, txt) -print(matches) # ['6', '2019', '8', '2021'] -``` - -要查找 \ 本身,我们应该使用双倍反斜杠: -```py -regex_pattern = r'\\d' # 这意味着寻找 \d -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -matches = re.findall(regex_pattern, txt) -print(matches) # [] -``` - -当我们在字符串中没有任何与 \d 匹配的内容时,找不到任何匹配项。 - -### 一次或多次(+) - -```py -regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -matches = re.findall(regex_pattern, txt) -print(matches) # ['6', '2019', '8', '2021'] -``` - -### 句点(.) - -```py -regex_pattern = r'[a].' # 这个方括号表示 a 和 . 表示任何字符,除了新行 -txt = '''Apple and banana are fruits''' -matches = re.findall(regex_pattern, txt) -print(matches) # ['an', 'an', 'an', 'a ', 'ar'] - -regex_pattern = r'[a].+' # . 任何字符,+ 任何字符一次或多次 -matches = re.findall(regex_pattern, txt) -print(matches) # ['and banana are fruits'] -``` - -### 零次或多次(*) - -零次或多次。这个例子不太明显,所以请慢慢看。 - -```py -regex_pattern = r'[a].*' # . 任何字符,* 任何字符零次或多次 -txt = '''Apple and banana are fruits''' -matches = re.findall(regex_pattern, txt) -print(matches) # ['and banana are fruits'] -``` - -### 零次或一次(?) - -零次或一次。它可以存在,也可以不存在。 - -```py -txt = '''I am not sure if there is a convention how to write the word e-mail. -Some people write it as email others may write it as Email or E-mail.''' -regex_pattern = r'[Ee]-?mail' # ? 表示零次或一次 -matches = re.findall(regex_pattern, txt) -print(matches) # ['e-mail', 'email', 'Email', 'E-mail'] -``` - -### RegEx中的量词 - -使用大括号,我们可以指定模式的长度 -```py -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -regex_pattern = r'\d{4}' # 正好有四位数的数字 -matches = re.findall(regex_pattern, txt) -print(matches) # ['2019', '2021'] - -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -regex_pattern = r'\d{1,4}' # 1到4位数的数字 -matches = re.findall(regex_pattern, txt) -print(matches) # ['6', '2019', '8', '2021'] -``` - -### 脱字符(^) - -- 以什么开始 - -```py -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -regex_pattern = r'^This' # ^ 表示以 This 开始 -matches = re.findall(regex_pattern, txt) -print(matches) # ['This'] -``` - -- 否定 - -```py -txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' -regex_pattern = r'[^A-Za-z ]+' # ^ 在方括号内表示否定,不是A-Z,不是a-z,不是空格 -matches = re.findall(regex_pattern, txt) -print(matches) # ['6,', '2019', '8,', '2021'] -``` - -## 💻 练习:第18天 - -### 练习:级别1 - -1. 什么是正则表达式? -2. 正则表达式的变量是什么? -3. 重新创建字符串模式,这些模式可以: - a) 查找对带有*才能*的字符串的引用,在一本书中 - b) 找出日期格式为 _DD-MM-YYYY_,例如12-01-2021 - c) 找出文本中动词的时态为ing - -### 练习:级别2 - -1. 编写一个模式,用于识别表示有效Python变量名的字符串 -2. 从以下文本中清除HTML标签。 -```python -text = ''' -HTML -Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript. - -Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document. - -HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects such as interactive forms may be embedded into the rendered page. HTML provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such as and directly introduce content into the page. Other tags such as

surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page. - -HTML can embed programs written in a scripting language such as JavaScript, which affects the behavior and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web Consortium (W3C), former maintainer of the HTML and current maintainer of the CSS standards, has encouraged the use of CSS over explicit presentational HTML since 1997. -''' -``` - -### 练习:级别3 - -1. 清理以下文本。在清理过程后,计算最常见的三个单词是什么。 - -```python - - paragraph = '''I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.''' - -``` - -2. 下面的文本包含了几个电子邮件地址。编写一个可以查找或提取电子邮件地址的模式。 - -```py -email_address = ''' -asabeneh@gmail.com -alex@yahoo.com -kofi@yahoo.com -doe@arc.gov -asabeneh.com -asabeneh@gmail -alex@yahoo -''' -``` - -🎉 恭喜!🎉 - -[<< 第17天](./17_Day_Exception_handling/17_exception_handling_cn.md) | [第19天 >>](./19_Day_File_handling/19_file_handling_cn.md) \ No newline at end of file +# 30天Python编程挑战:第18天 - 正则表达式 + +- [第18天](#-第18天) + - [正则表达式](#正则表达式) + - [*re* 模块](#re-模块) + - [*re* 模块中的方法](#re-模块中的方法) + - [匹配](#匹配) + - [搜索](#搜索) + - [使用 *findall* 搜索所有匹配项](#使用-findall-搜索所有匹配项) + - [替换子字符串](#替换子字符串) + - [使用RegEx拆分文本](#使用regex拆分文本) + - [编写RegEx模式](#编写regex模式) + - [方括号](#方括号) + - [RegEx中的转义字符(\\)](#regex中的转义字符) + - [一次或多次(+)](#一次或多次) + - [句点(.)](#句点) + - [零次或多次(*)](#零次或多次) + - [零次或一次(?)](#零次或一次) + - [RegEx中的量词](#regex中的量词) + - [脱字符(^)](#脱字符) + - [💻 练习:第18天](#-练习第18天) + - [练习:级别1](#练习级别1) + - [练习:级别2](#练习级别2) + - [练习:级别3](#练习级别3) + +# 📘 第18天 + +## 正则表达式 + +正则表达式(RegEx)是一种特殊的文本字符串,有助于在数据中查找模式。RegEx可用于检查不同数据类型中是否存在某种模式。要在Python中使用RegEx,首先我们应该导入RegEx模块,该模块被称为*re*。 + +### *re* 模块 + +导入模块后,我们可以使用它来检测或查找模式。 + +```py +import re +``` + +### *re* 模块中的方法 + +要查找模式,我们使用不同的*re*字符集,这些字符集允许在字符串中搜索匹配项。 + +- *re.match()*:只在字符串的第一行开头搜索,如果找到则返回匹配的对象,否则返回None。 +- *re.search*:如果字符串中的任何地方(包括多行字符串)有匹配项,则返回匹配对象。 +- *re.findall*:返回包含所有匹配项的列表。 +- *re.split*:接受一个字符串,在匹配点处分割,返回一个列表。 +- *re.sub*:替换字符串中的一个或多个匹配项。 + +#### 匹配 + +```py +# 语法 +re.match(substring, string, re.I) +# substring是一个字符串或模式,string是我们查找模式的文本,re.I是忽略大小写 +``` + +```py +import re + +txt = 'I love to teach python and javaScript' +# 它返回一个带有span和match的对象 +match = re.match('I love to teach', txt, re.I) +print(match) # +# 我们可以使用span获取匹配的起始和结束位置,作为元组 +span = match.span() +print(span) # (0, 15) +# 让我们从span中找到起始和结束位置 +start, end = span +print(start, end) # 0, 15 +substring = txt[start:end] +print(substring) # I love to teach +``` + +从上面的例子可以看出,我们正在寻找的模式(或我们正在寻找的子字符串)是*I love to teach*。match函数**只有**在文本以该模式开头时才会返回一个对象。 + +```py +import re + +txt = 'I love to teach python and javaScript' +match = re.match('I like to teach', txt, re.I) +print(match) # None +``` + +该字符串不以*I like to teach*开头,因此没有匹配,match方法返回None。 + +#### 搜索 + +```py +# 语法 +re.match(substring, string, re.I) +# substring是一个模式,string是我们查找模式的文本,re.I是忽略大小写标志 +``` + +```py +import re + +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +# 它返回一个带有span和match的对象 +match = re.search('first', txt, re.I) +print(match) # +# 我们可以使用span获取匹配的起始和结束位置,作为元组 +span = match.span() +print(span) # (100, 105) +# 让我们从span中找到起始和结束位置 +start, end = span +print(start, end) # 100 105 +substring = txt[start:end] +print(substring) # first +``` + +如你所见,search比match好得多,因为它可以在整个文本中查找模式。Search返回找到的第一个匹配项的匹配对象,否则返回*None*。更好的*re*函数是*findall*。此函数检查整个字符串中的模式,并将所有匹配项作为列表返回。 + +#### 使用 *findall* 搜索所有匹配项 + +*findall()* 将所有匹配项作为列表返回 + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +# 它返回一个列表 +matches = re.findall('language', txt, re.I) +print(matches) # ['language', 'language'] +``` + +如你所见,单词*language*在字符串中被找到了两次。让我们再练习一些。 +现在我们将在字符串中查找Python和python这两个单词: + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +# 它返回一个列表 +matches = re.findall('python', txt, re.I) +print(matches) # ['Python', 'python'] + +``` + +由于我们使用*re.I*,所以包含了大小写字母。如果我们没有re.I标志,那么我们将不得不以不同的方式编写我们的模式。让我们来看看: + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +matches = re.findall('Python|python', txt) +print(matches) # ['Python', 'python'] + +# +matches = re.findall('[Pp]ython', txt) +print(matches) # ['Python', 'python'] + +``` + +#### 替换子字符串 + +```py +txt = '''Python is the most beautiful language that a human being has ever created. +I recommend python for a first programming language''' + +match_replaced = re.sub('Python|python', 'JavaScript', txt, re.I) +print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created. +# 或者 +match_replaced = re.sub('[Pp]ython', 'JavaScript', txt, re.I) +print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created. +``` + +让我们再添加一个例子。除非我们删除%符号,否则以下字符串真的很难阅读。用空字符串替换%将清理文本。 + +```py + +txt = '''%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing. +T%he%re i%s n%o%th%ing as r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing p%e%o%ple. +I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs. +D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher?''' + +matches = re.sub('%', '', txt) +print(matches) +``` + +```sh +I am teacher and I love teaching. +There is nothing as rewarding as educating and empowering people. +I found teaching more interesting than any other jobs. Does this motivate you to be a teacher? +``` + +## 使用RegEx拆分文本 + +```py +txt = '''I am teacher and I love teaching. +There is nothing as rewarding as educating and empowering people. +I found teaching more interesting than any other jobs. +Does this motivate you to be a teacher?''' +print(re.split('\n', txt)) # 使用\n分割 - 行尾符号 +``` + +```sh +['I am teacher and I love teaching.', 'There is nothing as rewarding as educating and empowering people.', 'I found teaching more interesting than any other jobs.', 'Does this motivate you to be a teacher?'] +``` + +## 编写RegEx模式 + +要声明字符串变量,我们使用单引号或双引号。要声明RegEx变量,使用*r''*。 +以下模式仅识别小写的apple,要使其不区分大小写,我们应该重写模式或添加标志。 + +```py +import re + +regex_pattern = r'apple' +txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. ' +matches = re.findall(regex_pattern, txt) +print(matches) # ['apple'] + +# 要使其不区分大小写,添加标志' +matches = re.findall(regex_pattern, txt, re.I) +print(matches) # ['Apple', 'apple'] +# 或者我们可以使用一组字符方法 +regex_pattern = r'[Aa]pple' # 这意味着第一个字母可以是Apple或apple +matches = re.findall(regex_pattern, txt) +print(matches) # ['Apple', 'apple'] + +``` + +* []: 一组字符 + - [a-c] 表示,a或b或c + - [a-z] 表示,从a到z的任何字母 + - [A-Z] 表示,从A到Z的任何字符 + - [0-3] 表示,0或1或2或3 + - [0-9] 表示从0到9的任何数字 + - [A-Za-z0-9] 任何单个字符,即a到z,A到Z或0到9 + +### 方括号 + +让我们使用方括号练习更多的模式。记得,我们使用*re.I*作为标志,使搜索不区分大小写。 + +```py +regex_pattern = r'[Aa]pple|[Bb]anana' # 这意味着Apple或apple或Banana或banana +txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.' +matches = re.findall(regex_pattern, txt) +print(matches) # ['Apple', 'banana', 'apple', 'banana'] + +``` + +使用方括号和管道。 +```py +regex_pattern = r'[a-zA-Z0-9]' # 这个方括号表示 a 到 z, A 到 Z, 0 到 9 +txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.' +matches = re.findall(regex_pattern, txt) +print(matches) # ['A', 'p', 'p', 'l', 'e', 'a', 'n', 'd', 'b', 'a', 'n', 'a', 'n', 'a', 'a', 'r', 'e',...] + +regex_pattern = r'\d' # d 是一个特殊字符,表示数字 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2', '0', '1', '9', '8', '2', '0', '2', '1'] + +regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +### RegEx中的转义字符(\\) + +```py +regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +要查找 \ 本身,我们应该使用双倍反斜杠: +```py +regex_pattern = r'\\d' # 这意味着寻找 \d +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # [] +``` + +当我们在字符串中没有任何与 \d 匹配的内容时,找不到任何匹配项。 + +### 一次或多次(+) + +```py +regex_pattern = r'\d+' # d 是一个特殊字符,表示数字,+ 表示一个或多个 +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +### 句点(.) + +```py +regex_pattern = r'[a].' # 这个方括号表示 a 和 . 表示任何字符,除了新行 +txt = '''Apple and banana are fruits''' +matches = re.findall(regex_pattern, txt) +print(matches) # ['an', 'an', 'an', 'a ', 'ar'] + +regex_pattern = r'[a].+' # . 任何字符,+ 任何字符一次或多次 +matches = re.findall(regex_pattern, txt) +print(matches) # ['and banana are fruits'] +``` + +### 零次或多次(*) + +零次或多次。这个例子不太明显,所以请慢慢看。 + +```py +regex_pattern = r'[a].*' # . 任何字符,* 任何字符零次或多次 +txt = '''Apple and banana are fruits''' +matches = re.findall(regex_pattern, txt) +print(matches) # ['and banana are fruits'] +``` + +### 零次或一次(?) + +零次或一次。它可以存在,也可以不存在。 + +```py +txt = '''I am not sure if there is a convention how to write the word e-mail. +Some people write it as email others may write it as Email or E-mail.''' +regex_pattern = r'[Ee]-?mail' # ? 表示零次或一次 +matches = re.findall(regex_pattern, txt) +print(matches) # ['e-mail', 'email', 'Email', 'E-mail'] +``` + +### RegEx中的量词 + +使用大括号,我们可以指定模式的长度 +```py +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'\d{4}' # 正好有四位数的数字 +matches = re.findall(regex_pattern, txt) +print(matches) # ['2019', '2021'] + +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'\d{1,4}' # 1到4位数的数字 +matches = re.findall(regex_pattern, txt) +print(matches) # ['6', '2019', '8', '2021'] +``` + +### 脱字符(^) + +- 以什么开始 + +```py +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'^This' # ^ 表示以 This 开始 +matches = re.findall(regex_pattern, txt) +print(matches) # ['This'] +``` + +- 否定 + +```py +txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021' +regex_pattern = r'[^A-Za-z ]+' # ^ 在方括号内表示否定,不是A-Z,不是a-z,不是空格 +matches = re.findall(regex_pattern, txt) +print(matches) # ['6,', '2019', '8,', '2021'] +``` + +## 💻 练习:第18天 + +### 练习:级别1 + +1. 什么是正则表达式? +2. 正则表达式的变量是什么? +3. 重新创建字符串模式,这些模式可以: + a) 查找对带有*才能*的字符串的引用,在一本书中 + b) 找出日期格式为 _DD-MM-YYYY_,例如12-01-2021 + c) 找出文本中动词的时态为ing + +### 练习:级别2 + +1. 编写一个模式,用于识别表示有效Python变量名的字符串 +2. 从以下文本中清除HTML标签。 +```python +text = ''' +HTML +Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and scripting languages such as JavaScript. + +Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document. + +HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects such as interactive forms may be embedded into the rendered page. HTML provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such as and directly introduce content into the page. Other tags such as

surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page. + +HTML can embed programs written in a scripting language such as JavaScript, which affects the behavior and content of web pages. Inclusion of CSS defines the look and layout of content. The World Wide Web Consortium (W3C), former maintainer of the HTML and current maintainer of the CSS standards, has encouraged the use of CSS over explicit presentational HTML since 1997. +''' +``` + +### 练习:级别3 + +1. 清理以下文本。在清理过程后,计算最常见的三个单词是什么。 + +```python + + paragraph = '''I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.''' + +``` + +2. 下面的文本包含了几个电子邮件地址。编写一个可以查找或提取电子邮件地址的模式。 + +```py +email_address = ''' +asabeneh@gmail.com +alex@yahoo.com +kofi@yahoo.com +doe@arc.gov +asabeneh.com +asabeneh@gmail +alex@yahoo +''' +``` + +🎉 恭喜!🎉 + +[<< 第 17 天](./17_exception_handling_cn.md) | [第 19 天 >>](./19_file_handling_cn.md) \ No newline at end of file diff --git a/Chinese/19_file_handling_cn.md b/Chinese/19_file_handling_cn.md index 4c15062b6..837369085 100644 --- a/Chinese/19_file_handling_cn.md +++ b/Chinese/19_file_handling_cn.md @@ -1,549 +1,549 @@ -# 30天Python编程挑战:第19天 - 文件处理 - -- [第19天](#-第19天) - - [文件处理](#文件处理) - - [打开文件进行读取](#打开文件进行读取) - - [打开文件进行写入和更新](#打开文件进行写入和更新) - - [删除文件](#删除文件) - - [文件类型](#文件类型) - - [带有txt扩展名的文件](#带有txt扩展名的文件) - - [带有json扩展名的文件](#带有json扩展名的文件) - - [将JSON转换为字典](#将json转换为字典) - - [将字典转换为JSON](#将字典转换为json) - - [保存为JSON文件](#保存为json文件) - - [带有csv扩展名的文件](#带有csv扩展名的文件) - - [带有xlsx扩展名的文件](#带有xlsx扩展名的文件) - - [带有xml扩展名的文件](#带有xml扩展名的文件) - - [💻 练习:第19天](#-练习第19天) - - [练习:级别1](#练习级别1) - - [练习:级别2](#练习级别2) - - [练习:级别3](#练习级别3) - -# 📘 第19天 - -## 文件处理 - -到目前为止,我们已经了解了不同的Python数据类型。我们通常在不同的文件格式中存储数据。除了处理文件外,在本节中我们还将看到不同的文件格式(.txt、.json、.xml、.csv、.tsv、.excel)。首先,让我们熟悉使用常见文件格式(.txt)处理文件。 - -文件处理是编程的重要部分,它允许我们创建、读取、更新和删除文件。在Python中,处理数据我们使用内置函数 _open()_。 - -```py -# 语法 -open('filename', mode) # mode(r, a, w, x, t, b) 可以是读取、写入、更新 -``` - -- "r" - 读取 - 默认值。打开文件进行读取,如果文件不存在则返回错误 -- "a" - 追加 - 打开文件进行追加,如果文件不存在则创建文件 -- "w" - 写入 - 打开文件进行写入,如果文件不存在则创建文件 -- "x" - 创建 - 创建指定的文件,如果文件已存在则返回错误 -- "t" - 文本 - 默认值。文本模式 -- "b" - 二进制 - 二进制模式(例如图像) - -### 打开文件进行读取 - -_open_ 的默认模式是读取,因此我们不必指定'r'或'rt'。我已经在files目录中创建并保存了一个名为reading_file_example.txt的文件。让我们看看它是如何完成的: - -```py -f = open('./files/reading_file_example.txt') -print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'> -``` - -如上例所示,我打印了打开的文件,它提供了一些关于文件的信息。已打开的文件有不同的读取方法:_read()_、_readline_、_readlines_。打开的文件必须用 _close()_ 方法关闭。 - -- _read()_:将整个文本作为字符串读取。如果我们想限制想要读取的字符数,可以通过向 *read(number)* 方法传递int值来限制。 - -```py -f = open('./files/reading_file_example.txt') -txt = f.read() -print(type(txt)) -print(txt) -f.close() -``` - -```sh -# 输出 - -This is an example to show how to open a file and read. -This is the second line of the text. -``` - -与其打印所有文本,不如打印文本文件的前10个字符。 - -```py -f = open('./files/reading_file_example.txt') -txt = f.read(10) -print(type(txt)) -print(txt) -f.close() -``` - -```sh -# 输出 - -This is an -``` - -- _readline()_:只读取第一行 - -```py -f = open('./files/reading_file_example.txt') -line = f.readline() -print(type(line)) -print(line) -f.close() -``` - -```sh -# 输出 - -This is an example to show how to open a file and read. -``` - -- _readlines()_:逐行读取所有文本,并返回一个行列表 - -```py -f = open('./files/reading_file_example.txt') -lines = f.readlines() -print(type(lines)) -print(lines) -f.close() -``` - -```sh -# 输出 - -['This is an example to show how to open a file and read.\n', 'This is the second line of the text.'] -``` - -获取所有行作为列表的另一种方法是使用 _splitlines()_: - -```py -f = open('./files/reading_file_example.txt') -lines = f.read().splitlines() -print(type(lines)) -print(lines) -f.close() -``` - -```sh -# 输出 - -['This is an example to show how to open a file and read.', 'This is the second line of the text.'] -``` - -在打开文件后,我们应该关闭它。我们很容易忘记关闭它们。有一种使用 _with_ 打开文件的新方法——它会自动关闭文件。让我们用 _with_ 方法重写前面的例子: - -```py -with open('./files/reading_file_example.txt') as f: - lines = f.read().splitlines() - print(type(lines)) - print(lines) -``` - -```sh -# 输出 - -['This is an example to show how to open a file and read.', 'This is the second line of the text.'] -``` - -### 打开文件进行写入和更新 - -要写入现有文件,我们必须向 _open()_ 函数添加模式作为参数: - -- "a" - 追加 - 将在文件末尾追加,如果文件不存在则创建一个新文件。 -- "w" - 写入 - 将覆盖任何现有内容,如果文件不存在则创建。 - -让我们在我们一直在读取的文件中追加一些文本: - -```py -with open('./files/reading_file_example.txt','a') as f: - f.write('此文本必须附加在末尾') -``` - -如果文件不存在,以下方法将创建一个新文件: - -```py -with open('./files/writing_file_example.txt','w') as f: - f.write('这段文本将被写入新创建的文件中') -``` - -### 删除文件 - -我们在前面的部分中已经看到,如何使用 _os_ 模块创建和删除目录。现在,如果我们想删除一个文件,我们也使用 _os_ 模块。 - -```py -import os -os.remove('./files/example.txt') - -``` - -如果文件不存在,remove方法将引发错误,因此最好使用条件语句: - -```py -import os -if os.path.exists('./files/example.txt'): - os.remove('./files/example.txt') -else: - print('文件不存在') -``` - -## 文件类型 - -### 带有txt扩展名的文件 - -带有 _txt_ 扩展名的文件是一种非常常见的数据形式,我们已经在前面的部分中介绍了它。让我们转到JSON文件。 - -### 带有json扩展名的文件 - -JSON代表JavaScript对象表示法。实际上,它是一个字符串化的JavaScript对象或Python字典。 - -_示例:_ - -```py -# 字典 -person_dct= { - "name":"Asabeneh", - "country":"Finland", - "city":"Helsinki", - "skills":["JavaScrip", "React","Python"] -} -# JSON: 字典的字符串形式 -person_json = "{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'React', 'Python']}" - -# 我们使用三个引号并使其多行以使其更具可读性 -person_json = '''{ - "name":"Asabeneh", - "country":"Finland", - "city":"Helsinki", - "skills":["JavaScrip", "React","Python"] -}''' -``` - -### 将JSON转换为字典 - -要将JSON更改为字典,首先我们导入json模块,然后使用 _loads_ 方法。 - -```py -import json -# JSON -person_json = '''{ - "name": "Asabeneh", - "country": "Finland", - "city": "Helsinki", - "skills": ["JavaScrip", "React", "Python"] -}''' -# 将JSON字符串更改为字典 -person_dct = json.loads(person_json) -print(type(person_dct)) -print(person_dct) -print(person_dct['name']) -``` - -```sh -# 输出 - -{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'React', 'Python']} -Asabeneh -``` - -### 将字典转换为JSON - -要将字典更改为JSON,我们使用 _dumps_ 方法。 - -```py -import json -# python字典 -person = { - "name": "Asabeneh", - "country": "Finland", - "city": "Helsinki", - "skills": ["JavaScrip", "React", "Python"] -} -# 将字典转换为JSON字符串 -person_json = json.dumps(person, indent=4) # indent可以是2, 4, 8. 它漂亮地打印了。 -print(type(person_json)) -print(person_json) -``` - -```sh -# 输出 - -{ - "name": "Asabeneh", - "country": "Finland", - "city": "Helsinki", - "skills": [ - "JavaScrip", - "React", - "Python" - ] -} -``` - -### 保存为JSON文件 - -我们也可以将我们的数据保存为JSON文件。让我们使用前面的示例保存: - -```py -import json -# python字典 -person = { - "name": "Asabeneh", - "country": "Finland", - "city": "Helsinki", - "skills": ["JavaScrip", "React", "Python"] -} -with open('./files/json_example.json', 'w', encoding='utf-8') as f: - json.dump(person, f, ensure_ascii=False, indent=4) -``` - -在上面的代码中,我们使用了编码和确保_ascii参数。这些参数是为了保存非ASCII字符,如果我们想保存非英语字符。下面是一个包含非ASCII字符的示例: - -```py -import json -# python字典 -person = { - "name": "张三", - "country": "中国", - "city": "北京", - "skills": ["JavaScript", "React", "Python"] -} -with open('./files/json_example.json', 'w', encoding='utf-8') as f: - json.dump(person, f, ensure_ascii=False, indent=4) -``` - -现在,让我们读取我们刚刚创建的json文件: - -```py -import json -with open('./files/json_example.json', 'r', encoding='utf-8') as f: - person = json.load(f) - print(person) -``` - -```sh -# 输出 -{'name': '张三', 'country': '中国', 'city': '北京', 'skills': ['JavaScript', 'React', 'Python']} -``` - -### 带有csv扩展名的文件 - -CSV代表逗号分隔值。CSV是一种简单的文件格式,用于存储表格数据,如电子表格或数据库。CSV是数据科学中非常常见的数据格式。 - -**示例:** - -```csv -"name","country","city","skills" -"Asabeneh","Finland","Helsinki","JavaScript" -``` - -**示例:** - -```py -import csv -with open('./files/csv_example.csv') as f: - csv_reader = csv.reader(f, delimiter=',') # w+ 创建文件(如果不存在) - line_count = 0 - for row in csv_reader: - if line_count == 0: - print(f'列名为: {", ".join(row)}') - line_count += 1 - else: - print(f'{row[0]}来自{row[1]}的{row[2]}。 他了解{row[3]}') - line_count += 1 - print(f'已处理{line_count}行。') -``` - -```sh -# 输出: -列名为: name, country, city, skills -Asabeneh来自Finland的Helsinki。 他了解JavaScript -已处理2行。 -``` - -我们还可以使用相同的方法将数据写入csv文件 - -```py -import csv -with open('./files/csv_example.csv', 'w', encoding='UTF8', newline='') as f: - writer = csv.writer(f) - # 写入列名 - writer.writerow(['name', 'country', 'city', 'skills']) - # 写入数据 - writer.writerow(['Asabeneh', 'Finland', 'Helsinki', 'JavaScript']) -``` - -### 带有xlsx扩展名的文件 - -要读取Excel文件,我们需要安装xlrd包。我们将使用它来读取Excel文件。 - -```py -import xlrd -excel_book = xlrd.open_workbook('sample.xls') -print(excel_book.nsheets) -print(excel_book.sheet_names) -``` - -### 带有xml扩展名的文件 - -XML是一种元标记语言,非常类似于HTML。在XML中,我们可以使用自己的标签,从而使其更加灵活。我们使用XML主要是为了结构化数据。在Python中有少量的XML库。在本部分中,我们将使用xml.etree.ElementTree模块。 - -**示例:XML** - -```xml - - - Asabeneh - Finland - Helsinki - - JavaScript - React - Python - - -``` - -我们将使用xml.etree.ElementTree模块来解析XML文件。 - -```py -import xml.etree.ElementTree as ET -tree = ET.parse('./files/xml_example.xml') -root = tree.getroot() -print('Root tag:', root.tag) -print('Attribute:', root.attrib) -for child in root: - print('字段: ', child.tag) -``` - -```sh -# 输出 -Root tag: person -Attribute: {'gender': 'female'} -字段: name -字段: country -字段: city -字段: skills -``` - -```py -import xml.etree.ElementTree as ET -tree = ET.parse('./files/xml_example.xml') -root = tree.getroot() -print('Root tag:', root.tag) -print('Attribute:', root.attrib) -for child in root: - print('字段: ', child.tag) -``` - -```sh -# 输出 -Root tag: person -Attribute: {'gender': 'female'} -字段: name -字段: country -字段: city -字段: skills -``` - -让我们获取更多细节: - -```py -import xml.etree.ElementTree as ET -tree = ET.parse('./files/xml_example.xml') -root = tree.getroot() -print('Root tag:', root.tag) -print('Attribute:', root.attrib) -for child in root: - print('field: ', child.tag) - if child.tag != 'skills': - print(child.text) - else: - for skill in child: - print(skill.text) -``` - -```sh -# 输出 -Root tag: person -Attribute: {'gender': 'female'} -field: name -Asabeneh -field: country -Finland -field: city -Helsinki -field: skills -JavaScript -React -Python -``` - -## 💻 练习:第19天 - -### 练习:级别1 - -1. 编写一个函数,该函数需要一个参数(文件名)并统计文件中单词的数量 -2. 阅读obama_speech.txt文件并计算单词数 -3. 阅读michelle_obama_speech.txt文件并计算单词数 -4. 阅读donald_speech.txt文件并计算单词数 -5. 阅读melina_trump_speech.txt文件并计算单词数 - -### 练习:级别2 - -1. 从编程语言中提取所有Python目录文件: - a) 处理30DaysOfPython文件夹,提取出所有python文件,并将它们的名称存储在files_list.txt文件中 - b) 创建一个名为find_python.py的脚本,可以通过命令行运行它 - c) 添加一个名为--version的标志来处理命令行参数 - -### 练习:级别3 - -1. 使用以下数据集创建一个JSON文件: - ```py - python_libraries = [ - { - "库名称": "Django", - "创建者": "Adrian Holovaty", - "首次发布年份": 2005, - "版本": "4.0.2", - "用途": "Web开发", - "描述": "Django让您可以快速构建更好的Web应用程序。" - }, - { - "库名称": "Flask", - "创建者": "Armin Ronacher", - "首次发布年份": 2010, - "版本": "2.0.2", - "用途": "Web开发", - "描述": "Flask是一个轻量级的WSGI Web应用程序框架。" - }, - { - "库名称": "NumPy", - "创建者": "Travis Oliphant", - "首次发布年份": 2005, - "版本": "1.22.0", - "用途": "科学计算", - "描述": "NumPy是Python中用于科学计算的基础包。" - }, - { - "库名称": "Pandas", - "创建者": "Wes McKinney", - "首次发布年份": 2008, - "版本": "1.4.0", - "用途": "数据分析", - "描述": "pandas是一个用于数据分析和数据操作的开源库。" - }, - { - "库名称": "Matplotlib", - "创建者": "John D. Hunter", - "首次发布年份": 2003, - "版本": "3.5.1", - "用途": "数据可视化", - "描述": "Matplotlib是一个用于在Python中创建静态、动画和交互式可视化的库。" - } - ] - ``` - -🎉 恭喜!🎉 - -[<< 第18天](./18_Day_Regular_expressions/18_regular_expressions_cn.md) | [第20天 >>](./20_Day_Python_package_manager/20_python_package_manager_cn.md) \ No newline at end of file +# 30天Python编程挑战:第19天 - 文件处理 + +- [第19天](#-第19天) + - [文件处理](#文件处理) + - [打开文件进行读取](#打开文件进行读取) + - [打开文件进行写入和更新](#打开文件进行写入和更新) + - [删除文件](#删除文件) + - [文件类型](#文件类型) + - [带有txt扩展名的文件](#带有txt扩展名的文件) + - [带有json扩展名的文件](#带有json扩展名的文件) + - [将JSON转换为字典](#将json转换为字典) + - [将字典转换为JSON](#将字典转换为json) + - [保存为JSON文件](#保存为json文件) + - [带有csv扩展名的文件](#带有csv扩展名的文件) + - [带有xlsx扩展名的文件](#带有xlsx扩展名的文件) + - [带有xml扩展名的文件](#带有xml扩展名的文件) + - [💻 练习:第19天](#-练习第19天) + - [练习:级别1](#练习级别1) + - [练习:级别2](#练习级别2) + - [练习:级别3](#练习级别3) + +# 📘 第19天 + +## 文件处理 + +到目前为止,我们已经了解了不同的Python数据类型。我们通常在不同的文件格式中存储数据。除了处理文件外,在本节中我们还将看到不同的文件格式(.txt、.json、.xml、.csv、.tsv、.excel)。首先,让我们熟悉使用常见文件格式(.txt)处理文件。 + +文件处理是编程的重要部分,它允许我们创建、读取、更新和删除文件。在Python中,处理数据我们使用内置函数 _open()_。 + +```py +# 语法 +open('filename', mode) # mode(r, a, w, x, t, b) 可以是读取、写入、更新 +``` + +- "r" - 读取 - 默认值。打开文件进行读取,如果文件不存在则返回错误 +- "a" - 追加 - 打开文件进行追加,如果文件不存在则创建文件 +- "w" - 写入 - 打开文件进行写入,如果文件不存在则创建文件 +- "x" - 创建 - 创建指定的文件,如果文件已存在则返回错误 +- "t" - 文本 - 默认值。文本模式 +- "b" - 二进制 - 二进制模式(例如图像) + +### 打开文件进行读取 + +_open_ 的默认模式是读取,因此我们不必指定'r'或'rt'。我已经在files目录中创建并保存了一个名为reading_file_example.txt的文件。让我们看看它是如何完成的: + +```py +f = open('./files/reading_file_example.txt') +print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'> +``` + +如上例所示,我打印了打开的文件,它提供了一些关于文件的信息。已打开的文件有不同的读取方法:_read()_、_readline_、_readlines_。打开的文件必须用 _close()_ 方法关闭。 + +- _read()_:将整个文本作为字符串读取。如果我们想限制想要读取的字符数,可以通过向 *read(number)* 方法传递int值来限制。 + +```py +f = open('./files/reading_file_example.txt') +txt = f.read() +print(type(txt)) +print(txt) +f.close() +``` + +```sh +# 输出 + +This is an example to show how to open a file and read. +This is the second line of the text. +``` + +与其打印所有文本,不如打印文本文件的前10个字符。 + +```py +f = open('./files/reading_file_example.txt') +txt = f.read(10) +print(type(txt)) +print(txt) +f.close() +``` + +```sh +# 输出 + +This is an +``` + +- _readline()_:只读取第一行 + +```py +f = open('./files/reading_file_example.txt') +line = f.readline() +print(type(line)) +print(line) +f.close() +``` + +```sh +# 输出 + +This is an example to show how to open a file and read. +``` + +- _readlines()_:逐行读取所有文本,并返回一个行列表 + +```py +f = open('./files/reading_file_example.txt') +lines = f.readlines() +print(type(lines)) +print(lines) +f.close() +``` + +```sh +# 输出 + +['This is an example to show how to open a file and read.\n', 'This is the second line of the text.'] +``` + +获取所有行作为列表的另一种方法是使用 _splitlines()_: + +```py +f = open('./files/reading_file_example.txt') +lines = f.read().splitlines() +print(type(lines)) +print(lines) +f.close() +``` + +```sh +# 输出 + +['This is an example to show how to open a file and read.', 'This is the second line of the text.'] +``` + +在打开文件后,我们应该关闭它。我们很容易忘记关闭它们。有一种使用 _with_ 打开文件的新方法——它会自动关闭文件。让我们用 _with_ 方法重写前面的例子: + +```py +with open('./files/reading_file_example.txt') as f: + lines = f.read().splitlines() + print(type(lines)) + print(lines) +``` + +```sh +# 输出 + +['This is an example to show how to open a file and read.', 'This is the second line of the text.'] +``` + +### 打开文件进行写入和更新 + +要写入现有文件,我们必须向 _open()_ 函数添加模式作为参数: + +- "a" - 追加 - 将在文件末尾追加,如果文件不存在则创建一个新文件。 +- "w" - 写入 - 将覆盖任何现有内容,如果文件不存在则创建。 + +让我们在我们一直在读取的文件中追加一些文本: + +```py +with open('./files/reading_file_example.txt','a') as f: + f.write('此文本必须附加在末尾') +``` + +如果文件不存在,以下方法将创建一个新文件: + +```py +with open('./files/writing_file_example.txt','w') as f: + f.write('这段文本将被写入新创建的文件中') +``` + +### 删除文件 + +我们在前面的部分中已经看到,如何使用 _os_ 模块创建和删除目录。现在,如果我们想删除一个文件,我们也使用 _os_ 模块。 + +```py +import os +os.remove('./files/example.txt') + +``` + +如果文件不存在,remove方法将引发错误,因此最好使用条件语句: + +```py +import os +if os.path.exists('./files/example.txt'): + os.remove('./files/example.txt') +else: + print('文件不存在') +``` + +## 文件类型 + +### 带有txt扩展名的文件 + +带有 _txt_ 扩展名的文件是一种非常常见的数据形式,我们已经在前面的部分中介绍了它。让我们转到JSON文件。 + +### 带有json扩展名的文件 + +JSON代表JavaScript对象表示法。实际上,它是一个字符串化的JavaScript对象或Python字典。 + +_示例:_ + +```py +# 字典 +person_dct= { + "name":"Asabeneh", + "country":"Finland", + "city":"Helsinki", + "skills":["JavaScrip", "React","Python"] +} +# JSON: 字典的字符串形式 +person_json = "{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'React', 'Python']}" + +# 我们使用三个引号并使其多行以使其更具可读性 +person_json = '''{ + "name":"Asabeneh", + "country":"Finland", + "city":"Helsinki", + "skills":["JavaScrip", "React","Python"] +}''' +``` + +### 将JSON转换为字典 + +要将JSON更改为字典,首先我们导入json模块,然后使用 _loads_ 方法。 + +```py +import json +# JSON +person_json = '''{ + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": ["JavaScrip", "React", "Python"] +}''' +# 将JSON字符串更改为字典 +person_dct = json.loads(person_json) +print(type(person_dct)) +print(person_dct) +print(person_dct['name']) +``` + +```sh +# 输出 + +{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'React', 'Python']} +Asabeneh +``` + +### 将字典转换为JSON + +要将字典更改为JSON,我们使用 _dumps_ 方法。 + +```py +import json +# python字典 +person = { + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": ["JavaScrip", "React", "Python"] +} +# 将字典转换为JSON字符串 +person_json = json.dumps(person, indent=4) # indent可以是2, 4, 8. 它漂亮地打印了。 +print(type(person_json)) +print(person_json) +``` + +```sh +# 输出 + +{ + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": [ + "JavaScrip", + "React", + "Python" + ] +} +``` + +### 保存为JSON文件 + +我们也可以将我们的数据保存为JSON文件。让我们使用前面的示例保存: + +```py +import json +# python字典 +person = { + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "skills": ["JavaScrip", "React", "Python"] +} +with open('./files/json_example.json', 'w', encoding='utf-8') as f: + json.dump(person, f, ensure_ascii=False, indent=4) +``` + +在上面的代码中,我们使用了编码和确保_ascii参数。这些参数是为了保存非ASCII字符,如果我们想保存非英语字符。下面是一个包含非ASCII字符的示例: + +```py +import json +# python字典 +person = { + "name": "张三", + "country": "中国", + "city": "北京", + "skills": ["JavaScript", "React", "Python"] +} +with open('./files/json_example.json', 'w', encoding='utf-8') as f: + json.dump(person, f, ensure_ascii=False, indent=4) +``` + +现在,让我们读取我们刚刚创建的json文件: + +```py +import json +with open('./files/json_example.json', 'r', encoding='utf-8') as f: + person = json.load(f) + print(person) +``` + +```sh +# 输出 +{'name': '张三', 'country': '中国', 'city': '北京', 'skills': ['JavaScript', 'React', 'Python']} +``` + +### 带有csv扩展名的文件 + +CSV代表逗号分隔值。CSV是一种简单的文件格式,用于存储表格数据,如电子表格或数据库。CSV是数据科学中非常常见的数据格式。 + +**示例:** + +```csv +"name","country","city","skills" +"Asabeneh","Finland","Helsinki","JavaScript" +``` + +**示例:** + +```py +import csv +with open('./files/csv_example.csv') as f: + csv_reader = csv.reader(f, delimiter=',') # w+ 创建文件(如果不存在) + line_count = 0 + for row in csv_reader: + if line_count == 0: + print(f'列名为: {", ".join(row)}') + line_count += 1 + else: + print(f'{row[0]}来自{row[1]}的{row[2]}。 他了解{row[3]}') + line_count += 1 + print(f'已处理{line_count}行。') +``` + +```sh +# 输出: +列名为: name, country, city, skills +Asabeneh来自Finland的Helsinki。 他了解JavaScript +已处理2行。 +``` + +我们还可以使用相同的方法将数据写入csv文件 + +```py +import csv +with open('./files/csv_example.csv', 'w', encoding='UTF8', newline='') as f: + writer = csv.writer(f) + # 写入列名 + writer.writerow(['name', 'country', 'city', 'skills']) + # 写入数据 + writer.writerow(['Asabeneh', 'Finland', 'Helsinki', 'JavaScript']) +``` + +### 带有xlsx扩展名的文件 + +要读取Excel文件,我们需要安装xlrd包。我们将使用它来读取Excel文件。 + +```py +import xlrd +excel_book = xlrd.open_workbook('sample.xls') +print(excel_book.nsheets) +print(excel_book.sheet_names) +``` + +### 带有xml扩展名的文件 + +XML是一种元标记语言,非常类似于HTML。在XML中,我们可以使用自己的标签,从而使其更加灵活。我们使用XML主要是为了结构化数据。在Python中有少量的XML库。在本部分中,我们将使用xml.etree.ElementTree模块。 + +**示例:XML** + +```xml + + + Asabeneh + Finland + Helsinki + + JavaScript + React + Python + + +``` + +我们将使用xml.etree.ElementTree模块来解析XML文件。 + +```py +import xml.etree.ElementTree as ET +tree = ET.parse('./files/xml_example.xml') +root = tree.getroot() +print('Root tag:', root.tag) +print('Attribute:', root.attrib) +for child in root: + print('字段: ', child.tag) +``` + +```sh +# 输出 +Root tag: person +Attribute: {'gender': 'female'} +字段: name +字段: country +字段: city +字段: skills +``` + +```py +import xml.etree.ElementTree as ET +tree = ET.parse('./files/xml_example.xml') +root = tree.getroot() +print('Root tag:', root.tag) +print('Attribute:', root.attrib) +for child in root: + print('字段: ', child.tag) +``` + +```sh +# 输出 +Root tag: person +Attribute: {'gender': 'female'} +字段: name +字段: country +字段: city +字段: skills +``` + +让我们获取更多细节: + +```py +import xml.etree.ElementTree as ET +tree = ET.parse('./files/xml_example.xml') +root = tree.getroot() +print('Root tag:', root.tag) +print('Attribute:', root.attrib) +for child in root: + print('field: ', child.tag) + if child.tag != 'skills': + print(child.text) + else: + for skill in child: + print(skill.text) +``` + +```sh +# 输出 +Root tag: person +Attribute: {'gender': 'female'} +field: name +Asabeneh +field: country +Finland +field: city +Helsinki +field: skills +JavaScript +React +Python +``` + +## 💻 练习:第19天 + +### 练习:级别1 + +1. 编写一个函数,该函数需要一个参数(文件名)并统计文件中单词的数量 +2. 阅读obama_speech.txt文件并计算单词数 +3. 阅读michelle_obama_speech.txt文件并计算单词数 +4. 阅读donald_speech.txt文件并计算单词数 +5. 阅读melina_trump_speech.txt文件并计算单词数 + +### 练习:级别2 + +1. 从编程语言中提取所有Python目录文件: + a) 处理30DaysOfPython文件夹,提取出所有python文件,并将它们的名称存储在files_list.txt文件中 + b) 创建一个名为find_python.py的脚本,可以通过命令行运行它 + c) 添加一个名为--version的标志来处理命令行参数 + +### 练习:级别3 + +1. 使用以下数据集创建一个JSON文件: + ```py + python_libraries = [ + { + "库名称": "Django", + "创建者": "Adrian Holovaty", + "首次发布年份": 2005, + "版本": "4.0.2", + "用途": "Web开发", + "描述": "Django让您可以快速构建更好的Web应用程序。" + }, + { + "库名称": "Flask", + "创建者": "Armin Ronacher", + "首次发布年份": 2010, + "版本": "2.0.2", + "用途": "Web开发", + "描述": "Flask是一个轻量级的WSGI Web应用程序框架。" + }, + { + "库名称": "NumPy", + "创建者": "Travis Oliphant", + "首次发布年份": 2005, + "版本": "1.22.0", + "用途": "科学计算", + "描述": "NumPy是Python中用于科学计算的基础包。" + }, + { + "库名称": "Pandas", + "创建者": "Wes McKinney", + "首次发布年份": 2008, + "版本": "1.4.0", + "用途": "数据分析", + "描述": "pandas是一个用于数据分析和数据操作的开源库。" + }, + { + "库名称": "Matplotlib", + "创建者": "John D. Hunter", + "首次发布年份": 2003, + "版本": "3.5.1", + "用途": "数据可视化", + "描述": "Matplotlib是一个用于在Python中创建静态、动画和交互式可视化的库。" + } + ] + ``` + +🎉 恭喜!🎉 + +[<< 第 18 天](./18_regular_expressions_cn.md) | [第 20 天 >>](./20_python_package_manager_cn.md) \ No newline at end of file diff --git a/Chinese/20_python_package_manager_cn.md b/Chinese/20_python_package_manager_cn.md index a0fd023b8..10bb51537 100644 --- a/Chinese/20_python_package_manager_cn.md +++ b/Chinese/20_python_package_manager_cn.md @@ -1,352 +1,352 @@ -# 30天Python编程挑战:第20天 - PIP - -- [第20天](#-第20天) - - [Python PIP - Python包管理器](#python-pip---python包管理器) - - [什么是PIP?](#什么是pip) - - [安装PIP](#安装pip) - - [使用pip安装包](#使用pip安装包) - - [卸载包](#卸载包) - - [包列表](#包列表) - - [显示包信息](#显示包信息) - - [PIP Freeze](#pip-freeze) - - [从URL读取数据](#从url读取数据) - - [创建包](#创建包) - - [关于包的更多信息](#关于包的更多信息) - - [练习:第20天](#练习第20天) - -# 📘 第20天 - -## Python PIP - Python包管理器 - -### 什么是PIP? - -PIP代表首选安装程序(Preferred installer program)。我们使用_pip_来安装不同的Python包。 -包是一个Python模块,可以包含一个或多个模块或其他包。我们可以安装到应用程序中的模块或模块集合就是一个包。 -在编程中,我们不必编写每个实用程序,而是安装包并将它们导入到我们的应用程序中。 - -### 安装PIP - -如果你还没有安装pip,让我们现在安装它。转到你的终端或命令提示符,复制并粘贴: - -```sh -asabeneh@Asabeneh:~$ pip install pip -``` - -通过以下命令检查pip是否已安装: - -```sh -pip --version -``` - -```py -asabeneh@Asabeneh:~$ pip --version -pip 21.1.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.9.6) -``` - -如你所见,我正在使用pip 21.1.3版本,如果你看到的数字比这个稍低或稍高,说明你已经安装了pip。 - -让我们了解一下Python社区中用于不同目的的一些包。请注意,有很多可用于不同应用程序的包。 - -### 使用pip安装包 - -让我们尝试安装_numpy_,即数值Python。它是机器学习和数据科学社区中最流行的包之一。 - -- NumPy是Python科学计算的基础包。它包含以下内容: - - 强大的N维数组对象 - - 复杂的(广播)函数 - - 用于集成C/C++和Fortran代码的工具 - - 有用的线性代数、傅里叶变换和随机数功能 - -```sh -asabeneh@Asabeneh:~$ pip install numpy -``` - -让我们开始使用numpy。打开你的Python交互式shell,输入python,然后按如下方式导入numpy: - -```py -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> import numpy ->>> numpy.version.version -'1.20.1' ->>> lst = [1, 2, 3,4, 5] ->>> np_arr = numpy.array(lst) ->>> np_arr -array([1, 2, 3, 4, 5]) ->>> len(np_arr) -5 ->>> np_arr * 2 -array([ 2, 4, 6, 8, 10]) ->>> np_arr + 2 -array([3, 4, 5, 6, 7]) ->>> -``` - -Pandas是一个开源的、BSD许可的库,为Python编程语言提供高性能、易用的数据结构和数据分析工具。让我们安装numpy的"大兄弟"_pandas_: - -```sh -asabeneh@Asabeneh:~$ pip install pandas -``` - -```py -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> import pandas -``` - -这一节不是关于numpy或pandas的,我们在这里尝试学习如何安装包以及如何导入它们。如果需要,我们将在其他章节讨论不同的包。 - -让我们导入一个Web浏览器模块,它可以帮助我们打开任何网站。我们不需要安装这个模块,它已经默认安装在Python 3中。例如,如果你想随时打开任意数量的网站,或者如果你想安排某些事情,可以使用这个_webbrowser_模块。 - -```py -import webbrowser # web浏览器模块用于打开网站 - -# 网址列表:Python -url_lists = [ - 'http://www.python.org', - 'https://www.linkedin.com/in/asabeneh/', - 'https://github.com/Asabeneh', - 'https://twitter.com/Asabeneh', -] - -# 在不同的标签页中打开上面的网站列表 -for url in url_lists: - webbrowser.open_new_tab(url) -``` - -### 卸载包 - -如果你不想保留已安装的包,可以使用以下命令删除它们。 - -```sh -pip uninstall packagename -``` - -### 包列表 - -要查看我们机器上已安装的包,我们可以使用pip后跟list。 - -```sh -pip list -``` - -### 显示包信息 - -要显示有关包的信息: - -```sh -pip show packagename -``` - -```sh -asabeneh@Asabeneh:~$ pip show pandas -Name: pandas -Version: 1.2.3 -Summary: Powerful data structures for data analysis, time series, and statistics -Home-page: http://pandas.pydata.org -Author: None -Author-email: None -License: BSD -Location: /usr/local/lib/python3.7/site-packages -Requires: python-dateutil, pytz, numpy -Required-by: -``` - -如果我们想要更多的详细信息,只需添加--verbose - -```sh -asabeneh@Asabeneh:~$ pip show --verbose pandas -Name: pandas -Version: 1.2.3 -Summary: Powerful data structures for data analysis, time series, and statistics -Home-page: http://pandas.pydata.org -Author: None -Author-email: None -License: BSD -Location: /usr/local/lib/python3.7/site-packages -Requires: numpy, pytz, python-dateutil -Required-by: -Metadata-Version: 2.1 -Installer: pip -Classifiers: - Development Status :: 5 - Production/Stable - Environment :: Console - Operating System :: OS Independent - Intended Audience :: Science/Research - Programming Language :: Python - Programming Language :: Python :: 3 - Programming Language :: Python :: 3.5 - Programming Language :: Python :: 3.6 - Programming Language :: Python :: 3.7 - Programming Language :: Python :: 3.8 - Programming Language :: Cython - Topic :: Scientific/Engineering -Entry-points: - [pandas_plotting_backends] - matplotlib = pandas:plotting._matplotlib -``` - -### PIP Freeze - -生成已安装的Python包及其版本,输出适合在requirements文件中使用。requirements.txt文件是一个包含Python项目中所有已安装的Python包的文件。 - -```sh -asabeneh@Asabeneh:~$ pip freeze -docutils==0.11 -Jinja2==2.7.2 -MarkupSafe==0.19 -Pygments==1.6 -Sphinx==1.2.2 -``` - -pip freeze给我们列出了使用的、已安装的包及其版本。我们将它与requirements.txt文件一起用于部署。 - -### 从URL读取数据 - -到目前为止,你已经熟悉了如何读取或写入位于本地机器上的文件。有时,我们想要使用url从网站或API读取数据。 -API代表应用程序编程接口。它是一种在服务器之间交换结构化数据的方式,主要是json数据。要打开网络连接,我们需要一个名为_requests_的包——它允许打开网络连接并实现CRUD(创建、读取、更新和删除)操作。在本节中,我们将只涵盖CRUD的读取或获取部分。 - -让我们安装_requests_: - -```py -asabeneh@Asabeneh:~$ pip install requests -``` - -我们将在_requests_模块中看到_get_、_status_code_、_headers_、_text_和_json_方法: - - _get()_:打开网络并从url获取数据——它返回一个响应对象 - - _status_code_:在我们获取数据后,我们可以检查操作的状态(成功、错误等) - - _headers_:检查头部类型 - - _text_:从获取的响应对象中提取文本 - - _json_:提取json数据 -让我们从这个网站读取一个txt文件,https://www.w3.org/TR/PNG/iso_8859-1.txt。 - -```py -import requests # 导入请求模块 - -url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt' # 来自网站的文本 - -response = requests.get(url) # 打开网络并获取数据 -print(response) -print(response.status_code) # 状态码,成功时为200 -print(response.headers) # 获取响应的头部信息 -print(response.text) # 获取文本数据 -``` - -让我们读取一个API并得到一个json数据: - -```py -import requests -url = 'https://restcountries.eu/rest/v2/all' # 包含关于250多个国家的信息的国家API -response = requests.get(url) # 打开网络并获取数据 -print(response) # 响应对象 -print(response.status_code) # 状态码,成功时为200 -countries = response.json() -print(countries[:1]) # 我们只打印第一个国家信息,原始数据太大 -``` - -我们用一个国家API示例获取了json数据。我们可以导入json模块,并使用json.loads(response.text)方法将文本转换为json格式。然而,我们也可以直接使用response.json()方法。 - -Let us see another example similar to the above but with a different API, world_bank_ethiopia data: -让我们看另一个类似于上面的例子,但使用不同的API,世界银行埃塞俄比亚数据: - -```py -import requests -from pprint import pp # 导入pretty print,以美观地显示 - -url = 'http://api.worldbank.org/countries/et?format=json' # 埃塞俄比亚经济数据API -response = requests.get(url) # 打开网络并获取数据 -print(response) # 响应对象 -print(response.status_code) # 状态码,成功时为200 -# 让我们改变响应的JSON格式 -ethiopia_data = response.json() -pp(ethiopia_data) # 用pretty print打印数据 -``` - -### 创建包 - -我们可以创建自己的包,上传到Python包管理器仓库,并从那里下载它。让我们创建一个非常简单的包来演示。创建一个名为mypackage的目录,在该目录中创建一个名为__init__.py的空文件和以下文件: - -```py -# mypackage/arithmetics.py -def add_numbers(*args): - total = 0 - for num in args: - total += num - return total - -def subtract(a, b): - return (a - b) - -def multiple(a, b): - return a * b - -def division(a, b): - return a / b - -def remainder(a, b): - return a % b - -def power(a, b): - return a ** b -``` - -```py -# mypackage/greet.py -def greet_person(firstname, lastname): - return f'{firstname} {lastname}, welcome to 30DaysOfPython Challenge!' -``` - -__init__.py在python 3.3及更高版本中并非绝对必要,但对于兼容性,最好加上。 - -现在,让我们使用刚刚创建的包: - -```py -from mypackage import arithmetics -print(arithmetics.add_numbers(1, 2, 3, 5)) -print(arithmetics.subtract(5, 3)) -print(arithmetics.multiple(5, 3)) -print(arithmetics.division(5, 3)) -print(arithmetics.remainder(5, 3)) -print(arithmetics.power(5, 3)) - -from mypackage import greet -print(greet.greet_person('张', '三')) -``` - -### 关于包的更多信息 - -- Python有许多不同目的的内置包和模块,但有些不包含在内置包中,我们需要安装它们。 -- 有多种方法可以安装包,但建议使用pip。 - - 使用 pip:pip是Python、PyPI和virtualenv推荐的安装和管理Python包的工具。 -- 如何列出已安装的包: - - pip list:列出机器中安装的所有包。 -- 使用requirements.txt进行开发环境和生产环境: - - 要生成已安装包的列表:pip freeze来本地生成已安装包的列表,以便用于开发环境和生产环境需求。 -- 如何卸载包: - - 要卸载,请使用pip:pip uninstall packagename。 - - 另一种方法:pip uninstall -r requirements.txt卸载在requirements.txt中列出的所有包。 -- 使用virtualenv: - - virtualenv是一个工具,用于创建隔离的Python环境。它创建一个在自己的目录树中包含所有必要的可执行文件,以使用指定版本的Python运行Python项目所需的包。 - - 原始的virtualenv工具可以通过 - - pip install virtualenv - - 来安装。 - -## 练习:第20天 - -1. 阅读关于虚拟环境的更多信息,尝试创建虚拟环境并安装至少一个包 - -2. 使用一个国家API,获取所有国家信息,并找出前十个人口最多的国家 - -3. 从国家API数据中找出官方语言是英语(eng)的所有国家 - -4. 从国家API数据中获取数据,根据国家的面积找出前十个最大的国家 - -5. 从国家API数据中找出所有从新列出的国家,按他们的首都排序 - -🎉 恭喜!🎉 - -[<< 第19天](./19_Day_File_handling/19_file_handling_cn.md) | [第21天 >>](./21_Day_Classes_and_objects/21_classes_and_objects_cn.md) \ No newline at end of file +# 30天Python编程挑战:第20天 - PIP + +- [第20天](#-第20天) + - [Python PIP - Python包管理器](#python-pip---python包管理器) + - [什么是PIP?](#什么是pip) + - [安装PIP](#安装pip) + - [使用pip安装包](#使用pip安装包) + - [卸载包](#卸载包) + - [包列表](#包列表) + - [显示包信息](#显示包信息) + - [PIP Freeze](#pip-freeze) + - [从URL读取数据](#从url读取数据) + - [创建包](#创建包) + - [关于包的更多信息](#关于包的更多信息) + - [练习:第20天](#练习第20天) + +# 📘 第20天 + +## Python PIP - Python包管理器 + +### 什么是PIP? + +PIP代表首选安装程序(Preferred installer program)。我们使用_pip_来安装不同的Python包。 +包是一个Python模块,可以包含一个或多个模块或其他包。我们可以安装到应用程序中的模块或模块集合就是一个包。 +在编程中,我们不必编写每个实用程序,而是安装包并将它们导入到我们的应用程序中。 + +### 安装PIP + +如果你还没有安装pip,让我们现在安装它。转到你的终端或命令提示符,复制并粘贴: + +```sh +asabeneh@Asabeneh:~$ pip install pip +``` + +通过以下命令检查pip是否已安装: + +```sh +pip --version +``` + +```py +asabeneh@Asabeneh:~$ pip --version +pip 21.1.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.9.6) +``` + +如你所见,我正在使用pip 21.1.3版本,如果你看到的数字比这个稍低或稍高,说明你已经安装了pip。 + +让我们了解一下Python社区中用于不同目的的一些包。请注意,有很多可用于不同应用程序的包。 + +### 使用pip安装包 + +让我们尝试安装_numpy_,即数值Python。它是机器学习和数据科学社区中最流行的包之一。 + +- NumPy是Python科学计算的基础包。它包含以下内容: + - 强大的N维数组对象 + - 复杂的(广播)函数 + - 用于集成C/C++和Fortran代码的工具 + - 有用的线性代数、傅里叶变换和随机数功能 + +```sh +asabeneh@Asabeneh:~$ pip install numpy +``` + +让我们开始使用numpy。打开你的Python交互式shell,输入python,然后按如下方式导入numpy: + +```py +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import numpy +>>> numpy.version.version +'1.20.1' +>>> lst = [1, 2, 3,4, 5] +>>> np_arr = numpy.array(lst) +>>> np_arr +array([1, 2, 3, 4, 5]) +>>> len(np_arr) +5 +>>> np_arr * 2 +array([ 2, 4, 6, 8, 10]) +>>> np_arr + 2 +array([3, 4, 5, 6, 7]) +>>> +``` + +Pandas是一个开源的、BSD许可的库,为Python编程语言提供高性能、易用的数据结构和数据分析工具。让我们安装numpy的"大兄弟"_pandas_: + +```sh +asabeneh@Asabeneh:~$ pip install pandas +``` + +```py +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> import pandas +``` + +这一节不是关于numpy或pandas的,我们在这里尝试学习如何安装包以及如何导入它们。如果需要,我们将在其他章节讨论不同的包。 + +让我们导入一个Web浏览器模块,它可以帮助我们打开任何网站。我们不需要安装这个模块,它已经默认安装在Python 3中。例如,如果你想随时打开任意数量的网站,或者如果你想安排某些事情,可以使用这个_webbrowser_模块。 + +```py +import webbrowser # web浏览器模块用于打开网站 + +# 网址列表:Python +url_lists = [ + 'http://www.python.org', + 'https://www.linkedin.com/in/asabeneh/', + 'https://github.com/Asabeneh', + 'https://twitter.com/Asabeneh', +] + +# 在不同的标签页中打开上面的网站列表 +for url in url_lists: + webbrowser.open_new_tab(url) +``` + +### 卸载包 + +如果你不想保留已安装的包,可以使用以下命令删除它们。 + +```sh +pip uninstall packagename +``` + +### 包列表 + +要查看我们机器上已安装的包,我们可以使用pip后跟list。 + +```sh +pip list +``` + +### 显示包信息 + +要显示有关包的信息: + +```sh +pip show packagename +``` + +```sh +asabeneh@Asabeneh:~$ pip show pandas +Name: pandas +Version: 1.2.3 +Summary: Powerful data structures for data analysis, time series, and statistics +Home-page: http://pandas.pydata.org +Author: None +Author-email: None +License: BSD +Location: /usr/local/lib/python3.7/site-packages +Requires: python-dateutil, pytz, numpy +Required-by: +``` + +如果我们想要更多的详细信息,只需添加--verbose + +```sh +asabeneh@Asabeneh:~$ pip show --verbose pandas +Name: pandas +Version: 1.2.3 +Summary: Powerful data structures for data analysis, time series, and statistics +Home-page: http://pandas.pydata.org +Author: None +Author-email: None +License: BSD +Location: /usr/local/lib/python3.7/site-packages +Requires: numpy, pytz, python-dateutil +Required-by: +Metadata-Version: 2.1 +Installer: pip +Classifiers: + Development Status :: 5 - Production/Stable + Environment :: Console + Operating System :: OS Independent + Intended Audience :: Science/Research + Programming Language :: Python + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Cython + Topic :: Scientific/Engineering +Entry-points: + [pandas_plotting_backends] + matplotlib = pandas:plotting._matplotlib +``` + +### PIP Freeze + +生成已安装的Python包及其版本,输出适合在requirements文件中使用。requirements.txt文件是一个包含Python项目中所有已安装的Python包的文件。 + +```sh +asabeneh@Asabeneh:~$ pip freeze +docutils==0.11 +Jinja2==2.7.2 +MarkupSafe==0.19 +Pygments==1.6 +Sphinx==1.2.2 +``` + +pip freeze给我们列出了使用的、已安装的包及其版本。我们将它与requirements.txt文件一起用于部署。 + +### 从URL读取数据 + +到目前为止,你已经熟悉了如何读取或写入位于本地机器上的文件。有时,我们想要使用url从网站或API读取数据。 +API代表应用程序编程接口。它是一种在服务器之间交换结构化数据的方式,主要是json数据。要打开网络连接,我们需要一个名为_requests_的包——它允许打开网络连接并实现CRUD(创建、读取、更新和删除)操作。在本节中,我们将只涵盖CRUD的读取或获取部分。 + +让我们安装_requests_: + +```py +asabeneh@Asabeneh:~$ pip install requests +``` + +我们将在_requests_模块中看到_get_、_status_code_、_headers_、_text_和_json_方法: + - _get()_:打开网络并从url获取数据——它返回一个响应对象 + - _status_code_:在我们获取数据后,我们可以检查操作的状态(成功、错误等) + - _headers_:检查头部类型 + - _text_:从获取的响应对象中提取文本 + - _json_:提取json数据 +让我们从这个网站读取一个txt文件,https://www.w3.org/TR/PNG/iso_8859-1.txt。 + +```py +import requests # 导入请求模块 + +url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt' # 来自网站的文本 + +response = requests.get(url) # 打开网络并获取数据 +print(response) +print(response.status_code) # 状态码,成功时为200 +print(response.headers) # 获取响应的头部信息 +print(response.text) # 获取文本数据 +``` + +让我们读取一个API并得到一个json数据: + +```py +import requests +url = 'https://restcountries.eu/rest/v2/all' # 包含关于250多个国家的信息的国家API +response = requests.get(url) # 打开网络并获取数据 +print(response) # 响应对象 +print(response.status_code) # 状态码,成功时为200 +countries = response.json() +print(countries[:1]) # 我们只打印第一个国家信息,原始数据太大 +``` + +我们用一个国家API示例获取了json数据。我们可以导入json模块,并使用json.loads(response.text)方法将文本转换为json格式。然而,我们也可以直接使用response.json()方法。 + +Let us see another example similar to the above but with a different API, world_bank_ethiopia data: +让我们看另一个类似于上面的例子,但使用不同的API,世界银行埃塞俄比亚数据: + +```py +import requests +from pprint import pp # 导入pretty print,以美观地显示 + +url = 'http://api.worldbank.org/countries/et?format=json' # 埃塞俄比亚经济数据API +response = requests.get(url) # 打开网络并获取数据 +print(response) # 响应对象 +print(response.status_code) # 状态码,成功时为200 +# 让我们改变响应的JSON格式 +ethiopia_data = response.json() +pp(ethiopia_data) # 用pretty print打印数据 +``` + +### 创建包 + +我们可以创建自己的包,上传到Python包管理器仓库,并从那里下载它。让我们创建一个非常简单的包来演示。创建一个名为mypackage的目录,在该目录中创建一个名为__init__.py的空文件和以下文件: + +```py +# mypackage/arithmetics.py +def add_numbers(*args): + total = 0 + for num in args: + total += num + return total + +def subtract(a, b): + return (a - b) + +def multiple(a, b): + return a * b + +def division(a, b): + return a / b + +def remainder(a, b): + return a % b + +def power(a, b): + return a ** b +``` + +```py +# mypackage/greet.py +def greet_person(firstname, lastname): + return f'{firstname} {lastname}, welcome to 30DaysOfPython Challenge!' +``` + +__init__.py在python 3.3及更高版本中并非绝对必要,但对于兼容性,最好加上。 + +现在,让我们使用刚刚创建的包: + +```py +from mypackage import arithmetics +print(arithmetics.add_numbers(1, 2, 3, 5)) +print(arithmetics.subtract(5, 3)) +print(arithmetics.multiple(5, 3)) +print(arithmetics.division(5, 3)) +print(arithmetics.remainder(5, 3)) +print(arithmetics.power(5, 3)) + +from mypackage import greet +print(greet.greet_person('张', '三')) +``` + +### 关于包的更多信息 + +- Python有许多不同目的的内置包和模块,但有些不包含在内置包中,我们需要安装它们。 +- 有多种方法可以安装包,但建议使用pip。 + - 使用 pip:pip是Python、PyPI和virtualenv推荐的安装和管理Python包的工具。 +- 如何列出已安装的包: + - pip list:列出机器中安装的所有包。 +- 使用requirements.txt进行开发环境和生产环境: + - 要生成已安装包的列表:pip freeze来本地生成已安装包的列表,以便用于开发环境和生产环境需求。 +- 如何卸载包: + - 要卸载,请使用pip:pip uninstall packagename。 + - 另一种方法:pip uninstall -r requirements.txt卸载在requirements.txt中列出的所有包。 +- 使用virtualenv: + - virtualenv是一个工具,用于创建隔离的Python环境。它创建一个在自己的目录树中包含所有必要的可执行文件,以使用指定版本的Python运行Python项目所需的包。 + - 原始的virtualenv工具可以通过 + - pip install virtualenv + - 来安装。 + +## 练习:第20天 + +1. 阅读关于虚拟环境的更多信息,尝试创建虚拟环境并安装至少一个包 + +2. 使用一个国家API,获取所有国家信息,并找出前十个人口最多的国家 + +3. 从国家API数据中找出官方语言是英语(eng)的所有国家 + +4. 从国家API数据中获取数据,根据国家的面积找出前十个最大的国家 + +5. 从国家API数据中找出所有从新列出的国家,按他们的首都排序 + +🎉 恭喜!🎉 + +[<< 第 19 天](./19_file_handling_cn.md) | [第 21 天 >>](./21_classes_and_objects_cn.md) \ No newline at end of file diff --git a/Chinese/21_classes_and_objects_cn.md b/Chinese/21_classes_and_objects_cn.md index 5e09256aa..ac0fa4de8 100644 --- a/Chinese/21_classes_and_objects_cn.md +++ b/Chinese/21_classes_and_objects_cn.md @@ -1,419 +1,419 @@ -# 30天Python编程挑战:第21天 - 类和对象 - -- [第21天](#-第21天) - - [类和对象](#类和对象) - - [创建类](#创建类) - - [创建对象](#创建对象) - - [类构造函数](#类构造函数) - - [对象方法](#对象方法) - - [对象默认方法](#对象默认方法) - - [修改类默认值的方法](#修改类默认值的方法) - - [继承](#继承) - - [覆盖父类方法](#覆盖父类方法) - - [💻 练习:第21天](#-练习第21天) - - [练习:级别1](#练习级别1) - - [练习:级别2](#练习级别2) - - [练习:级别3](#练习级别3) - -# 📘 第21天 - -## 类和对象 - -Python是一种面向对象的编程语言。在Python中,一切都是对象,都有其属性和方法。在程序中使用的数字、字符串、列表、字典、元组、集合等都是相应内置类的对象。我们创建类来创建对象。类就像一个对象构造器,或者说是创建对象的"蓝图"。我们实例化一个类来创建一个对象。类定义了对象的属性和行为,而对象则代表了类。 - -从这个挑战的开始,我们就一直在不知不觉地使用类和对象。Python程序中的每个元素都是某个类的对象。 -让我们检查一下Python中的一切是否都是类: - -```py -asabeneh@Asabeneh:~$ python -Python 3.9.6 (default, Jun 28 2021, 15:26:21) -[Clang 11.0.0 (clang-1100.0.33.8)] on darwin -Type "help", "copyright", "credits" or "license" for more information. ->>> num = 10 ->>> type(num) - ->>> string = 'string' ->>> type(string) - ->>> boolean = True ->>> type(boolean) - ->>> lst = [] ->>> type(lst) - ->>> tpl = () ->>> type(tpl) - ->>> set1 = set() ->>> type(set1) - ->>> dct = {} ->>> type(dct) - -``` - -### 创建类 - -要创建一个类,我们需要关键字**class**,后跟类名和冒号。类名应该使用**驼峰命名法(CamelCase)**。 - -```sh -# 语法 -class 类名: - 代码放在这里 -``` - -**示例:** - -```py -class Person: - pass -print(Person) -``` - -```sh -<__main__.Person object at 0x10804e510> -``` - -### 创建对象 - -我们可以通过调用类来创建对象。 - -```py -p = Person() -print(p) -``` - -### 类构造函数 - -在上面的例子中,我们已经从Person类创建了一个对象。然而,没有构造函数的类在实际应用中并不真正有用。让我们使用构造函数使我们的类更有用。与Java或JavaScript中的构造函数一样,Python也有一个内置的**__init__**()构造函数。**__init__**构造函数有一个self参数,它是当前类实例的引用。 -**示例:** - -```py -class Person: - def __init__ (self, name): - # self允许将参数附加到类 - self.name = name - -p = Person('Asabeneh') -print(p.name) -print(p) -``` - -```sh -# 输出 -Asabeneh -<__main__.Person object at 0x2abf46907e80> -``` - -让我们向构造函数添加更多参数。 - -```py -class Person: - def __init__(self, firstname, lastname, age, country, city): - self.firstname = firstname - self.lastname = lastname - self.age = age - self.country = country - self.city = city - - -p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') -print(p.firstname) -print(p.lastname) -print(p.age) -print(p.country) -print(p.city) -``` - -```sh -# 输出 -Asabeneh -Yetayeh -250 -Finland -Helsinki -``` - -### 对象方法 - -对象可以有方法。方法是属于对象的函数。 - -**示例:** - -```py -class Person: - def __init__(self, firstname, lastname, age, country, city): - self.firstname = firstname - self.lastname = lastname - self.age = age - self.country = country - self.city = city - def person_info(self): - return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' - -p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') -print(p.person_info()) -``` - -```sh -# 输出 -Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 -``` - -### 对象默认方法 - -有时,你可能希望为对象方法提供默认值。如果我们为构造函数中的参数提供默认值,可以避免在不带参数调用或实例化类时出现错误。让我们看看这是什么样子: - -**示例:** - -```py -class Person: - def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250, country='Finland', city='Helsinki'): - self.firstname = firstname - self.lastname = lastname - self.age = age - self.country = country - self.city = city - - def person_info(self): - return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' - -p1 = Person() -print(p1.person_info()) -p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city') -print(p2.person_info()) -``` - -```sh -# 输出 -Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 -John Doe今年30岁。他住在Nomanland的Noman city。 -``` - -### 修改类默认值的方法 - -在下面的例子中,person类的所有构造函数参数都有默认值。此外,我们还有一个skills参数,可以通过方法访问。让我们创建一个add_skill方法,向skills列表添加技能。 - -```py -class Person: - def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250, country='Finland', city='Helsinki'): - self.firstname = firstname - self.lastname = lastname - self.age = age - self.country = country - self.city = city - self.skills = [] - - def person_info(self): - return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' - def add_skill(self, skill): - self.skills.append(skill) - -p1 = Person() -print(p1.person_info()) -p1.add_skill('HTML') -p1.add_skill('CSS') -p1.add_skill('JavaScript') -p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city') -print(p2.person_info()) -print(p1.skills) -print(p2.skills) -``` - -```sh -# 输出 -Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 -John Doe今年30岁。他住在Nomanland的Noman city。 -['HTML', 'CSS', 'JavaScript'] -[] -``` - -### 继承 - -继承允许我们定义一个继承父类所有功能的类。它使代码可重用。 - -```py -# 语法 -class 子类名(父类名): - 代码放在这里 -``` - -让我们通过实际例子来看看继承的含义: - -```py -class Student(Person): - pass - - -s1 = Student('Eyob', 'Yetayeh', 30, 'Finland', 'Helsinki') -s2 = Student('Lidiya', 'Teklemariam', 28, 'Finland', 'Espoo') -print(s1.person_info()) -s1.add_skill('JavaScript') -s1.add_skill('React') -s1.add_skill('Python') -print(s1.skills) -print(s2.person_info()) -s2.add_skill('Organizing') -s2.add_skill('Marketing') -s2.add_skill('Digital Marketing') -print(s2.skills) -``` - -```sh -# 输出 -Eyob Yetayeh今年30岁。他住在Finland的Helsinki。 -['JavaScript', 'React', 'Python'] -Lidiya Teklemariam今年28岁。他住在Finland的Espoo。 -['Organizing', 'Marketing', 'Digital Marketing'] -``` - -我们没有在Student类中调用任何方法,但我们能够访问来自Parent类的所有方法。Student类继承了Person类的__init__构造函数和person_info方法。如果我们想要向子类添加一个特定于子类的新方法,我们必须编写子类并在子类中创建新的方法。 - -```py -class Student(Person): - def __init__ (self, firstname='Asabeneh', lastname='Yetayeh',age=250, country='Finland', city='Helsinki', gender='male'): - self.gender = gender - super().__init__(firstname, lastname,age, country, city) - def person_info(self): - gender = '他' if self.gender =='male' else '她' - return f'{self.firstname} {self.lastname}今年{self.age}岁。{gender}住在{self.country}的{self.city}。' - - -s1 = Student('Eyob', 'Yetayeh', 30, 'Finland', 'Helsinki','male') -s2 = Student('Lidiya', 'Teklemariam', 28, 'Finland', 'Espoo', 'female') -print(s1.person_info()) -s1.add_skill('JavaScript') -s1.add_skill('React') -s1.add_skill('Python') -print(s1.skills) -print(s2.person_info()) -s2.add_skill('Organizing') -s2.add_skill('Marketing') -s2.add_skill('Digital Marketing') -print(s2.skills) -``` - -```sh -# 输出 -Eyob Yetayeh今年30岁。他住在Finland的Helsinki。 -['JavaScript', 'React', 'Python'] -Lidiya Teklemariam今年28岁。她住在Finland的Espoo。 -['Organizing', 'Marketing', 'Digital Marketing'] -``` - -我们可以使用super()函数或父类名Person来自动继承父类的方法和属性。在上面的例子中,我们覆盖了父类方法。子类的person_info方法有不同的实现,即使方法名称与父类相同。 - -### 覆盖父类方法 - -如上所示,我们可以通过创建与父类方法名称相同的子类方法来覆盖父类方法。 - -## 💻 练习:第21天 - -### 练习:级别1 - -1. Python有一个名为_statistics_的模块,我们可以使用这个模块来计算统计数据。但是,让我们尝试开发一个可以计算均值、中位数、众数、标准差等统计数据的类。 - -```py -class Statistics: - def __init__(self, data=[]): - self.data = data - - def count(self): - # 你自己的实现 - pass - - def sum(self): - # 你自己的实现 - pass - - def min(self): - # 你自己的实现 - pass - - def max(self): - # 你自己的实现 - pass - - def range(self): - # 你自己的实现 - pass - - def mean(self): - # 你自己的实现 - pass - - def median(self): - # 你自己的实现 - pass - - def mode(self): - # 你自己的实现 - pass - - def standard_deviation(self): - # 你自己的实现 - pass - - def variance(self): - # 你自己的实现 - pass - - def frequency_distribution(self): - # 你自己的实现 - pass - - def describe(self): - # 你自己的实现 - pass -``` - -```py -# 测试代码 -data = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26] -statistics = Statistics(data) -print('Count:', statistics.count()) # 25 -print('Sum: ', statistics.sum()) # 730 -print('Min: ', statistics.min()) # 24 -print('Max: ', statistics.max()) # 38 -print('Range: ', statistics.range()) # 14 -print('Mean: ', statistics.mean()) # 29.2 -print('Median: ', statistics.median()) # 27 -print('Mode: ', statistics.mode()) # {'mode': 26, 'count': 5} -print('Standard Deviation: ', statistics.standard_deviation()) # 4.2 -print('Variance: ', statistics.variance()) # 17.5 -print('Frequency Distribution: ', statistics.frequency_distribution()) # [(24, 2), (25, 1), (26, 5), (27, 4), (29, 1), (31, 2), (32, 3), (33, 2), (34, 2), (37, 2), (38, 1)] -``` - -### 练习:级别2 - -1. 创建一个名为PersonAccount的类。它有firstname、lastname、incomes、expenses属性和添加收入、添加支出以及账户余额方法。 - -### 练习:级别3 - -1. 以下是使用函数的方法。让我们将其转换为类 - -```python -def print_products(*args, **kwargs): - for product in args: - print(product) - print(kwargs) - for key in kwargs: - print(f"{key}: {kwargs[key]}") - -print_products("apple", "banana", "orange", vegetable="tomato", juice="orange") -``` - -```sh -apple -banana -orange -{'vegetable': 'tomato', 'juice': 'orange'} -vegetable: tomato -juice: orange -``` - -1. 在一个名为PersonAccount的类中,我们有属性:firstname、lastname、incomes、expenses。设计一个类,用于计算一个人的净收入。 - -🎉 恭喜!🎉 - -[<< 第20天](./20_Day_Python_package_manager/20_python_package_manager_cn.md) | [第22天 >>](./22_Day_Web_scraping/22_web_scraping_cn.md) \ No newline at end of file +# 30天Python编程挑战:第21天 - 类和对象 + +- [第21天](#-第21天) + - [类和对象](#类和对象) + - [创建类](#创建类) + - [创建对象](#创建对象) + - [类构造函数](#类构造函数) + - [对象方法](#对象方法) + - [对象默认方法](#对象默认方法) + - [修改类默认值的方法](#修改类默认值的方法) + - [继承](#继承) + - [覆盖父类方法](#覆盖父类方法) + - [💻 练习:第21天](#-练习第21天) + - [练习:级别1](#练习级别1) + - [练习:级别2](#练习级别2) + - [练习:级别3](#练习级别3) + +# 📘 第21天 + +## 类和对象 + +Python是一种面向对象的编程语言。在Python中,一切都是对象,都有其属性和方法。在程序中使用的数字、字符串、列表、字典、元组、集合等都是相应内置类的对象。我们创建类来创建对象。类就像一个对象构造器,或者说是创建对象的"蓝图"。我们实例化一个类来创建一个对象。类定义了对象的属性和行为,而对象则代表了类。 + +从这个挑战的开始,我们就一直在不知不觉地使用类和对象。Python程序中的每个元素都是某个类的对象。 +让我们检查一下Python中的一切是否都是类: + +```py +asabeneh@Asabeneh:~$ python +Python 3.9.6 (default, Jun 28 2021, 15:26:21) +[Clang 11.0.0 (clang-1100.0.33.8)] on darwin +Type "help", "copyright", "credits" or "license" for more information. +>>> num = 10 +>>> type(num) + +>>> string = 'string' +>>> type(string) + +>>> boolean = True +>>> type(boolean) + +>>> lst = [] +>>> type(lst) + +>>> tpl = () +>>> type(tpl) + +>>> set1 = set() +>>> type(set1) + +>>> dct = {} +>>> type(dct) + +``` + +### 创建类 + +要创建一个类,我们需要关键字**class**,后跟类名和冒号。类名应该使用**驼峰命名法(CamelCase)**。 + +```sh +# 语法 +class 类名: + 代码放在这里 +``` + +**示例:** + +```py +class Person: + pass +print(Person) +``` + +```sh +<__main__.Person object at 0x10804e510> +``` + +### 创建对象 + +我们可以通过调用类来创建对象。 + +```py +p = Person() +print(p) +``` + +### 类构造函数 + +在上面的例子中,我们已经从Person类创建了一个对象。然而,没有构造函数的类在实际应用中并不真正有用。让我们使用构造函数使我们的类更有用。与Java或JavaScript中的构造函数一样,Python也有一个内置的**__init__**()构造函数。**__init__**构造函数有一个self参数,它是当前类实例的引用。 +**示例:** + +```py +class Person: + def __init__ (self, name): + # self允许将参数附加到类 + self.name = name + +p = Person('Asabeneh') +print(p.name) +print(p) +``` + +```sh +# 输出 +Asabeneh +<__main__.Person object at 0x2abf46907e80> +``` + +让我们向构造函数添加更多参数。 + +```py +class Person: + def __init__(self, firstname, lastname, age, country, city): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + + +p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') +print(p.firstname) +print(p.lastname) +print(p.age) +print(p.country) +print(p.city) +``` + +```sh +# 输出 +Asabeneh +Yetayeh +250 +Finland +Helsinki +``` + +### 对象方法 + +对象可以有方法。方法是属于对象的函数。 + +**示例:** + +```py +class Person: + def __init__(self, firstname, lastname, age, country, city): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + def person_info(self): + return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' + +p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki') +print(p.person_info()) +``` + +```sh +# 输出 +Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 +``` + +### 对象默认方法 + +有时,你可能希望为对象方法提供默认值。如果我们为构造函数中的参数提供默认值,可以避免在不带参数调用或实例化类时出现错误。让我们看看这是什么样子: + +**示例:** + +```py +class Person: + def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250, country='Finland', city='Helsinki'): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + + def person_info(self): + return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' + +p1 = Person() +print(p1.person_info()) +p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city') +print(p2.person_info()) +``` + +```sh +# 输出 +Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 +John Doe今年30岁。他住在Nomanland的Noman city。 +``` + +### 修改类默认值的方法 + +在下面的例子中,person类的所有构造函数参数都有默认值。此外,我们还有一个skills参数,可以通过方法访问。让我们创建一个add_skill方法,向skills列表添加技能。 + +```py +class Person: + def __init__(self, firstname='Asabeneh', lastname='Yetayeh', age=250, country='Finland', city='Helsinki'): + self.firstname = firstname + self.lastname = lastname + self.age = age + self.country = country + self.city = city + self.skills = [] + + def person_info(self): + return f'{self.firstname} {self.lastname}今年{self.age}岁。他住在{self.country}的{self.city}。' + def add_skill(self, skill): + self.skills.append(skill) + +p1 = Person() +print(p1.person_info()) +p1.add_skill('HTML') +p1.add_skill('CSS') +p1.add_skill('JavaScript') +p2 = Person('John', 'Doe', 30, 'Nomanland', 'Noman city') +print(p2.person_info()) +print(p1.skills) +print(p2.skills) +``` + +```sh +# 输出 +Asabeneh Yetayeh今年250岁。他住在Finland的Helsinki。 +John Doe今年30岁。他住在Nomanland的Noman city。 +['HTML', 'CSS', 'JavaScript'] +[] +``` + +### 继承 + +继承允许我们定义一个继承父类所有功能的类。它使代码可重用。 + +```py +# 语法 +class 子类名(父类名): + 代码放在这里 +``` + +让我们通过实际例子来看看继承的含义: + +```py +class Student(Person): + pass + + +s1 = Student('Eyob', 'Yetayeh', 30, 'Finland', 'Helsinki') +s2 = Student('Lidiya', 'Teklemariam', 28, 'Finland', 'Espoo') +print(s1.person_info()) +s1.add_skill('JavaScript') +s1.add_skill('React') +s1.add_skill('Python') +print(s1.skills) +print(s2.person_info()) +s2.add_skill('Organizing') +s2.add_skill('Marketing') +s2.add_skill('Digital Marketing') +print(s2.skills) +``` + +```sh +# 输出 +Eyob Yetayeh今年30岁。他住在Finland的Helsinki。 +['JavaScript', 'React', 'Python'] +Lidiya Teklemariam今年28岁。他住在Finland的Espoo。 +['Organizing', 'Marketing', 'Digital Marketing'] +``` + +我们没有在Student类中调用任何方法,但我们能够访问来自Parent类的所有方法。Student类继承了Person类的__init__构造函数和person_info方法。如果我们想要向子类添加一个特定于子类的新方法,我们必须编写子类并在子类中创建新的方法。 + +```py +class Student(Person): + def __init__ (self, firstname='Asabeneh', lastname='Yetayeh',age=250, country='Finland', city='Helsinki', gender='male'): + self.gender = gender + super().__init__(firstname, lastname,age, country, city) + def person_info(self): + gender = '他' if self.gender =='male' else '她' + return f'{self.firstname} {self.lastname}今年{self.age}岁。{gender}住在{self.country}的{self.city}。' + + +s1 = Student('Eyob', 'Yetayeh', 30, 'Finland', 'Helsinki','male') +s2 = Student('Lidiya', 'Teklemariam', 28, 'Finland', 'Espoo', 'female') +print(s1.person_info()) +s1.add_skill('JavaScript') +s1.add_skill('React') +s1.add_skill('Python') +print(s1.skills) +print(s2.person_info()) +s2.add_skill('Organizing') +s2.add_skill('Marketing') +s2.add_skill('Digital Marketing') +print(s2.skills) +``` + +```sh +# 输出 +Eyob Yetayeh今年30岁。他住在Finland的Helsinki。 +['JavaScript', 'React', 'Python'] +Lidiya Teklemariam今年28岁。她住在Finland的Espoo。 +['Organizing', 'Marketing', 'Digital Marketing'] +``` + +我们可以使用super()函数或父类名Person来自动继承父类的方法和属性。在上面的例子中,我们覆盖了父类方法。子类的person_info方法有不同的实现,即使方法名称与父类相同。 + +### 覆盖父类方法 + +如上所示,我们可以通过创建与父类方法名称相同的子类方法来覆盖父类方法。 + +## 💻 练习:第21天 + +### 练习:级别1 + +1. Python有一个名为_statistics_的模块,我们可以使用这个模块来计算统计数据。但是,让我们尝试开发一个可以计算均值、中位数、众数、标准差等统计数据的类。 + +```py +class Statistics: + def __init__(self, data=[]): + self.data = data + + def count(self): + # 你自己的实现 + pass + + def sum(self): + # 你自己的实现 + pass + + def min(self): + # 你自己的实现 + pass + + def max(self): + # 你自己的实现 + pass + + def range(self): + # 你自己的实现 + pass + + def mean(self): + # 你自己的实现 + pass + + def median(self): + # 你自己的实现 + pass + + def mode(self): + # 你自己的实现 + pass + + def standard_deviation(self): + # 你自己的实现 + pass + + def variance(self): + # 你自己的实现 + pass + + def frequency_distribution(self): + # 你自己的实现 + pass + + def describe(self): + # 你自己的实现 + pass +``` + +```py +# 测试代码 +data = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26] +statistics = Statistics(data) +print('Count:', statistics.count()) # 25 +print('Sum: ', statistics.sum()) # 730 +print('Min: ', statistics.min()) # 24 +print('Max: ', statistics.max()) # 38 +print('Range: ', statistics.range()) # 14 +print('Mean: ', statistics.mean()) # 29.2 +print('Median: ', statistics.median()) # 27 +print('Mode: ', statistics.mode()) # {'mode': 26, 'count': 5} +print('Standard Deviation: ', statistics.standard_deviation()) # 4.2 +print('Variance: ', statistics.variance()) # 17.5 +print('Frequency Distribution: ', statistics.frequency_distribution()) # [(24, 2), (25, 1), (26, 5), (27, 4), (29, 1), (31, 2), (32, 3), (33, 2), (34, 2), (37, 2), (38, 1)] +``` + +### 练习:级别2 + +1. 创建一个名为PersonAccount的类。它有firstname、lastname、incomes、expenses属性和添加收入、添加支出以及账户余额方法。 + +### 练习:级别3 + +1. 以下是使用函数的方法。让我们将其转换为类 + +```python +def print_products(*args, **kwargs): + for product in args: + print(product) + print(kwargs) + for key in kwargs: + print(f"{key}: {kwargs[key]}") + +print_products("apple", "banana", "orange", vegetable="tomato", juice="orange") +``` + +```sh +apple +banana +orange +{'vegetable': 'tomato', 'juice': 'orange'} +vegetable: tomato +juice: orange +``` + +1. 在一个名为PersonAccount的类中,我们有属性:firstname、lastname、incomes、expenses。设计一个类,用于计算一个人的净收入。 + +🎉 恭喜!🎉 + +[<< 第 20 天](./20_python_package_manager_cn.md) | [第 22 天 >>](./22_web_scraping_cn.md) \ No newline at end of file diff --git a/Chinese/22_web_scraping_cn.md b/Chinese/22_web_scraping_cn.md index 0d4c2721f..7b08eb928 100644 --- a/Chinese/22_web_scraping_cn.md +++ b/Chinese/22_web_scraping_cn.md @@ -1,89 +1,89 @@ -# 30天Python编程挑战:第22天 - 网页抓取 - -- [第22天](#-第22天) - - [Python网页抓取](#python网页抓取) - - [什么是网页抓取](#什么是网页抓取) - - [💻 练习:第22天](#-练习第22天) - -# 📘 第22天 - -## Python网页抓取 - -### 什么是网页抓取 - -互联网充满了大量的数据,这些数据可以用于不同的目的。要收集这些数据,我们需要知道如何从网站上抓取数据。 - -网页抓取是从网站提取和收集数据,并将其存储在本地机器或数据库中的过程。 - -在本节中,我们将使用beautifulsoup和requests包来抓取数据。我们使用的是beautifulsoup 4版本。 - -要开始抓取网站,你需要_requests_、_beautifoulSoup4_和一个_网站_。 - -```sh -pip install requests -pip install beautifulsoup4 -``` - -要从网站抓取数据,需要基本了解HTML标签和CSS选择器。我们使用HTML标签、类或/和ID来定位网站上的内容。 -让我们导入requests和BeautifulSoup模块: - -```py -import requests -from bs4 import BeautifulSoup -``` - -让我们声明一个url变量,用于我们要抓取的网站。 - -```py -import requests -from bs4 import BeautifulSoup -url = 'https://archive.ics.uci.edu/ml/datasets.php' - -# 让我们使用requests的get方法从url获取数据 -response = requests.get(url) -# 检查状态 -status = response.status_code -print(status) # 200表示获取成功 -``` - -```sh -200 -``` - -使用beautifulSoup解析页面内容: - -```py -import requests -from bs4 import BeautifulSoup -url = 'https://archive.ics.uci.edu/ml/datasets.php' - -response = requests.get(url) -content = response.content # 我们从网站获取所有内容 -soup = BeautifulSoup(content, 'html.parser') # beautiful soup将给我们一个解析的机会 -print(soup.title) # UCI Machine Learning Repository: Data Sets -print(soup.title.get_text()) # UCI Machine Learning Repository: Data Sets -print(soup.body) # 给出网站上的整个页面 -print(response.status_code) - -tables = soup.find_all('table', {'cellpadding':'3'}) -# 我们定位cellpadding属性值为3的表格 -# 我们可以使用id、class或HTML标签进行选择,有关更多信息,请查看beautifulsoup文档 -table = tables[0] # 结果是一个列表,我们从中提取数据 -for td in table.find('tr').find_all('td'): - print(td.text) -``` - -如果你运行这段代码,你会发现提取工作只完成了一半。你可以继续完成它,因为这是练习1的一部分。 -参考[beautifulsoup文档](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start)获取更多信息。 - -🌕 你非常特别,你每天都在进步。你只剩下八天就要达到伟大的境界了。现在做一些练习来锻炼你的大脑和肌肉。 - -## 💻 练习:第22天 - -1. 抓取以下网站并将数据存储为json文件(url = 'http://www.bu.edu/president/boston-university-facts-stats/')。 -2. 提取此url中的表格(https://archive.ics.uci.edu/ml/datasets.php)并将其更改为json文件。 -3. 抓取总统表并将数据存储为json(https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States)。这个表格结构不是很规整,抓取可能需要很长时间。 - -🎉 恭喜!🎉 - -[<< 第21天](./21_Day_Classes_and_objects/21_classes_and_objects_cn.md) | [第23天 >>](./23_Day_Virtual_environment/23_virtual_environment_cn.md) \ No newline at end of file +# 30天Python编程挑战:第22天 - 网页抓取 + +- [第22天](#-第22天) + - [Python网页抓取](#python网页抓取) + - [什么是网页抓取](#什么是网页抓取) + - [💻 练习:第22天](#-练习第22天) + +# 📘 第22天 + +## Python网页抓取 + +### 什么是网页抓取 + +互联网充满了大量的数据,这些数据可以用于不同的目的。要收集这些数据,我们需要知道如何从网站上抓取数据。 + +网页抓取是从网站提取和收集数据,并将其存储在本地机器或数据库中的过程。 + +在本节中,我们将使用beautifulsoup和requests包来抓取数据。我们使用的是beautifulsoup 4版本。 + +要开始抓取网站,你需要_requests_、_beautifoulSoup4_和一个_网站_。 + +```sh +pip install requests +pip install beautifulsoup4 +``` + +要从网站抓取数据,需要基本了解HTML标签和CSS选择器。我们使用HTML标签、类或/和ID来定位网站上的内容。 +让我们导入requests和BeautifulSoup模块: + +```py +import requests +from bs4 import BeautifulSoup +``` + +让我们声明一个url变量,用于我们要抓取的网站。 + +```py +import requests +from bs4 import BeautifulSoup +url = 'https://archive.ics.uci.edu/ml/datasets.php' + +# 让我们使用requests的get方法从url获取数据 +response = requests.get(url) +# 检查状态 +status = response.status_code +print(status) # 200表示获取成功 +``` + +```sh +200 +``` + +使用beautifulSoup解析页面内容: + +```py +import requests +from bs4 import BeautifulSoup +url = 'https://archive.ics.uci.edu/ml/datasets.php' + +response = requests.get(url) +content = response.content # 我们从网站获取所有内容 +soup = BeautifulSoup(content, 'html.parser') # beautiful soup将给我们一个解析的机会 +print(soup.title) # UCI Machine Learning Repository: Data Sets +print(soup.title.get_text()) # UCI Machine Learning Repository: Data Sets +print(soup.body) # 给出网站上的整个页面 +print(response.status_code) + +tables = soup.find_all('table', {'cellpadding':'3'}) +# 我们定位cellpadding属性值为3的表格 +# 我们可以使用id、class或HTML标签进行选择,有关更多信息,请查看beautifulsoup文档 +table = tables[0] # 结果是一个列表,我们从中提取数据 +for td in table.find('tr').find_all('td'): + print(td.text) +``` + +如果你运行这段代码,你会发现提取工作只完成了一半。你可以继续完成它,因为这是练习1的一部分。 +参考[beautifulsoup文档](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start)获取更多信息。 + +🌕 你非常特别,你每天都在进步。你只剩下八天就要达到伟大的境界了。现在做一些练习来锻炼你的大脑和肌肉。 + +## 💻 练习:第22天 + +1. 抓取以下网站并将数据存储为json文件(url = 'http://www.bu.edu/president/boston-university-facts-stats/')。 +2. 提取此url中的表格(https://archive.ics.uci.edu/ml/datasets.php)并将其更改为json文件。 +3. 抓取总统表并将数据存储为json(https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States)。这个表格结构不是很规整,抓取可能需要很长时间。 + +🎉 恭喜!🎉 + +[<< 第 21 天](./21_classes_and_objects_cn.md) | [第 23 天 >>](./23_virtual_environment_cn.md) \ No newline at end of file diff --git a/Chinese/23_virtual_environment_cn.md b/Chinese/23_virtual_environment_cn.md index a93dd34db..36cbf547a 100644 --- a/Chinese/23_virtual_environment_cn.md +++ b/Chinese/23_virtual_environment_cn.md @@ -1,97 +1,97 @@ -# 30天Python编程挑战:第23天 - 虚拟环境 - -- [第23天](#-第23天) - - [设置虚拟环境](#设置虚拟环境) - - [💻 练习:第23天](#-练习第23天) - -# 📘 第23天 - -## 设置虚拟环境 - -开始项目时,最好有一个虚拟环境。虚拟环境可以帮助我们创建一个隔离或独立的环境。这将有助于避免不同项目之间的依赖冲突。如果你在终端上输入pip freeze,你将看到计算机上安装的所有包。如果我们使用virtualenv,我们将只能访问特定于该项目的包。打开你的终端并安装virtualenv: - -```sh -asabeneh@Asabeneh:~$ pip install virtualenv -``` - -在30DaysOfPython文件夹内创建一个flask_project文件夹。 - -安装virtualenv包后,进入项目文件夹并通过以下命令创建虚拟环境: - -对于Mac/Linux: -```sh -asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ virtualenv venv -``` - -对于Windows: -```sh -C:\Users\User\Documents\30DaysOfPython\flask_project>python -m venv venv -``` - -我喜欢将新项目称为venv,但你可以随意命名。让我们使用ls(或Windows命令提示符的dir)命令检查venv是否已创建。 - -```sh -asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ ls -venv/ -``` - -让我们通过在项目文件夹中编写以下命令来激活虚拟环境。 - -对于Mac/Linux: -```sh -asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ source venv/bin/activate -``` - -Windows上虚拟环境的激活可能因Windows PowerShell和git bash而异。 - -对于Windows PowerShell: -```sh -C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\activate -``` - -对于Windows Git bash: -```sh -C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\. activate -``` - -输入激活命令后,你的项目目录将以venv开头。请参见下面的示例。 - -```sh -(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ -``` - -现在,让我们通过输入pip freeze来检查这个项目中可用的包。你不会看到任何包。 - -我们将做一个小型flask项目,所以让我们为这个项目安装flask包。 - -```sh -(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install Flask -``` - -现在,让我们输入pip freeze查看项目中已安装的包列表: - -```sh -(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip freeze -Click==7.0 -Flask==1.1.1 -itsdangerous==1.1.0 -Jinja2==2.10.3 -MarkupSafe==1.1.1 -Werkzeug==0.16.0 -``` - -完成后,你应该使用_deactivate_来关闭活动项目。 - -```sh -(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ deactivate -``` - -使用flask所需的模块已经安装好了。现在,你的项目目录已经准备好用于flask项目。你应该将venv包含在.gitignore文件中,以避免将其推送到GitHub。 - -## 💻 练习:第23天 - -1. 根据上面给出的示例创建一个带有虚拟环境的项目目录。 - -🎉 恭喜!🎉 - -[<< 第22天](./22_Day_Web_scraping/22_web_scraping_cn.md) | [第24天 >>](./24_Day_Statistics/24_statistics_cn.md) \ No newline at end of file +# 30天Python编程挑战:第23天 - 虚拟环境 + +- [第23天](#-第23天) + - [设置虚拟环境](#设置虚拟环境) + - [💻 练习:第23天](#-练习第23天) + +# 📘 第23天 + +## 设置虚拟环境 + +开始项目时,最好有一个虚拟环境。虚拟环境可以帮助我们创建一个隔离或独立的环境。这将有助于避免不同项目之间的依赖冲突。如果你在终端上输入pip freeze,你将看到计算机上安装的所有包。如果我们使用virtualenv,我们将只能访问特定于该项目的包。打开你的终端并安装virtualenv: + +```sh +asabeneh@Asabeneh:~$ pip install virtualenv +``` + +在30DaysOfPython文件夹内创建一个flask_project文件夹。 + +安装virtualenv包后,进入项目文件夹并通过以下命令创建虚拟环境: + +对于Mac/Linux: +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ virtualenv venv +``` + +对于Windows: +```sh +C:\Users\User\Documents\30DaysOfPython\flask_project>python -m venv venv +``` + +我喜欢将新项目称为venv,但你可以随意命名。让我们使用ls(或Windows命令提示符的dir)命令检查venv是否已创建。 + +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ ls +venv/ +``` + +让我们通过在项目文件夹中编写以下命令来激活虚拟环境。 + +对于Mac/Linux: +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ source venv/bin/activate +``` + +Windows上虚拟环境的激活可能因Windows PowerShell和git bash而异。 + +对于Windows PowerShell: +```sh +C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\activate +``` + +对于Windows Git bash: +```sh +C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\. activate +``` + +输入激活命令后,你的项目目录将以venv开头。请参见下面的示例。 + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ +``` + +现在,让我们通过输入pip freeze来检查这个项目中可用的包。你不会看到任何包。 + +我们将做一个小型flask项目,所以让我们为这个项目安装flask包。 + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install Flask +``` + +现在,让我们输入pip freeze查看项目中已安装的包列表: + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip freeze +Click==7.0 +Flask==1.1.1 +itsdangerous==1.1.0 +Jinja2==2.10.3 +MarkupSafe==1.1.1 +Werkzeug==0.16.0 +``` + +完成后,你应该使用_deactivate_来关闭活动项目。 + +```sh +(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ deactivate +``` + +使用flask所需的模块已经安装好了。现在,你的项目目录已经准备好用于flask项目。你应该将venv包含在.gitignore文件中,以避免将其推送到GitHub。 + +## 💻 练习:第23天 + +1. 根据上面给出的示例创建一个带有虚拟环境的项目目录。 + +🎉 恭喜!🎉 + +[<< 第 22 天](./22_web_scraping_cn.md) | [第 24 天 >>](./24_statistics_cn.md) \ No newline at end of file diff --git a/Chinese/24_statistics_cn.md b/Chinese/24_statistics_cn.md index 982216e3a..bdfeb3d22 100644 --- a/Chinese/24_statistics_cn.md +++ b/Chinese/24_statistics_cn.md @@ -1,589 +1,589 @@ -# 30天Python编程挑战:第24天 - 统计 - -- [第24天](#-第24天) - - [Python进行统计分析](#python进行统计分析) - - [统计学](#统计学) - - [数据](#数据) - - [统计模块](#统计模块) -- [NumPy](#numpy) - - [导入NumPy](#导入numpy) - - [使用NumPy创建数组](#使用numpy创建数组) - - [创建整型NumPy数组](#创建整型numpy数组) - - [创建浮点型NumPy数组](#创建浮点型numpy数组) - - [创建布尔型NumPy数组](#创建布尔型numpy数组) - - [使用NumPy创建多维数组](#使用numpy创建多维数组) - - [将NumPy数组转换为列表](#将numpy数组转换为列表) - - [从元组创建NumPy数组](#从元组创建numpy数组) - - [NumPy数组的形状](#numpy数组的形状) - - [NumPy数组的数据类型](#numpy数组的数据类型) - - [NumPy数组的大小](#numpy数组的大小) - - [使用NumPy进行数学运算](#使用numpy进行数学运算) - - [加法](#加法) - -# 📘 第24天 - -## Python进行统计分析 - -## 统计学 - -统计学是研究数据的_收集_、_组织_、_显示_、_分析_、_解释_和_呈现_的学科。 -统计学是数学的一个分支,建议作为数据科学和机器学习的先决条件。统计学是一个非常广泛的领域,但在本节中,我们将只关注最相关的部分。 -完成这个挑战后,你可以进入Web开发、数据分析、机器学习和数据科学的道路。无论你选择哪条路,在你的职业生涯中的某个时刻,你都会得到可能需要处理的数据。拥有一些统计知识将帮助你基于数据做出决策,正如他们所说的_数据会告诉我们_。 - -## 数据 - -什么是数据?数据是为某种目的收集和翻译的任何字符集,通常用于分析。它可以是任何字符,包括文本和数字、图片、声音或视频。如果数据没有放在上下文中,对人类或计算机来说都没有任何意义。为了从数据中获取意义,我们需要使用不同的工具来处理数据。 - -数据分析、数据科学或机器学习的工作流程都是从数据开始的。数据可以由某些数据源提供,也可以创建。有结构化和非结构化数据。 - -数据可以以小型或大型格式存在。我们将获得的大多数数据类型已在文件处理部分中介绍。 - -## 统计模块 - -Python的_statistics_模块提供了用于计算数值数据的数学统计的函数。该模块并不打算与第三方库如NumPy、SciPy或面向专业统计学家的专有全功能统计软件包(如Minitab、SAS和Matlab)竞争。它的目标是达到图形和科学计算器的水平。 - -# NumPy - -在第一部分中,我们将Python定义为一种优秀的通用编程语言,但在其他流行库(如numpy、scipy、matplotlib、pandas等)的帮助下,它成为了一个强大的科学计算环境。 - -NumPy是Python中科学计算的核心库。它提供了高性能的多维数组对象和用于处理这些数组的工具。 - -到目前为止,我们一直在使用vscode,但从现在开始,我建议使用Jupyter Notebook。要访问jupyter notebook,让我们安装[anaconda](https://www.anaconda.com/)。如果你使用anaconda,大多数常用的包都已包含在内,如果你已安装anaconda,就不需要再安装这些包。 - -```sh -asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ pip install numpy -``` - -## 导入NumPy - -如果你喜欢[jupyter notebook](https://github.com/Asabeneh/data-science-for-everyone/blob/master/numpy/numpy.ipynb),可以使用它 - -```py -# 如何导入numpy -import numpy as np -# 如何检查numpy包的版本 -print('numpy:', np.__version__) -# 检查可用的方法 -print(dir(np)) -``` - -## 使用NumPy创建数组 - -### 创建整型NumPy数组 - -```py -# 创建Python列表 -python_list = [1,2,3,4,5] - -# 检查数据类型 -print('Type:', type (python_list)) # -# -print(python_list) # [1, 2, 3, 4, 5] - -two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]] - -print(two_dimensional_list) # [[0, 1, 2], [3, 4, 5], [6, 7, 8]] - -# 从Python列表创建NumPy(数值Python)数组 - -numpy_array_from_list = np.array(python_list) -print(type (numpy_array_from_list)) # -print(numpy_array_from_list) # array([1, 2, 3, 4, 5]) -``` - -### 创建浮点型NumPy数组 - -使用浮点数据类型参数从列表创建浮点NumPy数组 - -```py -# Python列表 -python_list = [1,2,3,4,5] - -numy_array_from_list2 = np.array(python_list, dtype=float) -print(numy_array_from_list2) # array([1., 2., 3., 4., 5.]) -``` - -### 创建布尔型NumPy数组 - -从列表创建布尔NumPy数组 - -```py -numpy_bool_array = np.array([0, 1, -1, 0, 0], dtype=bool) -print(numpy_bool_array) # array([False, True, True, False, False]) -``` - -### 使用NumPy创建多维数组 - -一个NumPy数组可能有一个或多个行和列 - -```py -two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]] -numpy_two_dimensional_list = np.array(two_dimensional_list) -print(type (numpy_two_dimensional_list)) -print(numpy_two_dimensional_list) -``` - -```sh - -[[0 1 2] - [3 4 5] - [6 7 8]] -``` - -### 将NumPy数组转换为列表 - -```python -# 我们总是可以使用tolist()将数组转换回Python列表。 -np_to_list = numpy_array_from_list.tolist() -print(type (np_to_list)) -print('一维数组:', np_to_list) -print('二维数组: ', numpy_two_dimensional_list.tolist()) -``` - -```sh - -一维数组: [1, 2, 3, 4, 5] -二维数组: [[0, 1, 2], [3, 4, 5], [6, 7, 8]] -``` - -### 从元组创建NumPy数组 - -```py -# 从元组创建NumPy数组 -# 在Python中创建元组 -python_tuple = (1,2,3,4,5) -print(type (python_tuple)) # -print('python_tuple: ', python_tuple) # python_tuple: (1, 2, 3, 4, 5) - -numpy_array_from_tuple = np.array(python_tuple) -print(type (numpy_array_from_tuple)) # -print('numpy_array_from_tuple: ', numpy_array_from_tuple) # numpy_array_from_tuple: [1 2 3 4 5] -``` - -### NumPy数组的形状 - -shape方法以元组形式提供数组的形状。第一个是行,第二个是列。如果数组只是一维的,它返回数组的大小。 - -```py -nums = np.array([1, 2, 3, 4, 5]) -print(nums) -print('nums的形状: ', nums.shape) -print(numpy_two_dimensional_list) -print('numpy_two_dimensional_list的形状: ', numpy_two_dimensional_list.shape) -three_by_four_array = np.array([[0, 1, 2, 3], - [4,5,6,7], - [8,9,10, 11]]) -print(three_by_four_array.shape) -``` - -```sh -[1 2 3 4 5] -nums的形状: (5,) -[[0 1 2] - [3 4 5] - [6 7 8]] -numpy_two_dimensional_list的形状: (3, 3) -(3, 4) -``` - -### NumPy数组的数据类型 - -数据类型的类型:str, int, float, complex, bool, list, None - -```py -int_lists = [-3, -2, -1, 0, 1, 2,3] -int_array = np.array(int_lists) -float_array = np.array(int_lists, dtype=float) - -print(int_array) -print(int_array.dtype) -print(float_array) -print(float_array.dtype) -``` - -```sh -[-3 -2 -1 0 1 2 3] -int64 -[-3. -2. -1. 0. 1. 2. 3.] -float64 -``` - -### NumPy数组的大小 - -在NumPy中,要知道NumPy数组列表中的项目数,我们使用size - -```py -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -two_dimensional_list = np.array([[0, 1, 2], - [3, 4, 5], - [6, 7, 8]]) - -print('大小:', numpy_array_from_list.size) # 5 -print('大小:', two_dimensional_list.size) # 9 -``` - -```sh -大小: 5 -大小: 9 -``` - -## 使用NumPy进行数学运算 - -NumPy数组与Python列表不完全相同。要对Python列表进行数学运算,我们必须遍历项目,但NumPy可以不通过循环就进行任何数学运算。 -数学运算: - -- 加法 (+) -- 减法 (-) -- 乘法 (*) -- 除法 (/) -- 模数 (%) -- 整除 (//) -- 指数 (**) - -### 加法 - -```py -# 声明 -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -print('原始数组: ', numpy_array_from_list) -print('加法: ', numpy_array_from_list + 2) -print('加法: ', np.add(numpy_array_from_list, 2)) -``` - -```sh -原始数组: [1 2 3 4 5] -加法: [3 4 5 6 7] -加法: [3 4 5 6 7] -``` - -### 减法 - -```py -# 声明 -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -print('原始数组: ', numpy_array_from_list) -print('减法: ', numpy_array_from_list - 2) -print('减法: ', np.subtract(numpy_array_from_list, 2)) -``` - -```sh -原始数组: [1 2 3 4 5] -减法: [-1 0 1 2 3] -减法: [-1 0 1 2 3] -``` - -### 乘法 - -```py -# 声明 -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -print('原始数组: ', numpy_array_from_list) -print('乘法: ', numpy_array_from_list * 2) -print('乘法: ', np.multiply(numpy_array_from_list, 2)) -``` - -```sh -原始数组: [1 2 3 4 5] -乘法: [ 2 4 6 8 10] -乘法: [ 2 4 6 8 10] -``` - -### 除法 - -```py -# 声明 -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -print('原始数组: ', numpy_array_from_list) -print('除法: ', numpy_array_from_list / 2) -print('除法: ', np.divide(numpy_array_from_list, 2)) -``` - -```sh -原始数组: [1 2 3 4 5] -除法: [0.5 1. 1.5 2. 2.5] -除法: [0.5 1. 1.5 2. 2.5] -``` - -### 模数 - -```py -# 声明 -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -print('原始数组: ', numpy_array_from_list) -print('模数: ', numpy_array_from_list % 2) -print('模数: ', np.mod(numpy_array_from_list, 2)) -``` - -```sh -原始数组: [1 2 3 4 5] -模数: [1 0 1 0 1] -模数: [1 0 1 0 1] -``` - -### 整除 - -```py -# 声明 -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -print('原始数组: ', numpy_array_from_list) -print('整除: ', numpy_array_from_list // 2) -print('整除: ', np.floor_divide(numpy_array_from_list, 2)) -``` - -```sh -原始数组: [1 2 3 4 5] -整除: [0 1 1 2 2] -整除: [0 1 1 2 2] -``` - -### 指数 - -```py -# 声明 -numpy_array_from_list = np.array([1, 2, 3, 4, 5]) -print('原始数组: ', numpy_array_from_list) -print('指数: ', numpy_array_from_list ** 2) -print('指数: ', np.power(numpy_array_from_list, 2)) -``` - -```sh -原始数组: [1 2 3 4 5] -指数: [ 1 4 9 16 25] -指数: [ 1 4 9 16 25] -``` - -## 检查数据类型 - -```py -numpy_int_arr = np.array([1, 2, 3, 4]) -numpy_float_arr = np.array([1.1, 2.0, 3.2]) -numpy_bool_arr = np.array([-3, -2, 0, 1, 2, 3], dtype='bool') - -print(numpy_int_arr.dtype) -print(numpy_float_arr.dtype) -print(numpy_bool_arr.dtype) -``` - -```sh -int64 -float64 -bool -``` - -## 转换类型 - -我们可以使用astype将数据类型从一种类型转换为另一种类型。让我们将int类型转换为浮点数,浮点数转换为整数,整数转换为布尔型。 - -```py -numpy_int_arr = np.array([1, 2, 3, 4], dtype='float') -numpy_int_arr.astype('int').dtype -numpy_float_arr = np.array([1.1, 2.0, 3.2]) -numpy_float_arr.astype('int').dtype -numpy_int_arr = np.array([-3, -2, 0, 1, 2, 3]) -numpy_int_arr.astype('bool').dtype -``` - -```sh -int64 -int64 -bool -``` - -## 多维数组 - -NumPy的主要优点之一是处理多维数组。我们先构建多维数组。 - -```py -two_dimension_array = np.array([(1,2,3),(4,5,6), (7,8,9)]) -print(type (two_dimension_array)) -print(two_dimension_array) -print('形状: ', two_dimension_array.shape) -print('大小: ', two_dimension_array.size) -print('数据类型: ', two_dimension_array.dtype) -``` - -```sh - -[[1 2 3] - [4 5 6] - [7 8 9]] -形状: (3, 3) -大小: 9 -数据类型: int64 -``` - -### 从NumPy中获取项目 - -```py -# 二维数组 -two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]]) -first_row = two_dimension_array[0] -second_row = two_dimension_array[1] -third_row = two_dimension_array[2] -print('第一行:', first_row) -print('第二行:', second_row) -print('第三行: ', third_row) -``` - -```sh -第一行: [1 2 3] -第二行: [4 5 6] -第三行: [7 8 9] -``` - -现在让我们获取每一行的第一项: - -```py -first_column= two_dimension_array[:,0] -second_column = two_dimension_array[:,1] -third_column = two_dimension_array[:,2] -print('第一列:', first_column) -print('第二列:', second_column) -print('第三列: ', third_column) -``` - -```sh -第一列: [1 4 7] -第二列: [2 5 8] -第三列: [3 6 9] -``` - -## NumPy数组切片 - -切片NumPy数组与切片Python列表相似,只是它适用于两个维度(行和列)。让我们先看看如何从NumPy数组中切片项目。 - -```py -numpy_array_from_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) -print('原始数组:', numpy_array_from_list) - -# 第一个参数代表:起始位置 -# 第二个参数代表:停止位置 -# 第三个参数代表:步长 -print('第一个参数代表:起始位置') -print('第二个参数代表:停止位置') -print('第三个参数代表:步长') -# 使用正index -ten_first_items = numpy_array_from_list[0:10] -print('前10项:', ten_first_items) -first_five_items = numpy_array_from_list[:5] -print('前5项:', first_five_items) -last_five_items = numpy_array_from_list[5:] -print('后5项:', last_five_items) -# 使用负index -last_five_items = numpy_array_from_list[-5:] -print('后5项:', last_five_items) -``` - -```sh -原始数组: [ 1 2 3 4 5 6 7 8 9 10] -第一个参数代表:起始位置 -第二个参数代表:停止位置 -第三个参数代表:步长 -前10项: [ 1 2 3 4 5 6 7 8 9 10] -前5项: [1 2 3 4 5] -后5项: [ 6 7 8 9 10] -后5项: [ 6 7 8 9 10] -``` - -现在,让我们通过设置步长来访问每个2个项目: - -```py -every_two_item = numpy_array_from_list[::2] -print('每隔一项:', every_two_item) -``` - -```sh -每隔一项: [1 3 5 7 9] -``` - -让我们反转数组: - -```py -reversed_array = numpy_array_from_list[::-1] -print('反转数组:', reversed_array) -``` - -```sh -反转数组: [10 9 8 7 6 5 4 3 2 1] -``` - -我们可以在NumPy二维数组上使用切片: - -```py -two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]]) -print(two_dimension_array) -print(two_dimension_array[1, 1]) -print(two_dimension_array[1, 1:3]) -print(two_dimension_array[1:3, 1:3]) -``` - -```sh -[[1 2 3] - [4 5 6] - [7 8 9]] -5 -[5 6] -[[5 6] - [8 9]] -``` - -## NumPy连接数组 - -NumPy提供了连接数组的方法。 - -```py -first_array = np.array([1, 2, 3]) -second_array = np.array([4, 5, 6]) -third_array = np.array([7, 8, 9]) -print('第一个数组:', first_array) -print('第二个数组:', second_array) -print('第三个数组:', third_array) -``` - -```sh -第一个数组: [1 2 3] -第二个数组: [4 5 6] -第三个数组: [7 8 9] -``` - -### 水平连接 - -```py -horizontal_concat = np.hstack((first_array, second_array, third_array)) -print('水平连接:', horizontal_concat) -``` - -```sh -水平连接: [1 2 3 4 5 6 7 8 9] -``` - -### 垂直连接 - -```py -vertical_concat = np.vstack((first_array, second_array, third_array)) -print('垂直连接:', vertical_concat) -``` - -```sh -垂直连接: -[[1 2 3] - [4 5 6] - [7 8 9]] -``` - -## 常见NumPy函数 - -我们看看最常见的NumPy函数: - -### 最小值、最大值、平均值、中位数和百分位数 - -```py -numpy_array_from_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) -print('最小值:', numpy_array_from_list.min()) -print('最大值:', numpy_array_from_list.max()) -print('平均值:', numpy_array_from_list.mean()) -``` - -🎉 恭喜!🎉 - -[<< 第23天](./23_Day_Virtual_environment/23_virtual_environment_cn.md) | [第25天 >>](./25_Day_Pandas/25_pandas_cn.md) \ No newline at end of file +# 30天Python编程挑战:第24天 - 统计 + +- [第24天](#-第24天) + - [Python进行统计分析](#python进行统计分析) + - [统计学](#统计学) + - [数据](#数据) + - [统计模块](#统计模块) +- [NumPy](#numpy) + - [导入NumPy](#导入numpy) + - [使用NumPy创建数组](#使用numpy创建数组) + - [创建整型NumPy数组](#创建整型numpy数组) + - [创建浮点型NumPy数组](#创建浮点型numpy数组) + - [创建布尔型NumPy数组](#创建布尔型numpy数组) + - [使用NumPy创建多维数组](#使用numpy创建多维数组) + - [将NumPy数组转换为列表](#将numpy数组转换为列表) + - [从元组创建NumPy数组](#从元组创建numpy数组) + - [NumPy数组的形状](#numpy数组的形状) + - [NumPy数组的数据类型](#numpy数组的数据类型) + - [NumPy数组的大小](#numpy数组的大小) + - [使用NumPy进行数学运算](#使用numpy进行数学运算) + - [加法](#加法) + +# 📘 第24天 + +## Python进行统计分析 + +## 统计学 + +统计学是研究数据的_收集_、_组织_、_显示_、_分析_、_解释_和_呈现_的学科。 +统计学是数学的一个分支,建议作为数据科学和机器学习的先决条件。统计学是一个非常广泛的领域,但在本节中,我们将只关注最相关的部分。 +完成这个挑战后,你可以进入Web开发、数据分析、机器学习和数据科学的道路。无论你选择哪条路,在你的职业生涯中的某个时刻,你都会得到可能需要处理的数据。拥有一些统计知识将帮助你基于数据做出决策,正如他们所说的_数据会告诉我们_。 + +## 数据 + +什么是数据?数据是为某种目的收集和翻译的任何字符集,通常用于分析。它可以是任何字符,包括文本和数字、图片、声音或视频。如果数据没有放在上下文中,对人类或计算机来说都没有任何意义。为了从数据中获取意义,我们需要使用不同的工具来处理数据。 + +数据分析、数据科学或机器学习的工作流程都是从数据开始的。数据可以由某些数据源提供,也可以创建。有结构化和非结构化数据。 + +数据可以以小型或大型格式存在。我们将获得的大多数数据类型已在文件处理部分中介绍。 + +## 统计模块 + +Python的_statistics_模块提供了用于计算数值数据的数学统计的函数。该模块并不打算与第三方库如NumPy、SciPy或面向专业统计学家的专有全功能统计软件包(如Minitab、SAS和Matlab)竞争。它的目标是达到图形和科学计算器的水平。 + +# NumPy + +在第一部分中,我们将Python定义为一种优秀的通用编程语言,但在其他流行库(如numpy、scipy、matplotlib、pandas等)的帮助下,它成为了一个强大的科学计算环境。 + +NumPy是Python中科学计算的核心库。它提供了高性能的多维数组对象和用于处理这些数组的工具。 + +到目前为止,我们一直在使用vscode,但从现在开始,我建议使用Jupyter Notebook。要访问jupyter notebook,让我们安装[anaconda](https://www.anaconda.com/)。如果你使用anaconda,大多数常用的包都已包含在内,如果你已安装anaconda,就不需要再安装这些包。 + +```sh +asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ pip install numpy +``` + +## 导入NumPy + +如果你喜欢[jupyter notebook](https://github.com/Asabeneh/data-science-for-everyone/blob/master/numpy/numpy.ipynb),可以使用它 + +```py +# 如何导入numpy +import numpy as np +# 如何检查numpy包的版本 +print('numpy:', np.__version__) +# 检查可用的方法 +print(dir(np)) +``` + +## 使用NumPy创建数组 + +### 创建整型NumPy数组 + +```py +# 创建Python列表 +python_list = [1,2,3,4,5] + +# 检查数据类型 +print('Type:', type (python_list)) # +# +print(python_list) # [1, 2, 3, 4, 5] + +two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]] + +print(two_dimensional_list) # [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + +# 从Python列表创建NumPy(数值Python)数组 + +numpy_array_from_list = np.array(python_list) +print(type (numpy_array_from_list)) # +print(numpy_array_from_list) # array([1, 2, 3, 4, 5]) +``` + +### 创建浮点型NumPy数组 + +使用浮点数据类型参数从列表创建浮点NumPy数组 + +```py +# Python列表 +python_list = [1,2,3,4,5] + +numy_array_from_list2 = np.array(python_list, dtype=float) +print(numy_array_from_list2) # array([1., 2., 3., 4., 5.]) +``` + +### 创建布尔型NumPy数组 + +从列表创建布尔NumPy数组 + +```py +numpy_bool_array = np.array([0, 1, -1, 0, 0], dtype=bool) +print(numpy_bool_array) # array([False, True, True, False, False]) +``` + +### 使用NumPy创建多维数组 + +一个NumPy数组可能有一个或多个行和列 + +```py +two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]] +numpy_two_dimensional_list = np.array(two_dimensional_list) +print(type (numpy_two_dimensional_list)) +print(numpy_two_dimensional_list) +``` + +```sh + +[[0 1 2] + [3 4 5] + [6 7 8]] +``` + +### 将NumPy数组转换为列表 + +```python +# 我们总是可以使用tolist()将数组转换回Python列表。 +np_to_list = numpy_array_from_list.tolist() +print(type (np_to_list)) +print('一维数组:', np_to_list) +print('二维数组: ', numpy_two_dimensional_list.tolist()) +``` + +```sh + +一维数组: [1, 2, 3, 4, 5] +二维数组: [[0, 1, 2], [3, 4, 5], [6, 7, 8]] +``` + +### 从元组创建NumPy数组 + +```py +# 从元组创建NumPy数组 +# 在Python中创建元组 +python_tuple = (1,2,3,4,5) +print(type (python_tuple)) # +print('python_tuple: ', python_tuple) # python_tuple: (1, 2, 3, 4, 5) + +numpy_array_from_tuple = np.array(python_tuple) +print(type (numpy_array_from_tuple)) # +print('numpy_array_from_tuple: ', numpy_array_from_tuple) # numpy_array_from_tuple: [1 2 3 4 5] +``` + +### NumPy数组的形状 + +shape方法以元组形式提供数组的形状。第一个是行,第二个是列。如果数组只是一维的,它返回数组的大小。 + +```py +nums = np.array([1, 2, 3, 4, 5]) +print(nums) +print('nums的形状: ', nums.shape) +print(numpy_two_dimensional_list) +print('numpy_two_dimensional_list的形状: ', numpy_two_dimensional_list.shape) +three_by_four_array = np.array([[0, 1, 2, 3], + [4,5,6,7], + [8,9,10, 11]]) +print(three_by_four_array.shape) +``` + +```sh +[1 2 3 4 5] +nums的形状: (5,) +[[0 1 2] + [3 4 5] + [6 7 8]] +numpy_two_dimensional_list的形状: (3, 3) +(3, 4) +``` + +### NumPy数组的数据类型 + +数据类型的类型:str, int, float, complex, bool, list, None + +```py +int_lists = [-3, -2, -1, 0, 1, 2,3] +int_array = np.array(int_lists) +float_array = np.array(int_lists, dtype=float) + +print(int_array) +print(int_array.dtype) +print(float_array) +print(float_array.dtype) +``` + +```sh +[-3 -2 -1 0 1 2 3] +int64 +[-3. -2. -1. 0. 1. 2. 3.] +float64 +``` + +### NumPy数组的大小 + +在NumPy中,要知道NumPy数组列表中的项目数,我们使用size + +```py +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +two_dimensional_list = np.array([[0, 1, 2], + [3, 4, 5], + [6, 7, 8]]) + +print('大小:', numpy_array_from_list.size) # 5 +print('大小:', two_dimensional_list.size) # 9 +``` + +```sh +大小: 5 +大小: 9 +``` + +## 使用NumPy进行数学运算 + +NumPy数组与Python列表不完全相同。要对Python列表进行数学运算,我们必须遍历项目,但NumPy可以不通过循环就进行任何数学运算。 +数学运算: + +- 加法 (+) +- 减法 (-) +- 乘法 (*) +- 除法 (/) +- 模数 (%) +- 整除 (//) +- 指数 (**) + +### 加法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('加法: ', numpy_array_from_list + 2) +print('加法: ', np.add(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +加法: [3 4 5 6 7] +加法: [3 4 5 6 7] +``` + +### 减法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('减法: ', numpy_array_from_list - 2) +print('减法: ', np.subtract(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +减法: [-1 0 1 2 3] +减法: [-1 0 1 2 3] +``` + +### 乘法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('乘法: ', numpy_array_from_list * 2) +print('乘法: ', np.multiply(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +乘法: [ 2 4 6 8 10] +乘法: [ 2 4 6 8 10] +``` + +### 除法 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('除法: ', numpy_array_from_list / 2) +print('除法: ', np.divide(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +除法: [0.5 1. 1.5 2. 2.5] +除法: [0.5 1. 1.5 2. 2.5] +``` + +### 模数 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('模数: ', numpy_array_from_list % 2) +print('模数: ', np.mod(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +模数: [1 0 1 0 1] +模数: [1 0 1 0 1] +``` + +### 整除 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('整除: ', numpy_array_from_list // 2) +print('整除: ', np.floor_divide(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +整除: [0 1 1 2 2] +整除: [0 1 1 2 2] +``` + +### 指数 + +```py +# 声明 +numpy_array_from_list = np.array([1, 2, 3, 4, 5]) +print('原始数组: ', numpy_array_from_list) +print('指数: ', numpy_array_from_list ** 2) +print('指数: ', np.power(numpy_array_from_list, 2)) +``` + +```sh +原始数组: [1 2 3 4 5] +指数: [ 1 4 9 16 25] +指数: [ 1 4 9 16 25] +``` + +## 检查数据类型 + +```py +numpy_int_arr = np.array([1, 2, 3, 4]) +numpy_float_arr = np.array([1.1, 2.0, 3.2]) +numpy_bool_arr = np.array([-3, -2, 0, 1, 2, 3], dtype='bool') + +print(numpy_int_arr.dtype) +print(numpy_float_arr.dtype) +print(numpy_bool_arr.dtype) +``` + +```sh +int64 +float64 +bool +``` + +## 转换类型 + +我们可以使用astype将数据类型从一种类型转换为另一种类型。让我们将int类型转换为浮点数,浮点数转换为整数,整数转换为布尔型。 + +```py +numpy_int_arr = np.array([1, 2, 3, 4], dtype='float') +numpy_int_arr.astype('int').dtype +numpy_float_arr = np.array([1.1, 2.0, 3.2]) +numpy_float_arr.astype('int').dtype +numpy_int_arr = np.array([-3, -2, 0, 1, 2, 3]) +numpy_int_arr.astype('bool').dtype +``` + +```sh +int64 +int64 +bool +``` + +## 多维数组 + +NumPy的主要优点之一是处理多维数组。我们先构建多维数组。 + +```py +two_dimension_array = np.array([(1,2,3),(4,5,6), (7,8,9)]) +print(type (two_dimension_array)) +print(two_dimension_array) +print('形状: ', two_dimension_array.shape) +print('大小: ', two_dimension_array.size) +print('数据类型: ', two_dimension_array.dtype) +``` + +```sh + +[[1 2 3] + [4 5 6] + [7 8 9]] +形状: (3, 3) +大小: 9 +数据类型: int64 +``` + +### 从NumPy中获取项目 + +```py +# 二维数组 +two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]]) +first_row = two_dimension_array[0] +second_row = two_dimension_array[1] +third_row = two_dimension_array[2] +print('第一行:', first_row) +print('第二行:', second_row) +print('第三行: ', third_row) +``` + +```sh +第一行: [1 2 3] +第二行: [4 5 6] +第三行: [7 8 9] +``` + +现在让我们获取每一行的第一项: + +```py +first_column= two_dimension_array[:,0] +second_column = two_dimension_array[:,1] +third_column = two_dimension_array[:,2] +print('第一列:', first_column) +print('第二列:', second_column) +print('第三列: ', third_column) +``` + +```sh +第一列: [1 4 7] +第二列: [2 5 8] +第三列: [3 6 9] +``` + +## NumPy数组切片 + +切片NumPy数组与切片Python列表相似,只是它适用于两个维度(行和列)。让我们先看看如何从NumPy数组中切片项目。 + +```py +numpy_array_from_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) +print('原始数组:', numpy_array_from_list) + +# 第一个参数代表:起始位置 +# 第二个参数代表:停止位置 +# 第三个参数代表:步长 +print('第一个参数代表:起始位置') +print('第二个参数代表:停止位置') +print('第三个参数代表:步长') +# 使用正index +ten_first_items = numpy_array_from_list[0:10] +print('前10项:', ten_first_items) +first_five_items = numpy_array_from_list[:5] +print('前5项:', first_five_items) +last_five_items = numpy_array_from_list[5:] +print('后5项:', last_five_items) +# 使用负index +last_five_items = numpy_array_from_list[-5:] +print('后5项:', last_five_items) +``` + +```sh +原始数组: [ 1 2 3 4 5 6 7 8 9 10] +第一个参数代表:起始位置 +第二个参数代表:停止位置 +第三个参数代表:步长 +前10项: [ 1 2 3 4 5 6 7 8 9 10] +前5项: [1 2 3 4 5] +后5项: [ 6 7 8 9 10] +后5项: [ 6 7 8 9 10] +``` + +现在,让我们通过设置步长来访问每个2个项目: + +```py +every_two_item = numpy_array_from_list[::2] +print('每隔一项:', every_two_item) +``` + +```sh +每隔一项: [1 3 5 7 9] +``` + +让我们反转数组: + +```py +reversed_array = numpy_array_from_list[::-1] +print('反转数组:', reversed_array) +``` + +```sh +反转数组: [10 9 8 7 6 5 4 3 2 1] +``` + +我们可以在NumPy二维数组上使用切片: + +```py +two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]]) +print(two_dimension_array) +print(two_dimension_array[1, 1]) +print(two_dimension_array[1, 1:3]) +print(two_dimension_array[1:3, 1:3]) +``` + +```sh +[[1 2 3] + [4 5 6] + [7 8 9]] +5 +[5 6] +[[5 6] + [8 9]] +``` + +## NumPy连接数组 + +NumPy提供了连接数组的方法。 + +```py +first_array = np.array([1, 2, 3]) +second_array = np.array([4, 5, 6]) +third_array = np.array([7, 8, 9]) +print('第一个数组:', first_array) +print('第二个数组:', second_array) +print('第三个数组:', third_array) +``` + +```sh +第一个数组: [1 2 3] +第二个数组: [4 5 6] +第三个数组: [7 8 9] +``` + +### 水平连接 + +```py +horizontal_concat = np.hstack((first_array, second_array, third_array)) +print('水平连接:', horizontal_concat) +``` + +```sh +水平连接: [1 2 3 4 5 6 7 8 9] +``` + +### 垂直连接 + +```py +vertical_concat = np.vstack((first_array, second_array, third_array)) +print('垂直连接:', vertical_concat) +``` + +```sh +垂直连接: +[[1 2 3] + [4 5 6] + [7 8 9]] +``` + +## 常见NumPy函数 + +我们看看最常见的NumPy函数: + +### 最小值、最大值、平均值、中位数和百分位数 + +```py +numpy_array_from_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) +print('最小值:', numpy_array_from_list.min()) +print('最大值:', numpy_array_from_list.max()) +print('平均值:', numpy_array_from_list.mean()) +``` + +🎉 恭喜!🎉 + +[<< 第 23 天](./23_virtual_environment_cn.md) | [第 25 天 >>](./25_pandas_cn.md) \ No newline at end of file diff --git a/Chinese/25_pandas_cn.md b/Chinese/25_pandas_cn.md index f8abe23b8..62d5e0286 100644 --- a/Chinese/25_pandas_cn.md +++ b/Chinese/25_pandas_cn.md @@ -1,551 +1,551 @@ -# 30天Python编程挑战:第25天 - Pandas - -- [第25天](#-第25天) - - [Pandas](#pandas) - - [安装Pandas](#安装pandas) - - [导入Pandas](#导入pandas) - - [使用默认索引创建Pandas系列](#使用默认索引创建pandas系列) - - [使用自定义索引创建Pandas系列](#使用自定义索引创建pandas系列) - - [从字典创建Pandas系列](#从字典创建pandas系列) - - [创建常量Pandas系列](#创建常量pandas系列) - - [使用Linspace创建Pandas系列](#使用linspace创建pandas系列) - - [数据框(DataFrames)](#数据框dataframes) - - [从列表的列表创建数据框](#从列表的列表创建数据框) - - [使用字典创建数据框](#使用字典创建数据框) - - [从字典列表创建数据框](#从字典列表创建数据框) - - [使用Pandas读取CSV文件](#使用pandas读取csv文件) - - [数据探索](#数据探索) - - [修改数据框](#修改数据框) - - [创建数据框](#创建数据框) - - [添加新列](#添加新列) - - [修改列值](#修改列值) - - [格式化数据框列](#格式化数据框列) - - [检查列值的数据类型](#检查列值的数据类型) - - [布尔索引](#布尔索引) - - [练习:第25天](#练习第25天) - -# 📘 第25天 - -## Pandas - -Pandas是一个开源的、高性能的、易于使用的Python编程语言数据结构和数据分析工具。 -Pandas添加了设计用于处理表格数据的数据结构和工具,这些数据结构是*系列(Series)*和*数据框(Data Frames)*。 -Pandas提供了用于数据操作的工具: - -- 重塑 -- 合并 -- 排序 -- 切片 -- 聚合 -- 插补 -如果你使用的是anaconda,则不必安装pandas。 - -### 安装Pandas - -对于Mac: -```py -pip install conda -conda install pandas -``` - -对于Windows: -```py -pip install conda -pip install pandas -``` - -Pandas数据结构基于*系列(Series)*和*数据框(DataFrames)*。 - -*系列*是一个*列*,而数据框是由*系列*集合组成的*多维表*。为了创建pandas系列,我们应该使用numpy创建一维数组或Python列表。 -让我们看一个系列的例子: - -名称Pandas系列 - -![pandas series](../images/pandas-series-1.png) - -国家系列 - -![pandas series](../images/pandas-series-2.png) - -城市系列 - -![pandas series](../images/pandas-series-3.png) - -如你所见,pandas系列只是一列数据。如果我们想要有多列,我们使用数据框。下面的例子显示了pandas数据框。 - -让我们看一个pandas数据框的例子: - -![Pandas data frame](../images/pandas-dataframe-1.png) - -数据框是行和列的集合。看看下面的表格;它比上面的例子有更多的列: - -![Pandas data frame](../images/pandas-dataframe-2.png) - -接下来,我们将看到如何导入pandas以及如何使用pandas创建系列和数据框 - -### 导入Pandas - -```python -import pandas as pd # 将pandas导入为pd -import numpy as np # 将numpy导入为np -``` - -### 使用默认索引创建Pandas系列 - -```python -nums = [1, 2, 3, 4,5] -s = pd.Series(nums) -print(s) -``` - -```sh -0 1 -1 2 -2 3 -3 4 -4 5 -dtype: int64 -``` - -### 使用自定义索引创建Pandas系列 - -```python -nums = [1, 2, 3, 4, 5] -s = pd.Series(nums, index=[1, 2, 3, 4, 5]) -print(s) -``` - -```sh -1 1 -2 2 -3 3 -4 4 -5 5 -dtype: int64 -``` - -```python -fruits = ['Orange','Banana','Mango'] -fruits = pd.Series(fruits, index=[1, 2, 3]) -print(fruits) -``` - -```sh -1 Orange -2 Banana -3 Mango -dtype: object -``` - -### 从字典创建Pandas系列 - -```python -dct = {'name':'Asabeneh','country':'Finland','city':'Helsinki'} -``` - -```python -s = pd.Series(dct) -print(s) -``` - -```sh -name Asabeneh -country Finland -city Helsinki -dtype: object -``` - -### 创建常量Pandas系列 - -```python -s = pd.Series(10, index = [1, 2, 3]) -print(s) -``` - -```sh -1 10 -2 10 -3 10 -dtype: int64 -``` - -### 使用Linspace创建Pandas系列 - -```python -s = pd.Series(np.linspace(5, 20, 10)) # linspace(起始点, 终点, 项目数) -print(s) -``` - -```sh -0 5.000000 -1 6.666667 -2 8.333333 -3 10.000000 -4 11.666667 -5 13.333333 -6 15.000000 -7 16.666667 -8 18.333333 -9 20.000000 -dtype: float64 -``` - -## 数据框(DataFrames) - -Pandas数据框可以以不同的方式创建: - -- 从列表的列表创建 -- 从字典创建 -- 从字典的列表创建 -- 从CSV文件创建 - -### 从列表的列表创建数据框 - -```python -data = [ - ['Asabeneh', 'Finland', 'Helsinki'], - ['David', 'UK', 'London'], - ['John', 'Sweden', 'Stockholm'] -] -df = pd.DataFrame(data, columns=['Name', 'Country', 'City']) -print(df) -``` - -```sh - Name Country City -0 Asabeneh Finland Helsinki -1 David UK London -2 John Sweden Stockholm -``` - -### 使用字典创建数据框 - -```python -data = {'Name': ['Asabeneh', 'David', 'John'], 'Country':[ - 'Finland', 'UK', 'Sweden'], 'City': ['Helsinki', 'London', 'Stockholm']} -df = pd.DataFrame(data) -print(df) -``` - -```sh - Name Country City -0 Asabeneh Finland Helsinki -1 David UK London -2 John Sweden Stockholm -``` - -### 从字典列表创建数据框 - -```python -data = [ - {'Name': 'Asabeneh', 'Country': 'Finland', 'City': 'Helsinki'}, - {'Name': 'David', 'Country': 'UK', 'City': 'London'}, - {'Name': 'John', 'Country': 'Sweden', 'City': 'Stockholm'}] -df = pd.DataFrame(data) -print(df) -``` - -```sh - Name Country City -0 Asabeneh Finland Helsinki -1 David UK London -2 John Sweden Stockholm -``` - -## 使用Pandas读取CSV文件 - -让我们在数据目录中读取文件,将通过将文件路径作为参数传递给pd.read_csv()函数来读取weight-height.csv文件。让我们使用head()方法查看前五行。 - -```python -import pandas as pd - -df = pd.read_csv('./data/weight-height.csv') -print(df.head()) # 默认为前五行 -``` - -```sh - Gender Height Weight -0 Male 73.847017 241.893563 -1 Male 68.781904 162.310473 -2 Male 74.110105 212.740856 -3 Male 71.730978 220.042470 -4 Male 69.881796 206.349801 -``` - -让我们使用tail()方法查看最后五行: - -```python -print(df.tail()) # 最后五行 -``` - -```sh - Gender Height Weight -9995 Female 66.172652 136.777454 -9996 Female 67.067155 170.867906 -9997 Female 63.867992 128.475319 -9998 Female 69.034243 163.852461 -9999 Female 61.944246 113.649103 -``` - -### 数据探索 - -让我们使用shape属性获取行和列的数量: -```python -print(df.shape) # 行和列的数量 -``` - -```sh -(10000, 3) -``` - -如你所见,该数据集有10000行和3列。让我们获取有关数据的更多信息: - -```python -print(df.columns) # 列名 -print(df.head(10)) # 前10行 -print(df.tail(10)) # 最后10行 -print(df['Gender'].value_counts()) # 计算每个值有多少个 -print(df.describe()) # 数据统计概要 -``` - -```sh -Index(['Gender', 'Height', 'Weight'], dtype='object') - Gender Height Weight -0 Male 73.847017 241.893563 -1 Male 68.781904 162.310473 -2 Male 74.110105 212.740856 -3 Male 71.730978 220.042470 -4 Male 69.881796 206.349801 -5 Male 68.767792 152.212156 -6 Male 67.961960 183.927889 -7 Male 68.563817 175.929316 -8 Male 71.267570 196.028855 -9 Male 72.040119 205.801386 - Gender Height Weight -9990 Female 64.744846 139.725595 -9991 Female 62.109532 132.451630 -9992 Female 62.593008 130.727432 -9993 Female 62.100222 131.220717 -9994 Female 63.421888 133.330246 -9995 Female 66.172652 136.777454 -9996 Female 67.067155 170.867906 -9997 Female 63.867992 128.475319 -9998 Female 69.034243 163.852461 -9999 Female 61.944246 113.649103 -Gender -Male 5000 -Female 5000 -Name: count, dtype: int64 - Height Weight -count 10000.000000 10000.000000 -mean 66.367560 161.440357 -std 3.847528 32.108439 -min 54.263133 64.700127 -25% 63.505620 135.818051 -50% 66.318070 161.212928 -75% 69.174262 187.169525 -max 78.998742 269.989699 -``` - -## 修改数据框 - -### 创建数据框 - -首先,让我们使用前面学到的内容创建一个数据框: - -```python -# 导入pandas包 -import pandas as pd -# 导入numpy包 -import numpy as np -# 数据 -data = [ - {"Name": "张三", "Country":"中国", "City":"上海"}, - {"Name": "李四", "Country":"中国", "City":"北京"}, - {"Name": "王五", "Country":"中国", "City":"广州"}] -# 创建一个数据框 -df = pd.DataFrame(data) -print(df) -``` - -```sh - Name Country City -0 张三 中国 上海 -1 李四 中国 北京 -2 王五 中国 广州 -``` - -### 添加新列 - -让我们向DataFrame添加权重列: - -```python -weights = [74, 78, 69] -df['Weight'] = weights -df -``` - -```sh - Name Country City Weight -0 张三 中国 上海 74 -1 李四 中国 北京 78 -2 王五 中国 广州 69 -``` - -让我们添加一个高度列: - -```python -heights = [173, 175, 169] -df['Height'] = heights -df -``` - -```sh - Name Country City Weight Height -0 张三 中国 上海 74 173 -1 李四 中国 北京 78 175 -2 王五 中国 广州 69 169 -``` - -### 修改列值 - -我们可以通过三种方式修改列: - -1. 直接在列名中写入新数据: - -```python -df['Name'] = ['赵六', '钱七', '孙八'] -df -``` - -```sh - Name Country City Weight Height -0 赵六 中国 上海 74 173 -1 钱七 中国 北京 78 175 -2 孙八 中国 广州 69 169 -``` - -2. 通过索引进行修改: - -```python -df.loc[1, 'Name'] = '小七' -df -``` - -```sh - Name Country City Weight Height -0 赵六 中国 上海 74 173 -1 小七 中国 北京 78 175 -2 孙八 中国 广州 69 169 -``` - -通过iloc索引: - -```python -print('原始数据:\n', df) -df.iloc[1, 0] = '阿七' -print('修改后的数据:\n', df) -``` - -```sh -原始数据: - Name Country City Weight Height -0 赵六 中国 上海 74 173 -1 小七 中国 北京 78 175 -2 孙八 中国 广州 69 169 -修改后的数据: - Name Country City Weight Height -0 赵六 中国 上海 74 173 -1 阿七 中国 北京 78 175 -2 孙八 中国 广州 69 169 -``` - -### 格式化数据框列 - -让我们使用格式进行修改。强大公式是BMI:体重(kg)/ 身高²(m)。让我们添加一个BMI列: - -```python -# 添加身高、体重和BMI列 -df['BMI'] = np.round(df['Weight'] / ((df['Height'] * 0.01) ** 2), 2) # 保留两位小数 - -print(df) -``` - -```sh - Name Country City Weight Height BMI -0 赵六 中国 上海 74 173 24.73 -1 阿七 中国 北京 78 175 25.47 -2 孙八 中国 广州 69 169 24.16 -``` - -## 检查列值的数据类型 - -我们可以使用dtypes属性检查DataFrame中列的数据类型: - -```python -print(df.dtypes) -``` - -```sh -Name object -Country object -City object -Weight int64 -Height int64 -BMI float64 -dtype: object -``` - -### 布尔索引 - -布尔索引或布尔掩码允许您使用条件选择DataFrame中的特定行: - -```python -# 创建一个数据框 -df = pd.DataFrame({ - 'name': ['张三', '李四', '王五', '赵六'], - 'country': ['中国', '美国', '英国', '西班牙'], - 'age': [25, 15, 22, 28], - '在职': [True, False, True, False] -}) - -print(df) -``` - -```sh - name country age 在职 -0 张三 中国 25 True -1 李四 美国 15 False -2 王五 英国 22 True -3 赵六 西班牙 28 False -``` - -让我们筛选出年龄大于20岁且在职的人员: - -```python -print(df[(df['age'] > 20) & (df['在职'] == True)]) -``` - -```sh - name country age 在职 -0 张三 中国 25 True -2 王五 英国 22 True -``` - -## 练习:第25天 - -1. 阅读[hacker_news.csv](../data/hacker_news.csv)文件并获取前五行 -2. 获取标题列 -3. 获取行数、列数 -4. 获取前十行和最后十行 -5. 获取第二行和第四行从第二列到第四列的数据 -6. 获取主题为Python的行 -7. 获取Python主题行的数量 -8. 获取投票数超过200的所有行 -9. 按投票数排序数据框 -10. 按投票数进行降序排序 -11. 过滤掉Python主题并按票数排序 - -🎉 恭喜!🎉 - -[<< 第24天](./24_Day_Statistics/24_statistics_cn.md) | [第26天 >>](./26_Day_Python_web/26_python_web_cn.md) \ No newline at end of file +# 30天Python编程挑战:第25天 - Pandas + +- [第25天](#-第25天) + - [Pandas](#pandas) + - [安装Pandas](#安装pandas) + - [导入Pandas](#导入pandas) + - [使用默认索引创建Pandas系列](#使用默认索引创建pandas系列) + - [使用自定义索引创建Pandas系列](#使用自定义索引创建pandas系列) + - [从字典创建Pandas系列](#从字典创建pandas系列) + - [创建常量Pandas系列](#创建常量pandas系列) + - [使用Linspace创建Pandas系列](#使用linspace创建pandas系列) + - [数据框(DataFrames)](#数据框dataframes) + - [从列表的列表创建数据框](#从列表的列表创建数据框) + - [使用字典创建数据框](#使用字典创建数据框) + - [从字典列表创建数据框](#从字典列表创建数据框) + - [使用Pandas读取CSV文件](#使用pandas读取csv文件) + - [数据探索](#数据探索) + - [修改数据框](#修改数据框) + - [创建数据框](#创建数据框) + - [添加新列](#添加新列) + - [修改列值](#修改列值) + - [格式化数据框列](#格式化数据框列) + - [检查列值的数据类型](#检查列值的数据类型) + - [布尔索引](#布尔索引) + - [练习:第25天](#练习第25天) + +# 📘 第25天 + +## Pandas + +Pandas是一个开源的、高性能的、易于使用的Python编程语言数据结构和数据分析工具。 +Pandas添加了设计用于处理表格数据的数据结构和工具,这些数据结构是*系列(Series)*和*数据框(Data Frames)*。 +Pandas提供了用于数据操作的工具: + +- 重塑 +- 合并 +- 排序 +- 切片 +- 聚合 +- 插补 +如果你使用的是anaconda,则不必安装pandas。 + +### 安装Pandas + +对于Mac: +```py +pip install conda +conda install pandas +``` + +对于Windows: +```py +pip install conda +pip install pandas +``` + +Pandas数据结构基于*系列(Series)*和*数据框(DataFrames)*。 + +*系列*是一个*列*,而数据框是由*系列*集合组成的*多维表*。为了创建pandas系列,我们应该使用numpy创建一维数组或Python列表。 +让我们看一个系列的例子: + +名称Pandas系列 + +![pandas series](../images/pandas-series-1.png) + +国家系列 + +![pandas series](../images/pandas-series-2.png) + +城市系列 + +![pandas series](../images/pandas-series-3.png) + +如你所见,pandas系列只是一列数据。如果我们想要有多列,我们使用数据框。下面的例子显示了pandas数据框。 + +让我们看一个pandas数据框的例子: + +![Pandas data frame](../images/pandas-dataframe-1.png) + +数据框是行和列的集合。看看下面的表格;它比上面的例子有更多的列: + +![Pandas data frame](../images/pandas-dataframe-2.png) + +接下来,我们将看到如何导入pandas以及如何使用pandas创建系列和数据框 + +### 导入Pandas + +```python +import pandas as pd # 将pandas导入为pd +import numpy as np # 将numpy导入为np +``` + +### 使用默认索引创建Pandas系列 + +```python +nums = [1, 2, 3, 4,5] +s = pd.Series(nums) +print(s) +``` + +```sh +0 1 +1 2 +2 3 +3 4 +4 5 +dtype: int64 +``` + +### 使用自定义索引创建Pandas系列 + +```python +nums = [1, 2, 3, 4, 5] +s = pd.Series(nums, index=[1, 2, 3, 4, 5]) +print(s) +``` + +```sh +1 1 +2 2 +3 3 +4 4 +5 5 +dtype: int64 +``` + +```python +fruits = ['Orange','Banana','Mango'] +fruits = pd.Series(fruits, index=[1, 2, 3]) +print(fruits) +``` + +```sh +1 Orange +2 Banana +3 Mango +dtype: object +``` + +### 从字典创建Pandas系列 + +```python +dct = {'name':'Asabeneh','country':'Finland','city':'Helsinki'} +``` + +```python +s = pd.Series(dct) +print(s) +``` + +```sh +name Asabeneh +country Finland +city Helsinki +dtype: object +``` + +### 创建常量Pandas系列 + +```python +s = pd.Series(10, index = [1, 2, 3]) +print(s) +``` + +```sh +1 10 +2 10 +3 10 +dtype: int64 +``` + +### 使用Linspace创建Pandas系列 + +```python +s = pd.Series(np.linspace(5, 20, 10)) # linspace(起始点, 终点, 项目数) +print(s) +``` + +```sh +0 5.000000 +1 6.666667 +2 8.333333 +3 10.000000 +4 11.666667 +5 13.333333 +6 15.000000 +7 16.666667 +8 18.333333 +9 20.000000 +dtype: float64 +``` + +## 数据框(DataFrames) + +Pandas数据框可以以不同的方式创建: + +- 从列表的列表创建 +- 从字典创建 +- 从字典的列表创建 +- 从CSV文件创建 + +### 从列表的列表创建数据框 + +```python +data = [ + ['Asabeneh', 'Finland', 'Helsinki'], + ['David', 'UK', 'London'], + ['John', 'Sweden', 'Stockholm'] +] +df = pd.DataFrame(data, columns=['Name', 'Country', 'City']) +print(df) +``` + +```sh + Name Country City +0 Asabeneh Finland Helsinki +1 David UK London +2 John Sweden Stockholm +``` + +### 使用字典创建数据框 + +```python +data = {'Name': ['Asabeneh', 'David', 'John'], 'Country':[ + 'Finland', 'UK', 'Sweden'], 'City': ['Helsinki', 'London', 'Stockholm']} +df = pd.DataFrame(data) +print(df) +``` + +```sh + Name Country City +0 Asabeneh Finland Helsinki +1 David UK London +2 John Sweden Stockholm +``` + +### 从字典列表创建数据框 + +```python +data = [ + {'Name': 'Asabeneh', 'Country': 'Finland', 'City': 'Helsinki'}, + {'Name': 'David', 'Country': 'UK', 'City': 'London'}, + {'Name': 'John', 'Country': 'Sweden', 'City': 'Stockholm'}] +df = pd.DataFrame(data) +print(df) +``` + +```sh + Name Country City +0 Asabeneh Finland Helsinki +1 David UK London +2 John Sweden Stockholm +``` + +## 使用Pandas读取CSV文件 + +让我们在数据目录中读取文件,将通过将文件路径作为参数传递给pd.read_csv()函数来读取weight-height.csv文件。让我们使用head()方法查看前五行。 + +```python +import pandas as pd + +df = pd.read_csv('./data/weight-height.csv') +print(df.head()) # 默认为前五行 +``` + +```sh + Gender Height Weight +0 Male 73.847017 241.893563 +1 Male 68.781904 162.310473 +2 Male 74.110105 212.740856 +3 Male 71.730978 220.042470 +4 Male 69.881796 206.349801 +``` + +让我们使用tail()方法查看最后五行: + +```python +print(df.tail()) # 最后五行 +``` + +```sh + Gender Height Weight +9995 Female 66.172652 136.777454 +9996 Female 67.067155 170.867906 +9997 Female 63.867992 128.475319 +9998 Female 69.034243 163.852461 +9999 Female 61.944246 113.649103 +``` + +### 数据探索 + +让我们使用shape属性获取行和列的数量: +```python +print(df.shape) # 行和列的数量 +``` + +```sh +(10000, 3) +``` + +如你所见,该数据集有10000行和3列。让我们获取有关数据的更多信息: + +```python +print(df.columns) # 列名 +print(df.head(10)) # 前10行 +print(df.tail(10)) # 最后10行 +print(df['Gender'].value_counts()) # 计算每个值有多少个 +print(df.describe()) # 数据统计概要 +``` + +```sh +Index(['Gender', 'Height', 'Weight'], dtype='object') + Gender Height Weight +0 Male 73.847017 241.893563 +1 Male 68.781904 162.310473 +2 Male 74.110105 212.740856 +3 Male 71.730978 220.042470 +4 Male 69.881796 206.349801 +5 Male 68.767792 152.212156 +6 Male 67.961960 183.927889 +7 Male 68.563817 175.929316 +8 Male 71.267570 196.028855 +9 Male 72.040119 205.801386 + Gender Height Weight +9990 Female 64.744846 139.725595 +9991 Female 62.109532 132.451630 +9992 Female 62.593008 130.727432 +9993 Female 62.100222 131.220717 +9994 Female 63.421888 133.330246 +9995 Female 66.172652 136.777454 +9996 Female 67.067155 170.867906 +9997 Female 63.867992 128.475319 +9998 Female 69.034243 163.852461 +9999 Female 61.944246 113.649103 +Gender +Male 5000 +Female 5000 +Name: count, dtype: int64 + Height Weight +count 10000.000000 10000.000000 +mean 66.367560 161.440357 +std 3.847528 32.108439 +min 54.263133 64.700127 +25% 63.505620 135.818051 +50% 66.318070 161.212928 +75% 69.174262 187.169525 +max 78.998742 269.989699 +``` + +## 修改数据框 + +### 创建数据框 + +首先,让我们使用前面学到的内容创建一个数据框: + +```python +# 导入pandas包 +import pandas as pd +# 导入numpy包 +import numpy as np +# 数据 +data = [ + {"Name": "张三", "Country":"中国", "City":"上海"}, + {"Name": "李四", "Country":"中国", "City":"北京"}, + {"Name": "王五", "Country":"中国", "City":"广州"}] +# 创建一个数据框 +df = pd.DataFrame(data) +print(df) +``` + +```sh + Name Country City +0 张三 中国 上海 +1 李四 中国 北京 +2 王五 中国 广州 +``` + +### 添加新列 + +让我们向DataFrame添加权重列: + +```python +weights = [74, 78, 69] +df['Weight'] = weights +df +``` + +```sh + Name Country City Weight +0 张三 中国 上海 74 +1 李四 中国 北京 78 +2 王五 中国 广州 69 +``` + +让我们添加一个高度列: + +```python +heights = [173, 175, 169] +df['Height'] = heights +df +``` + +```sh + Name Country City Weight Height +0 张三 中国 上海 74 173 +1 李四 中国 北京 78 175 +2 王五 中国 广州 69 169 +``` + +### 修改列值 + +我们可以通过三种方式修改列: + +1. 直接在列名中写入新数据: + +```python +df['Name'] = ['赵六', '钱七', '孙八'] +df +``` + +```sh + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 钱七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +``` + +2. 通过索引进行修改: + +```python +df.loc[1, 'Name'] = '小七' +df +``` + +```sh + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 小七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +``` + +通过iloc索引: + +```python +print('原始数据:\n', df) +df.iloc[1, 0] = '阿七' +print('修改后的数据:\n', df) +``` + +```sh +原始数据: + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 小七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +修改后的数据: + Name Country City Weight Height +0 赵六 中国 上海 74 173 +1 阿七 中国 北京 78 175 +2 孙八 中国 广州 69 169 +``` + +### 格式化数据框列 + +让我们使用格式进行修改。强大公式是BMI:体重(kg)/ 身高²(m)。让我们添加一个BMI列: + +```python +# 添加身高、体重和BMI列 +df['BMI'] = np.round(df['Weight'] / ((df['Height'] * 0.01) ** 2), 2) # 保留两位小数 + +print(df) +``` + +```sh + Name Country City Weight Height BMI +0 赵六 中国 上海 74 173 24.73 +1 阿七 中国 北京 78 175 25.47 +2 孙八 中国 广州 69 169 24.16 +``` + +## 检查列值的数据类型 + +我们可以使用dtypes属性检查DataFrame中列的数据类型: + +```python +print(df.dtypes) +``` + +```sh +Name object +Country object +City object +Weight int64 +Height int64 +BMI float64 +dtype: object +``` + +### 布尔索引 + +布尔索引或布尔掩码允许您使用条件选择DataFrame中的特定行: + +```python +# 创建一个数据框 +df = pd.DataFrame({ + 'name': ['张三', '李四', '王五', '赵六'], + 'country': ['中国', '美国', '英国', '西班牙'], + 'age': [25, 15, 22, 28], + '在职': [True, False, True, False] +}) + +print(df) +``` + +```sh + name country age 在职 +0 张三 中国 25 True +1 李四 美国 15 False +2 王五 英国 22 True +3 赵六 西班牙 28 False +``` + +让我们筛选出年龄大于20岁且在职的人员: + +```python +print(df[(df['age'] > 20) & (df['在职'] == True)]) +``` + +```sh + name country age 在职 +0 张三 中国 25 True +2 王五 英国 22 True +``` + +## 练习:第25天 + +1. 阅读[hacker_news.csv](../data/hacker_news.csv)文件并获取前五行 +2. 获取标题列 +3. 获取行数、列数 +4. 获取前十行和最后十行 +5. 获取第二行和第四行从第二列到第四列的数据 +6. 获取主题为Python的行 +7. 获取Python主题行的数量 +8. 获取投票数超过200的所有行 +9. 按投票数排序数据框 +10. 按投票数进行降序排序 +11. 过滤掉Python主题并按票数排序 + +🎉 恭喜!🎉 + +[<< 第 24 天](./24_statistics_cn.md) | [第 26 天 >>](./26_python_web_cn.md) \ No newline at end of file diff --git a/Chinese/26_python_web_cn.md b/Chinese/26_python_web_cn.md index 63bbdab18..3eb6a41f5 100644 --- a/Chinese/26_python_web_cn.md +++ b/Chinese/26_python_web_cn.md @@ -1,817 +1,817 @@ -# 30天Python编程挑战:第26天 - Python网络编程 - -- [第26天](#-第26天) - - [Python网络编程](#python网络编程) - - [Flask](#flask) - - [文件夹结构](#文件夹结构) - - [设置项目目录](#设置项目目录) - - [创建路由](#创建路由) - - [创建模板](#创建模板) - - [Python脚本](#python脚本) - - [导航](#导航) - - [创建布局](#创建布局) - - [提供静态文件](#提供静态文件) - - [部署](#部署) - - [创建Heroku账户](#创建heroku账户) - - [登录Heroku](#登录heroku) - - [创建requirements和Procfile](#创建requirements和procfile) - - [将项目推送到Heroku](#将项目推送到heroku) - - [练习:第26天](#练习第26天) - -# 📘 第26天 - -## Python网络编程 - -Python是一种通用编程语言,可以用于多种场合。在本节中,我们将看到如何使用Python进行网络开发。Python有许多Web框架。Django和Flask是最流行的框架。今天,我们将学习如何使用Flask进行Web开发。 - -### Flask - -Flask是用Python编写的Web开发框架。Flask使用Jinja2模板引擎。Flask也可以与其他现代前端库(如React)一起使用。 - -如果你还没有安装virtualenv包,请先安装它。虚拟环境将允许隔离项目依赖与本地机器依赖。 - -#### 文件夹结构 - -完成所有步骤后,你的项目文件结构应该如下所示: - -```sh -├── Procfile -├── app.py -├── env -│ ├── bin -├── requirements.txt -├── static -│ └── css -│ └── main.css -└── templates - ├── about.html - ├── home.html - ├── layout.html - ├── post.html - └── result.html -``` - -### 设置项目目录 - -按照以下步骤开始使用Flask。 - -步骤1:使用以下命令安装virtualenv。 - -```sh -pip install virtualenv -``` - -步骤2: - -```sh -asabeneh@Asabeneh:~/Desktop$ mkdir python_for_web -asabeneh@Asabeneh:~/Desktop$ cd python_for_web/ -asabeneh@Asabeneh:~/Desktop/python_for_web$ virtualenv venv -asabeneh@Asabeneh:~/Desktop/python_for_web$ source venv/bin/activate -(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze -(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install Flask -(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze -Click==7.0 -Flask==1.1.1 -itsdangerous==1.1.0 -Jinja2==2.10.3 -MarkupSafe==1.1.1 -Werkzeug==0.16.0 -(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ -``` - -我们创建了一个名为python_for_web的项目目录。在项目中,我们创建了一个虚拟环境*venv*,它可以是任何名称,但我喜欢称它为_venv_。然后我们激活了虚拟环境。我们使用pip freeze检查项目目录中安装的包。pip freeze的结果是空的,因为还没有安装包。 - -现在,让我们在项目目录中创建app.py文件并编写以下代码。app.py文件将是项目中的主文件。以下代码包含flask模块和os模块。 - -### 创建路由 - -主页路由。 - -```py -# 导入flask -from flask import Flask -import os # 导入操作系统模块 - -app = Flask(__name__) - -@app.route('/') # 这个装饰器创建主页路由 -def home (): - return '

欢迎

' - -@app.route('/about') -def about(): - return '

关于我们

' - - -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -要运行flask应用程序,在主flask应用程序目录中输入python app.py。 - -运行_python app.py_后,检查本地主机5000端口。 - -让我们添加额外的路由。 -创建关于路由 - -```py -# 导入flask -from flask import Flask -import os # 导入操作系统模块 - -app = Flask(__name__) - -@app.route('/') # 这个装饰器创建主页路由 -def home (): - return '

欢迎

' - -@app.route('/about') -def about(): - return '

关于我们

' - -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -现在,我们在上面的代码中添加了关于路由。如果我们想渲染HTML文件而不是字符串呢?使用*render_template*函数可以渲染HTML文件。让我们在项目目录中创建一个名为templates的文件夹,并在其中创建home.html和about.html。让我们也从flask导入*render_template*函数。 - -### 创建模板 - -在templates文件夹内创建HTML文件。 - -home.html - -```html - - - - - - 主页 - - - -

欢迎回家

- - -``` - -about.html - -```html - - - - - - 关于 - - - -

关于我们

- - -``` - -### Python脚本 - -app.py - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 - -app = Flask(__name__) - -@app.route('/') # 这个装饰器创建主页路由 -def home (): - return render_template('home.html') - -@app.route('/about') -def about(): - return render_template('about.html') - -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -正如你所看到的,为了访问不同的页面或进行导航,我们需要一个导航。让我们为每个页面添加一个链接,或者创建一个我们用于每个页面的布局。 - -### 导航 - -```html - -``` - -现在,我们可以使用上面的链接在页面之间导航。让我们创建一个额外的页面来处理表单数据。你可以给它取任何名字,我喜欢称它为post.html。 - -我们可以使用Jinja2模板引擎向HTML文件注入数据。 - -```py -# 导入flask -from flask import Flask, render_template, request, redirect, url_for -import os # 导入操作系统模块 - -app = Flask(__name__) - -@app.route('/') # 这个装饰器创建主页路由 -def home (): - techs = ['HTML', 'CSS', 'Flask', 'Python'] - name = '30天Python编程挑战' - return render_template('home.html', techs=techs, name=name, title='主页') - -@app.route('/about') -def about(): - name = '30天Python编程挑战' - return render_template('about.html', name=name, title='关于我们') - -@app.route('/post') -def post(): - name = '编程语言文章' - path = request.path - return render_template('post.html', name=name, path=path, title='文章') - -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -home.html - -```html - - - - - - {{title}} - - - - -

欢迎回到{{name}}

-
    - {% for tech in techs %} -
  • {{tech}}
  • - {% endfor %} -
- - -``` - -about.html - -```html - - - - - - {{title}} - - - - -

关于{{name}}

- - -``` - -post.html - -```html - - - - - - {{title}} - - - - -

{{name}}

-

当前路径: {{path}}

-
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
- - -``` - -现在,让我们添加一个接收表单数据的路由。我们使用POST方法,因为我们将收到表单数据。 - -```py -# 导入flask -from flask import Flask, render_template, request, redirect, url_for -import os # 导入操作系统模块 - -app = Flask(__name__) - -@app.route('/') # 这个装饰器创建主页路由 -def home(): - techs = ['HTML', 'CSS', 'Flask', 'Python'] - name = '30天Python编程挑战' - return render_template('home.html', techs=techs, name=name, title='主页') - -@app.route('/about') -def about(): - name = '30天Python编程挑战' - return render_template('about.html', name=name, title='关于我们') - -@app.route('/post') -def post(): - name = '文章' - return render_template('post.html', name=name, title='文章') - - -@app.route('/result', methods=['POST']) -def result(): - first_name = request.form['first_name'] - last_name = request.form['last_name'] - old_job = request.form['old_job'] - current_job = request.form['current_job'] - country = request.form['country'] - print(first_name, last_name, old_job, current_job, country) - result_data = { - 'first_name':first_name, - 'last_name':last_name, - 'old_job': old_job, - 'current_job': current_job, - 'country':country - } - return render_template('result.html', result_data = result_data, title= '结果') - -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -result.html - -```html - - - - - - {{title}} - - - - -

表单数据

- -
    -
  • 第一名字: {{result_data.first_name}}
  • -
  • 姓氏: {{result_data.last_name}}
  • -
  • 旧工作: {{result_data.old_job}}
  • -
  • 当前工作: {{result_data.current_job}}
  • -
  • 国家: {{result_data.country}}
  • -
- - -``` - -在现实世界中,我们不会在所有页面中重复HTML代码。而是创建一个布局并将其继承到其他文件中。让我们使用继承(模板)。现在,我们需要创建的不是三个不同的文件,而是一个名为layout.html的布局文件。然后其他文件将继承它。 - -### 创建布局 - -layout.html - -```html - - - - - - - - {% if title %} - 30天Python - {{ title}} - {% else %} - 30天Python - {% endif %} - - - -
- -
-
- {% block content %} {% endblock %} -
- - -``` - -在上面的布局中,我们创建了一个可以被所有继承布局的页面使用的公共布局。在布局内部,我们可以看到导航链接。我们使用{% block content %}{% endblock %}标记以允许子模板添加内容。 - -home.html - -```html -{% extends 'layout.html' %} {% block content %} -
-

欢迎回到{{name}}

-

- 这个项目是通过使用以下技术构建的: - Flask, Python - and HTML CSS -

-
    - {% for tech in techs %} -
  • {{tech}}
  • - - {% endfor %} -
-
- -{% endblock %} -``` - -about.html - -```html -{% extends 'layout.html' %} {% block content %} -
-

关于{{name}}

-

- 这个挑战是一个30天编程挑战,旨在帮助你学习Python编程语言,通过每天解决一个Python问题。 -

-
-{% endblock %} -``` - -post.html - -```html -{% extends 'layout.html' %} {% block content %} -
-

{{name}}

-

{{path}}

-
-
- -
-
- -
-
- -
-
- -
-
- -
-
- -
-
-
- -{% endblock %} -``` - -result.html - -```html -{% extends 'layout.html' %} {% block content %} -
-

表单数据

-
    -
  • 第一名字: {{result_data.first_name}}
  • -
  • 姓氏: {{result_data.last_name}}
  • -
  • 旧工作: {{result_data.old_job}}
  • -
  • 当前工作: {{result_data.current_job}}
  • -
  • 国家: {{result_data.country}}
  • -
-
- -{% endblock %} -``` - -#### 提供静态文件 - -以下是main.css文件,我们将把它放在static/css目录中: - -```css -/* === GENERAL === */ -body { - margin: 0; - padding: 0; - font-family: "Lato", sans-serif; - background-color: #f0f8ea; -} - -.container { - max-width: 80%; - margin: auto; - padding: 30px; -} - -ul { - list-style-type: none; - padding: 0; -} - -.tech { - color: #5bbc2e; -} - -/* === HEADER === */ -header { - background-color: #5bbc2e; -} - -.menu-container { - display: flex; - justify-content: space-between; - padding: 20px 30px; -} - -.brand-name { - color: white; - font-weight: 800; - font-size: 24px; -} - -.nav-lists { - display: flex; -} - -.nav-list { - margin-right: 15px; -} - -.nav-link { - text-decoration: none; - color: white; - font-weight: 300; -} - -/* === FORM === */ - -form { - margin: 30px 0; - border: 1px solid #ddd; - padding: 30px; - border-radius: 10px; -} - -form > div { - margin-bottom: 15px; -} - -input { - width: 100%; - padding: 10px; - border: 1px solid #ddd; - border-radius: 5px; - outline: 0; - font-size: 16px; - box-sizing: border-box; - margin-top: 5px; -} - -button { - padding: 12px 24px; - border: 0; - background-color: #5bbc2e; - color: white; - border-radius: 10px; - font-size: 16px; - outline: 0; - cursor: pointer; -} - -button:hover { - background-color: #4b9c25; -} -``` - -### 部署 - -#### 创建Heroku账户 - -Heroku提供了一个免费的托管服务。如果你想要部署一个应用程序,你应该有一个Heroku账户。 - -#### 登录Heroku - -```sh -asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku login -heroku: Press any key to open up the browser to login or q to exit: -Opening browser to https://cli-auth.heroku.com/auth/cli/browser/ec0972d5-d8c6-4adf-b004-a42a22dd09a8 -Logging in... done -Logged in as asabeneh@gmail.com -asabeneh@Asabeneh:~/Desktop/python_for_web$ -``` - -#### 创建requirements和Procfile - -在部署应用程序之前,我们需要告诉Heroku哪些依赖包需要安装,以及如何运行应用程序。Heroku使用requirements.txt文件获取应用程序依赖包的信息。使用pip freeze命令列出所有依赖包及其版本,并将其写入requirements.txt。 - -```sh -asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze -Click==7.0 -Flask==1.1.1 -itsdangerous==1.1.0 -Jinja2==2.10.3 -MarkupSafe==1.1.1 -Werkzeug==0.16.0 -asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze > requirements.txt -``` - -Procfile告诉Heroku如何运行应用程序。在本例中,我们使用Gunicorn作为WSGI HTTP服务器,用于运行Python Web应用程序。我们需要将Gunicorn添加到我们的依赖包中。 - -```sh -asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install gunicorn -asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze > requirements.txt -``` - -现在,让我们创建一个Procfile,并添加以下内容: - -```sh -web: gunicorn app:app -``` - -#### 将项目推送到Heroku - -```sh -asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku create 30-days-of-python-app -Creating ⬢ 30-days-of-python-app... done -https://30-days-of-python-app.herokuapp.com/ | https://git.heroku.com/30-days-of-python-app.git -asabeneh@Asabeneh:~/Desktop/python_for_web$ git init -Initialized empty Git repository in /home/asabeneh/Desktop/python_for_web/.git/ -asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku git:remote -a 30-days-of-python-app -set git remote heroku to https://git.heroku.com/30-days-of-python-app.git -asabeneh@Asabeneh:~/Desktop/python_for_web$ echo -e "venv\n.vscode" > .gitignore -asabeneh@Asabeneh:~/Desktop/python_for_web$ git add . -asabeneh@Asabeneh:~/Desktop/python_for_web$ git commit -m "first python web app" -[master (root-commit) 9dfcc6a] first python web app - 9 files changed, 403 insertions(+) - create mode 100644 .gitignore - create mode 100644 Procfile - create mode 100644 app.py - create mode 100644 requirements.txt - create mode 100644 static/css/main.css - create mode 100644 templates/about.html - create mode 100644 templates/home.html - create mode 100644 templates/layout.html - create mode 100644 templates/post.html - create mode 100644 templates/result.html -asabeneh@Asabeneh:~/Desktop/python_for_web$ git push heroku master -Enumerating objects: 14, done. -Counting objects: 100% (14/14), done. -Delta compression using up to 2 threads -Compressing objects: 100% (12/12), done. -Writing objects: 100% (14/14), 6.08 KiB | 1.52 MiB/s, done. -Total 14 (delta 2), reused 0 (delta 0) -remote: Compressing source files... done. -remote: Building source: -remote: -remote: -----> Python app detected -remote: -----> Installing python-3.6.10 -remote: -----> Installing pip -remote: -----> Installing dependencies with Pipenv 2018.5.18… -remote: Installing dependencies from Pipfile.lock (872ae5)… -remote: -----> Installing SQLite3 -remote: -----> $ python manage.py collectstatic --noinput -remote: Traceback (most recent call last): -remote: File "manage.py", line 10, in -remote: from app import app -remote: ModuleNotFoundError: No module named 'app' -remote: -remote: ! Error while running '$ python manage.py collectstatic --noinput'. -remote: See traceback above for details. -remote: -remote: You may need to update application code to resolve this error. -remote: Or, you can disable collectstatic for this application: -remote: -remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 -remote: -remote: https://devcenter.heroku.com/articles/django-assets -remote: -----> Discovering process types -remote: Procfile declares types -> web -remote: -remote: -----> Compressing... -remote: Done: 55.7M -remote: -----> Launching... -remote: Released v3 -remote: https://30-days-of-python-app.herokuapp.com/ deployed to Heroku -remote: -remote: Verifying deploy... done. -To https://git.heroku.com/30-days-of-python-app.git - * [new branch] master -> master -asabeneh@Asabeneh:~/Desktop/python_for_web$ -``` - -如你所见,我们已经成功地创建了第一个网络应用程序、对其进行部署,并将其托管在Heroku上。您可以使用此[链接](https://30-days-of-python-app.herokuapp.com/)尝试本应用程序。 - -事不宜迟,让我们做一些练习,巩固所学到的知识。 - -## 练习:第26天 - -1. 创建一个名为"成绩计算器"的Flask应用程序。用户可以输入他们的分数、科目名称,然后应用程序应根据分数显示不同的消息: - - 如果分数≥90,显示"优秀!你的[科目]成绩是[分数]"。 - - 如果80≤分数<90,显示"很好!你的[科目]成绩是[分数]"。 - - 如果70≤分数<80,显示"一般!你的[科目]成绩是[分数]"。 - - 如果60≤分数<70,显示"及格!你的[科目]成绩是[分数]"。 - - 如果分数<60,显示"你需要更加努力!你的[科目]成绩是[分数]"。 - -2. 创建一个"体重指数计算器"应用程序,计算体重指数(BMI),公式为体重(kg)/(身高(m)²)。根据BMI值显示不同的健康状态: - - BMI<18.5:"体重过轻" - - 18.5≤BMI<24.9:"健康体重" - - 25≤BMI<29.9:"超重" - - BMI≥30:"肥胖" - -3. 创建一个博客应用程序,用户可以添加、编辑和删除博客文章。 - -4. 创建一个"任务管理器"应用程序,用户可以添加、查看和删除任务。 - -🎉 恭喜!🎉 - -[<< 第25天](./25_Day_Pandas/25_pandas_cn.md) | [第27天 >>](./27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) \ No newline at end of file +# 30天Python编程挑战:第26天 - Python网络编程 + +- [第26天](#-第26天) + - [Python网络编程](#python网络编程) + - [Flask](#flask) + - [文件夹结构](#文件夹结构) + - [设置项目目录](#设置项目目录) + - [创建路由](#创建路由) + - [创建模板](#创建模板) + - [Python脚本](#python脚本) + - [导航](#导航) + - [创建布局](#创建布局) + - [提供静态文件](#提供静态文件) + - [部署](#部署) + - [创建Heroku账户](#创建heroku账户) + - [登录Heroku](#登录heroku) + - [创建requirements和Procfile](#创建requirements和procfile) + - [将项目推送到Heroku](#将项目推送到heroku) + - [练习:第26天](#练习第26天) + +# 📘 第26天 + +## Python网络编程 + +Python是一种通用编程语言,可以用于多种场合。在本节中,我们将看到如何使用Python进行网络开发。Python有许多Web框架。Django和Flask是最流行的框架。今天,我们将学习如何使用Flask进行Web开发。 + +### Flask + +Flask是用Python编写的Web开发框架。Flask使用Jinja2模板引擎。Flask也可以与其他现代前端库(如React)一起使用。 + +如果你还没有安装virtualenv包,请先安装它。虚拟环境将允许隔离项目依赖与本地机器依赖。 + +#### 文件夹结构 + +完成所有步骤后,你的项目文件结构应该如下所示: + +```sh +├── Procfile +├── app.py +├── env +│ ├── bin +├── requirements.txt +├── static +│ └── css +│ └── main.css +└── templates + ├── about.html + ├── home.html + ├── layout.html + ├── post.html + └── result.html +``` + +### 设置项目目录 + +按照以下步骤开始使用Flask。 + +步骤1:使用以下命令安装virtualenv。 + +```sh +pip install virtualenv +``` + +步骤2: + +```sh +asabeneh@Asabeneh:~/Desktop$ mkdir python_for_web +asabeneh@Asabeneh:~/Desktop$ cd python_for_web/ +asabeneh@Asabeneh:~/Desktop/python_for_web$ virtualenv venv +asabeneh@Asabeneh:~/Desktop/python_for_web$ source venv/bin/activate +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install Flask +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze +Click==7.0 +Flask==1.1.1 +itsdangerous==1.1.0 +Jinja2==2.10.3 +MarkupSafe==1.1.1 +Werkzeug==0.16.0 +(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ +``` + +我们创建了一个名为python_for_web的项目目录。在项目中,我们创建了一个虚拟环境*venv*,它可以是任何名称,但我喜欢称它为_venv_。然后我们激活了虚拟环境。我们使用pip freeze检查项目目录中安装的包。pip freeze的结果是空的,因为还没有安装包。 + +现在,让我们在项目目录中创建app.py文件并编写以下代码。app.py文件将是项目中的主文件。以下代码包含flask模块和os模块。 + +### 创建路由 + +主页路由。 + +```py +# 导入flask +from flask import Flask +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + return '

欢迎

' + +@app.route('/about') +def about(): + return '

关于我们

' + + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +要运行flask应用程序,在主flask应用程序目录中输入python app.py。 + +运行_python app.py_后,检查本地主机5000端口。 + +让我们添加额外的路由。 +创建关于路由 + +```py +# 导入flask +from flask import Flask +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + return '

欢迎

' + +@app.route('/about') +def about(): + return '

关于我们

' + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +现在,我们在上面的代码中添加了关于路由。如果我们想渲染HTML文件而不是字符串呢?使用*render_template*函数可以渲染HTML文件。让我们在项目目录中创建一个名为templates的文件夹,并在其中创建home.html和about.html。让我们也从flask导入*render_template*函数。 + +### 创建模板 + +在templates文件夹内创建HTML文件。 + +home.html + +```html + + + + + + 主页 + + + +

欢迎回家

+ + +``` + +about.html + +```html + + + + + + 关于 + + + +

关于我们

+ + +``` + +### Python脚本 + +app.py + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + return render_template('home.html') + +@app.route('/about') +def about(): + return render_template('about.html') + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +正如你所看到的,为了访问不同的页面或进行导航,我们需要一个导航。让我们为每个页面添加一个链接,或者创建一个我们用于每个页面的布局。 + +### 导航 + +```html + +``` + +现在,我们可以使用上面的链接在页面之间导航。让我们创建一个额外的页面来处理表单数据。你可以给它取任何名字,我喜欢称它为post.html。 + +我们可以使用Jinja2模板引擎向HTML文件注入数据。 + +```py +# 导入flask +from flask import Flask, render_template, request, redirect, url_for +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home (): + techs = ['HTML', 'CSS', 'Flask', 'Python'] + name = '30天Python编程挑战' + return render_template('home.html', techs=techs, name=name, title='主页') + +@app.route('/about') +def about(): + name = '30天Python编程挑战' + return render_template('about.html', name=name, title='关于我们') + +@app.route('/post') +def post(): + name = '编程语言文章' + path = request.path + return render_template('post.html', name=name, path=path, title='文章') + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +home.html + +```html + + + + + + {{title}} + + + + +

欢迎回到{{name}}

+
    + {% for tech in techs %} +
  • {{tech}}
  • + {% endfor %} +
+ + +``` + +about.html + +```html + + + + + + {{title}} + + + + +

关于{{name}}

+ + +``` + +post.html + +```html + + + + + + {{title}} + + + + +

{{name}}

+

当前路径: {{path}}

+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + +``` + +现在,让我们添加一个接收表单数据的路由。我们使用POST方法,因为我们将收到表单数据。 + +```py +# 导入flask +from flask import Flask, render_template, request, redirect, url_for +import os # 导入操作系统模块 + +app = Flask(__name__) + +@app.route('/') # 这个装饰器创建主页路由 +def home(): + techs = ['HTML', 'CSS', 'Flask', 'Python'] + name = '30天Python编程挑战' + return render_template('home.html', techs=techs, name=name, title='主页') + +@app.route('/about') +def about(): + name = '30天Python编程挑战' + return render_template('about.html', name=name, title='关于我们') + +@app.route('/post') +def post(): + name = '文章' + return render_template('post.html', name=name, title='文章') + + +@app.route('/result', methods=['POST']) +def result(): + first_name = request.form['first_name'] + last_name = request.form['last_name'] + old_job = request.form['old_job'] + current_job = request.form['current_job'] + country = request.form['country'] + print(first_name, last_name, old_job, current_job, country) + result_data = { + 'first_name':first_name, + 'last_name':last_name, + 'old_job': old_job, + 'current_job': current_job, + 'country':country + } + return render_template('result.html', result_data = result_data, title= '结果') + +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +result.html + +```html + + + + + + {{title}} + + + + +

表单数据

+ +
    +
  • 第一名字: {{result_data.first_name}}
  • +
  • 姓氏: {{result_data.last_name}}
  • +
  • 旧工作: {{result_data.old_job}}
  • +
  • 当前工作: {{result_data.current_job}}
  • +
  • 国家: {{result_data.country}}
  • +
+ + +``` + +在现实世界中,我们不会在所有页面中重复HTML代码。而是创建一个布局并将其继承到其他文件中。让我们使用继承(模板)。现在,我们需要创建的不是三个不同的文件,而是一个名为layout.html的布局文件。然后其他文件将继承它。 + +### 创建布局 + +layout.html + +```html + + + + + + + + {% if title %} + 30天Python - {{ title}} + {% else %} + 30天Python + {% endif %} + + + +
+ +
+
+ {% block content %} {% endblock %} +
+ + +``` + +在上面的布局中,我们创建了一个可以被所有继承布局的页面使用的公共布局。在布局内部,我们可以看到导航链接。我们使用{% block content %}{% endblock %}标记以允许子模板添加内容。 + +home.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

欢迎回到{{name}}

+

+ 这个项目是通过使用以下技术构建的: + Flask, Python + and HTML CSS +

+
    + {% for tech in techs %} +
  • {{tech}}
  • + + {% endfor %} +
+
+ +{% endblock %} +``` + +about.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

关于{{name}}

+

+ 这个挑战是一个30天编程挑战,旨在帮助你学习Python编程语言,通过每天解决一个Python问题。 +

+
+{% endblock %} +``` + +post.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

{{name}}

+

{{path}}

+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +{% endblock %} +``` + +result.html + +```html +{% extends 'layout.html' %} {% block content %} +
+

表单数据

+
    +
  • 第一名字: {{result_data.first_name}}
  • +
  • 姓氏: {{result_data.last_name}}
  • +
  • 旧工作: {{result_data.old_job}}
  • +
  • 当前工作: {{result_data.current_job}}
  • +
  • 国家: {{result_data.country}}
  • +
+
+ +{% endblock %} +``` + +#### 提供静态文件 + +以下是main.css文件,我们将把它放在static/css目录中: + +```css +/* === GENERAL === */ +body { + margin: 0; + padding: 0; + font-family: "Lato", sans-serif; + background-color: #f0f8ea; +} + +.container { + max-width: 80%; + margin: auto; + padding: 30px; +} + +ul { + list-style-type: none; + padding: 0; +} + +.tech { + color: #5bbc2e; +} + +/* === HEADER === */ +header { + background-color: #5bbc2e; +} + +.menu-container { + display: flex; + justify-content: space-between; + padding: 20px 30px; +} + +.brand-name { + color: white; + font-weight: 800; + font-size: 24px; +} + +.nav-lists { + display: flex; +} + +.nav-list { + margin-right: 15px; +} + +.nav-link { + text-decoration: none; + color: white; + font-weight: 300; +} + +/* === FORM === */ + +form { + margin: 30px 0; + border: 1px solid #ddd; + padding: 30px; + border-radius: 10px; +} + +form > div { + margin-bottom: 15px; +} + +input { + width: 100%; + padding: 10px; + border: 1px solid #ddd; + border-radius: 5px; + outline: 0; + font-size: 16px; + box-sizing: border-box; + margin-top: 5px; +} + +button { + padding: 12px 24px; + border: 0; + background-color: #5bbc2e; + color: white; + border-radius: 10px; + font-size: 16px; + outline: 0; + cursor: pointer; +} + +button:hover { + background-color: #4b9c25; +} +``` + +### 部署 + +#### 创建Heroku账户 + +Heroku提供了一个免费的托管服务。如果你想要部署一个应用程序,你应该有一个Heroku账户。 + +#### 登录Heroku + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku login +heroku: Press any key to open up the browser to login or q to exit: +Opening browser to https://cli-auth.heroku.com/auth/cli/browser/ec0972d5-d8c6-4adf-b004-a42a22dd09a8 +Logging in... done +Logged in as asabeneh@gmail.com +asabeneh@Asabeneh:~/Desktop/python_for_web$ +``` + +#### 创建requirements和Procfile + +在部署应用程序之前,我们需要告诉Heroku哪些依赖包需要安装,以及如何运行应用程序。Heroku使用requirements.txt文件获取应用程序依赖包的信息。使用pip freeze命令列出所有依赖包及其版本,并将其写入requirements.txt。 + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze +Click==7.0 +Flask==1.1.1 +itsdangerous==1.1.0 +Jinja2==2.10.3 +MarkupSafe==1.1.1 +Werkzeug==0.16.0 +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze > requirements.txt +``` + +Procfile告诉Heroku如何运行应用程序。在本例中,我们使用Gunicorn作为WSGI HTTP服务器,用于运行Python Web应用程序。我们需要将Gunicorn添加到我们的依赖包中。 + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install gunicorn +asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze > requirements.txt +``` + +现在,让我们创建一个Procfile,并添加以下内容: + +```sh +web: gunicorn app:app +``` + +#### 将项目推送到Heroku + +```sh +asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku create 30-days-of-python-app +Creating ⬢ 30-days-of-python-app... done +https://30-days-of-python-app.herokuapp.com/ | https://git.heroku.com/30-days-of-python-app.git +asabeneh@Asabeneh:~/Desktop/python_for_web$ git init +Initialized empty Git repository in /home/asabeneh/Desktop/python_for_web/.git/ +asabeneh@Asabeneh:~/Desktop/python_for_web$ heroku git:remote -a 30-days-of-python-app +set git remote heroku to https://git.heroku.com/30-days-of-python-app.git +asabeneh@Asabeneh:~/Desktop/python_for_web$ echo -e "venv\n.vscode" > .gitignore +asabeneh@Asabeneh:~/Desktop/python_for_web$ git add . +asabeneh@Asabeneh:~/Desktop/python_for_web$ git commit -m "first python web app" +[master (root-commit) 9dfcc6a] first python web app + 9 files changed, 403 insertions(+) + create mode 100644 .gitignore + create mode 100644 Procfile + create mode 100644 app.py + create mode 100644 requirements.txt + create mode 100644 static/css/main.css + create mode 100644 templates/about.html + create mode 100644 templates/home.html + create mode 100644 templates/layout.html + create mode 100644 templates/post.html + create mode 100644 templates/result.html +asabeneh@Asabeneh:~/Desktop/python_for_web$ git push heroku master +Enumerating objects: 14, done. +Counting objects: 100% (14/14), done. +Delta compression using up to 2 threads +Compressing objects: 100% (12/12), done. +Writing objects: 100% (14/14), 6.08 KiB | 1.52 MiB/s, done. +Total 14 (delta 2), reused 0 (delta 0) +remote: Compressing source files... done. +remote: Building source: +remote: +remote: -----> Python app detected +remote: -----> Installing python-3.6.10 +remote: -----> Installing pip +remote: -----> Installing dependencies with Pipenv 2018.5.18… +remote: Installing dependencies from Pipfile.lock (872ae5)… +remote: -----> Installing SQLite3 +remote: -----> $ python manage.py collectstatic --noinput +remote: Traceback (most recent call last): +remote: File "manage.py", line 10, in +remote: from app import app +remote: ModuleNotFoundError: No module named 'app' +remote: +remote: ! Error while running '$ python manage.py collectstatic --noinput'. +remote: See traceback above for details. +remote: +remote: You may need to update application code to resolve this error. +remote: Or, you can disable collectstatic for this application: +remote: +remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 +remote: +remote: https://devcenter.heroku.com/articles/django-assets +remote: -----> Discovering process types +remote: Procfile declares types -> web +remote: +remote: -----> Compressing... +remote: Done: 55.7M +remote: -----> Launching... +remote: Released v3 +remote: https://30-days-of-python-app.herokuapp.com/ deployed to Heroku +remote: +remote: Verifying deploy... done. +To https://git.heroku.com/30-days-of-python-app.git + * [new branch] master -> master +asabeneh@Asabeneh:~/Desktop/python_for_web$ +``` + +如你所见,我们已经成功地创建了第一个网络应用程序、对其进行部署,并将其托管在Heroku上。您可以使用此[链接](https://30-days-of-python-app.herokuapp.com/)尝试本应用程序。 + +事不宜迟,让我们做一些练习,巩固所学到的知识。 + +## 练习:第26天 + +1. 创建一个名为"成绩计算器"的Flask应用程序。用户可以输入他们的分数、科目名称,然后应用程序应根据分数显示不同的消息: + - 如果分数≥90,显示"优秀!你的[科目]成绩是[分数]"。 + - 如果80≤分数<90,显示"很好!你的[科目]成绩是[分数]"。 + - 如果70≤分数<80,显示"一般!你的[科目]成绩是[分数]"。 + - 如果60≤分数<70,显示"及格!你的[科目]成绩是[分数]"。 + - 如果分数<60,显示"你需要更加努力!你的[科目]成绩是[分数]"。 + +2. 创建一个"体重指数计算器"应用程序,计算体重指数(BMI),公式为体重(kg)/(身高(m)²)。根据BMI值显示不同的健康状态: + - BMI<18.5:"体重过轻" + - 18.5≤BMI<24.9:"健康体重" + - 25≤BMI<29.9:"超重" + - BMI≥30:"肥胖" + +3. 创建一个博客应用程序,用户可以添加、编辑和删除博客文章。 + +4. 创建一个"任务管理器"应用程序,用户可以添加、查看和删除任务。 + +🎉 恭喜!🎉 + +[<< 第 25 天](./25_pandas_cn.md) | [第 27 天 >>](./27_python_with_mongodb_cn.md) \ No newline at end of file diff --git a/Chinese/27_python_with_mongodb_cn.md b/Chinese/27_python_with_mongodb_cn.md index c6bb1eeec..f9a6279e1 100644 --- a/Chinese/27_python_with_mongodb_cn.md +++ b/Chinese/27_python_with_mongodb_cn.md @@ -1,632 +1,632 @@ -# 30天Python编程挑战:第27天 - Python与MongoDB - -- [第27天](#-第27天) -- [Python与MongoDB](#python与mongodb) - - [MongoDB](#mongodb) - - [SQL与NoSQL的比较](#sql与nosql的比较) - - [获取连接字符串(MongoDB URI)](#获取连接字符串mongodb-uri) - - [将Flask应用程序连接到MongoDB集群](#将flask应用程序连接到mongodb集群) - - [创建数据库和集合](#创建数据库和集合) - - [向集合中插入多个文档](#向集合中插入多个文档) - - [MongoDB查找](#mongodb查找) - - [使用查询进行查找](#使用查询进行查找) - - [使用修饰符的查询查找](#使用修饰符的查询查找) - - [限制文档数量](#限制文档数量) - - [使用排序进行查找](#使用排序进行查找) - - [使用查询进行更新](#使用查询进行更新) - - [删除文档](#删除文档) - - [删除集合](#删除集合) - - [💻 练习:第27天](#-练习第27天) - -# 📘 第27天 - -# Python与MongoDB - -Python是一种后端技术,可以与不同的数据库应用程序连接。它可以连接到SQL和NoSQL数据库。在本节中,我们将Python与MongoDB数据库连接,MongoDB是一种NoSQL数据库。 - -## MongoDB - -MongoDB是一种NoSQL数据库。MongoDB以类似JSON的文档形式存储数据,这使得MongoDB非常灵活和可扩展。让我们看看SQL和NoSQL数据库的不同术语。下表将展示SQL与NoSQL数据库之间的区别。 - -### SQL与NoSQL的比较 - -![SQL与NoSQL](../images/mongoDB/sql-vs-nosql.png) - -在本节中,我们将重点关注NoSQL数据库MongoDB。通过点击注册按钮,然后在下一页点击注册,让我们在[mongoDB](https://www.mongodb.com/)上注册。 - -![MongoDB注册页面](../images/mongoDB/mongodb-signup-page.png) - -完成表格并点击继续 - -![MongoDB注册](../images/mongoDB/mongodb-register.png) - -选择免费计划 - -![MongoDB免费计划](../images/mongoDB/mongodb-free.png) - -选择最近的免费区域,并为你的集群命名。 - -![MongoDB集群名称](../images/mongoDB/mongodb-cluster-name.png) - -现在,一个免费的沙箱已创建 - -![MongoDB沙箱](../images/mongoDB/mongodb-sandbox.png) - -允许所有本地主机访问 - -![MongoDB允许IP访问](../images/mongoDB/mongodb-allow-ip-access.png) - -添加用户和密码 - -![MongoDB添加用户](../images/mongoDB/mongodb-add-user.png) - -创建MongoDB URI链接 - -![MongoDB创建URI](../images/mongoDB/mongodb-create-uri.png) - -选择Python 3.6或更高版本的驱动程序 - -![MongoDB Python驱动程序](../images/mongoDB/mongodb-python-driver.png) - -### 获取连接字符串(MongoDB URI) - -复制连接字符串链接,你将获得类似这样的内容: - -```sh -mongodb+srv://asabeneh:@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority -``` - -不要担心这个URL,它是连接你的应用程序与mongoDB的一种方式。 -让我们用你添加用户时使用的密码替换密码占位符。 - -**示例:** - -```sh -mongodb+srv://asabeneh:123123123@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority -``` - -现在,我已经替换了所有内容,密码是123123123,数据库名称是*thirty_days_python*。这只是一个示例,你的密码必须比示例密码更强。 - -Python需要mongoDB驱动程序才能访问mongoDB数据库。我们将使用_pymongo_和_dnspython_来连接我们的应用程序与mongoDB基础。在你的项目目录中安装pymongo和dnspython。 - -```sh -pip install pymongo dnspython -``` - -要使用mongodb+srv://URI,必须安装"dnspython"模块。dnspython是用于Python的DNS工具包。它支持几乎所有记录类型。 - -### 将Flask应用程序连接到MongoDB集群 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -print(client.list_database_names()) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -当我们运行上面的代码时,我们会得到默认的mongoDB数据库。 - -```sh -['admin', 'local'] -``` - -### 创建数据库和集合 - -让我们创建一个数据库,如果数据库和集合在mongoDB中不存在,它们将被创建。让我们创建一个名为*thirty_days_of_python*的数据库和*students*集合。 - -创建数据库的方法: - -```sh -db = client.name_of_databse # 我们可以这样创建数据库,或者使用第二种方式 -db = client['name_of_database'] -``` - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -# 创建数据库 -db = client.thirty_days_of_python -# 创建students集合并插入文档 -db.students.insert_one({'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}) -print(client.list_database_names()) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -在创建数据库后,我们还创建了一个students集合,并使用*insert_one()*方法插入了一个文档。 -现在,数据库*thirty_days_of_python*和*students*集合已经创建,并且文档已经插入。 -检查你的mongoDB集群,你将看到数据库和集合。在集合内部,将有一个文档。 - -```sh -['thirty_days_of_python', 'admin', 'local'] -``` - -如果你在mongoDB集群上看到这个,这意味着你已经成功创建了一个数据库和一个集合。 - -![创建数据库和集合](../images/mongoDB/mongodb-creating_database.png) - -如果你看到上图,文档已经创建,并带有一个长ID作为主键。每次我们创建一个文档,mongoDB都会为它创建一个唯一的ID。 - -### 向集合中插入多个文档 - -*insert_one()*方法一次插入一个项目,如果我们想一次插入多个文档,我们可以使用*insert_many()*方法或for循环。 -我们可以使用for循环一次插入多个文档。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) - -students = [ - {'name':'David','country':'UK','city':'London','age':34}, - {'name':'John','country':'Sweden','city':'Stockholm','age':28}, - {'name':'Sami','country':'Finland','city':'Helsinki','age':25}, - ] -for student in students: - db.students.insert_one(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -### MongoDB查找 - -*find()*和*findOne()*方法是在mongoDB数据库集合中查找数据的常用方法。它类似于MySQL数据库中的SELECT语句。 -让我们使用_find_one()_方法来获取数据库集合中的一个文档。 - -- \*find_one({"\_id": ObjectId("id"}): 如果没有提供id,则获取第一次出现的文档 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -student = db.students.find_one() -print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Helsinki', 'city': 'Helsinki', 'age': 250} -``` - -上面的查询返回第一个条目,但我们可以使用特定的\_id来定位特定的文档。让我们做一个例子,使用David的id来获取David对象。 -'\_id':ObjectId('5df68a23f106fe2d315bbc8c') - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -from bson.objectid import ObjectId # id对象 -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -student = db.students.find_one({'_id':ObjectId('5df68a23f106fe2d315bbc8c')}) -print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} -``` - -我们已经看到如何使用上面的例子来使用_find_one()_。让我们进一步了解_find()_ - -- _find()_: 如果我们不传递查询对象,返回集合中的所有出现。该对象是pymongo.cursor对象。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -students = db.students.find() -for student in students: - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} -{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -我们可以通过在_find({}, {})_中传递第二个对象来指定要返回的字段。0表示不包含,1表示包含,但我们不能混合使用0和1,除了\_id。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -students = db.students.find({}, {"_id":0, "name": 1, "country":1}) # 0表示不包含,1表示包含 -for student in students: - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'name': 'Asabeneh', 'country': 'Finland'} -{'name': 'David', 'country': 'UK'} -{'name': 'John', 'country': 'Sweden'} -{'name': 'Sami', 'country': 'Finland'} -``` - -### 使用查询进行查找 - -在mongoDB中,find接受一个查询对象。我们可以传递一个查询对象,我们可以过滤我们想要过滤的文档。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -query = { - "country":"Finland" -} -students = db.students.find(query) - -for student in students: - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -带有修饰符的查询 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -query = { - "city":"Helsinki" -} -students = db.students.find(query) -for student in students: - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -### 使用修饰符的查询查找 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -query = { - "country":"Finland", - "city":"Helsinki" -} -students = db.students.find(query) -for student in students: - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -带有修饰符的查询 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -query = {"age":{"$gt":30}} -students = db.students.find(query) -for student in students: - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} -``` - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -query = {"age":{"$lt":30}} -students = db.students.find(query) -for student in students: - print(student) -``` - -```sh -{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -### 限制文档数量 - -我们可以使用_limit()_方法来限制我们返回的文档数量。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -db.students.find().limit(3) -``` - -### 使用排序进行查找 - -默认情况下,排序是升序的。我们可以通过添加-1参数将排序更改为降序。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -students = db.students.find().sort('name') -for student in students: - print(student) - -students = db.students.find().sort('name',-1) -for student in students: - print(student) - -students = db.students.find().sort('age') -for student in students: - print(student) - -students = db.students.find().sort('age',-1) -for student in students: - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -升序 - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} -{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -降序 - -```sh -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} -{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} -``` - -### 使用查询进行更新 - -我们将使用*update_one()*方法来更新一个项目。它接受两个对象,一个是查询,另一个是新对象。 -第一个人,Asabeneh得到了一个非常不合理的年龄。让我们更新Asabeneh的年龄。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -query = {'age':250} -new_value = {'$set':{'age':38}} - -db.students.update_one(query, new_value) -# 让我们检查结果,看看年龄是否被修改 -for student in db.students.find(): - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38} -{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} -{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -当我们想要一次更新多个文档时,我们使用*upate_many()*方法。 - -### 删除文档 - -方法*delete_one()*删除一个文档。*delete_one()*方法接受一个查询对象参数。它只删除第一次出现的文档。 -让我们从集合中删除一个John。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -query = {'name':'John'} -db.students.delete_one(query) - -for student in db.students.find(): - print(student) -# 让我们检查结果,看看年龄是否被修改 -for student in db.students.find(): - print(student) - -app = Flask(__name__) -if __name__ == '__main__': - # 部署时我们使用环境变量 - # 使其同时适用于生产和开发环境 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38} -{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} -{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} -``` - -如你所见,John已经从集合中删除。 - -当我们想要删除多个文档时,我们使用*delete_many()*方法,它接受一个查询对象。如果我们将一个空的查询对象传递给*delete_many({})*,它将删除集合中的所有文档。 - -### 删除集合 - -使用_drop()_方法,我们可以从数据库中删除一个集合。 - -```py -# 导入flask -from flask import Flask, render_template -import os # 导入操作系统模块 -import pymongo - -MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 -db.students.drop() -``` - -现在,我们已经从数据库中删除了students集合。 - -## 💻 练习:第27天 - -🎉 恭喜!🎉 - -[<< 第26天](./26_Day_Python_web/26_python_web_cn.md) | [第28天 >>](./28_Day_API/28_API_cn.md) \ No newline at end of file +# 30天Python编程挑战:第27天 - Python与MongoDB + +- [第27天](#-第27天) +- [Python与MongoDB](#python与mongodb) + - [MongoDB](#mongodb) + - [SQL与NoSQL的比较](#sql与nosql的比较) + - [获取连接字符串(MongoDB URI)](#获取连接字符串mongodb-uri) + - [将Flask应用程序连接到MongoDB集群](#将flask应用程序连接到mongodb集群) + - [创建数据库和集合](#创建数据库和集合) + - [向集合中插入多个文档](#向集合中插入多个文档) + - [MongoDB查找](#mongodb查找) + - [使用查询进行查找](#使用查询进行查找) + - [使用修饰符的查询查找](#使用修饰符的查询查找) + - [限制文档数量](#限制文档数量) + - [使用排序进行查找](#使用排序进行查找) + - [使用查询进行更新](#使用查询进行更新) + - [删除文档](#删除文档) + - [删除集合](#删除集合) + - [💻 练习:第27天](#-练习第27天) + +# 📘 第27天 + +# Python与MongoDB + +Python是一种后端技术,可以与不同的数据库应用程序连接。它可以连接到SQL和NoSQL数据库。在本节中,我们将Python与MongoDB数据库连接,MongoDB是一种NoSQL数据库。 + +## MongoDB + +MongoDB是一种NoSQL数据库。MongoDB以类似JSON的文档形式存储数据,这使得MongoDB非常灵活和可扩展。让我们看看SQL和NoSQL数据库的不同术语。下表将展示SQL与NoSQL数据库之间的区别。 + +### SQL与NoSQL的比较 + +![SQL与NoSQL](../images/mongoDB/sql-vs-nosql.png) + +在本节中,我们将重点关注NoSQL数据库MongoDB。通过点击注册按钮,然后在下一页点击注册,让我们在[mongoDB](https://www.mongodb.com/)上注册。 + +![MongoDB注册页面](../images/mongoDB/mongodb-signup-page.png) + +完成表格并点击继续 + +![MongoDB注册](../images/mongoDB/mongodb-register.png) + +选择免费计划 + +![MongoDB免费计划](../images/mongoDB/mongodb-free.png) + +选择最近的免费区域,并为你的集群命名。 + +![MongoDB集群名称](../images/mongoDB/mongodb-cluster-name.png) + +现在,一个免费的沙箱已创建 + +![MongoDB沙箱](../images/mongoDB/mongodb-sandbox.png) + +允许所有本地主机访问 + +![MongoDB允许IP访问](../images/mongoDB/mongodb-allow-ip-access.png) + +添加用户和密码 + +![MongoDB添加用户](../images/mongoDB/mongodb-add-user.png) + +创建MongoDB URI链接 + +![MongoDB创建URI](../images/mongoDB/mongodb-create-uri.png) + +选择Python 3.6或更高版本的驱动程序 + +![MongoDB Python驱动程序](../images/mongoDB/mongodb-python-driver.png) + +### 获取连接字符串(MongoDB URI) + +复制连接字符串链接,你将获得类似这样的内容: + +```sh +mongodb+srv://asabeneh:@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority +``` + +不要担心这个URL,它是连接你的应用程序与mongoDB的一种方式。 +让我们用你添加用户时使用的密码替换密码占位符。 + +**示例:** + +```sh +mongodb+srv://asabeneh:123123123@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority +``` + +现在,我已经替换了所有内容,密码是123123123,数据库名称是*thirty_days_python*。这只是一个示例,你的密码必须比示例密码更强。 + +Python需要mongoDB驱动程序才能访问mongoDB数据库。我们将使用_pymongo_和_dnspython_来连接我们的应用程序与mongoDB基础。在你的项目目录中安装pymongo和dnspython。 + +```sh +pip install pymongo dnspython +``` + +要使用mongodb+srv://URI,必须安装"dnspython"模块。dnspython是用于Python的DNS工具包。它支持几乎所有记录类型。 + +### 将Flask应用程序连接到MongoDB集群 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +print(client.list_database_names()) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +当我们运行上面的代码时,我们会得到默认的mongoDB数据库。 + +```sh +['admin', 'local'] +``` + +### 创建数据库和集合 + +让我们创建一个数据库,如果数据库和集合在mongoDB中不存在,它们将被创建。让我们创建一个名为*thirty_days_of_python*的数据库和*students*集合。 + +创建数据库的方法: + +```sh +db = client.name_of_databse # 我们可以这样创建数据库,或者使用第二种方式 +db = client['name_of_database'] +``` + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +# 创建数据库 +db = client.thirty_days_of_python +# 创建students集合并插入文档 +db.students.insert_one({'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}) +print(client.list_database_names()) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +在创建数据库后,我们还创建了一个students集合,并使用*insert_one()*方法插入了一个文档。 +现在,数据库*thirty_days_of_python*和*students*集合已经创建,并且文档已经插入。 +检查你的mongoDB集群,你将看到数据库和集合。在集合内部,将有一个文档。 + +```sh +['thirty_days_of_python', 'admin', 'local'] +``` + +如果你在mongoDB集群上看到这个,这意味着你已经成功创建了一个数据库和一个集合。 + +![创建数据库和集合](../images/mongoDB/mongodb-creating_database.png) + +如果你看到上图,文档已经创建,并带有一个长ID作为主键。每次我们创建一个文档,mongoDB都会为它创建一个唯一的ID。 + +### 向集合中插入多个文档 + +*insert_one()*方法一次插入一个项目,如果我们想一次插入多个文档,我们可以使用*insert_many()*方法或for循环。 +我们可以使用for循环一次插入多个文档。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) + +students = [ + {'name':'David','country':'UK','city':'London','age':34}, + {'name':'John','country':'Sweden','city':'Stockholm','age':28}, + {'name':'Sami','country':'Finland','city':'Helsinki','age':25}, + ] +for student in students: + db.students.insert_one(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +### MongoDB查找 + +*find()*和*findOne()*方法是在mongoDB数据库集合中查找数据的常用方法。它类似于MySQL数据库中的SELECT语句。 +让我们使用_find_one()_方法来获取数据库集合中的一个文档。 + +- \*find_one({"\_id": ObjectId("id"}): 如果没有提供id,则获取第一次出现的文档 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +student = db.students.find_one() +print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Helsinki', 'city': 'Helsinki', 'age': 250} +``` + +上面的查询返回第一个条目,但我们可以使用特定的\_id来定位特定的文档。让我们做一个例子,使用David的id来获取David对象。 +'\_id':ObjectId('5df68a23f106fe2d315bbc8c') + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +from bson.objectid import ObjectId # id对象 +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +student = db.students.find_one({'_id':ObjectId('5df68a23f106fe2d315bbc8c')}) +print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +``` + +我们已经看到如何使用上面的例子来使用_find_one()_。让我们进一步了解_find()_ + +- _find()_: 如果我们不传递查询对象,返回集合中的所有出现。该对象是pymongo.cursor对象。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +students = db.students.find() +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +我们可以通过在_find({}, {})_中传递第二个对象来指定要返回的字段。0表示不包含,1表示包含,但我们不能混合使用0和1,除了\_id。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +students = db.students.find({}, {"_id":0, "name": 1, "country":1}) # 0表示不包含,1表示包含 +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'name': 'Asabeneh', 'country': 'Finland'} +{'name': 'David', 'country': 'UK'} +{'name': 'John', 'country': 'Sweden'} +{'name': 'Sami', 'country': 'Finland'} +``` + +### 使用查询进行查找 + +在mongoDB中,find接受一个查询对象。我们可以传递一个查询对象,我们可以过滤我们想要过滤的文档。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = { + "country":"Finland" +} +students = db.students.find(query) + +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +带有修饰符的查询 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = { + "city":"Helsinki" +} +students = db.students.find(query) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +### 使用修饰符的查询查找 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +query = { + "country":"Finland", + "city":"Helsinki" +} +students = db.students.find(query) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +带有修饰符的查询 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +query = {"age":{"$gt":30}} +students = db.students.find(query) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +``` + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +query = {"age":{"$lt":30}} +students = db.students.find(query) +for student in students: + print(student) +``` + +```sh +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +### 限制文档数量 + +我们可以使用_limit()_方法来限制我们返回的文档数量。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +db.students.find().limit(3) +``` + +### 使用排序进行查找 + +默认情况下,排序是升序的。我们可以通过添加-1参数将排序更改为降序。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +students = db.students.find().sort('name') +for student in students: + print(student) + +students = db.students.find().sort('name',-1) +for student in students: + print(student) + +students = db.students.find().sort('age') +for student in students: + print(student) + +students = db.students.find().sort('age',-1) +for student in students: + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +升序 + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +降序 + +```sh +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} +``` + +### 使用查询进行更新 + +我们将使用*update_one()*方法来更新一个项目。它接受两个对象,一个是查询,另一个是新对象。 +第一个人,Asabeneh得到了一个非常不合理的年龄。让我们更新Asabeneh的年龄。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = {'age':250} +new_value = {'$set':{'age':38}} + +db.students.update_one(query, new_value) +# 让我们检查结果,看看年龄是否被修改 +for student in db.students.find(): + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8d'), 'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +当我们想要一次更新多个文档时,我们使用*upate_many()*方法。 + +### 删除文档 + +方法*delete_one()*删除一个文档。*delete_one()*方法接受一个查询对象参数。它只删除第一次出现的文档。 +让我们从集合中删除一个John。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +query = {'name':'John'} +db.students.delete_one(query) + +for student in db.students.find(): + print(student) +# 让我们检查结果,看看年龄是否被修改 +for student in db.students.find(): + print(student) + +app = Flask(__name__) +if __name__ == '__main__': + # 部署时我们使用环境变量 + # 使其同时适用于生产和开发环境 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +{'_id': ObjectId('5df68a21f106fe2d315bbc8b'), 'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 38} +{'_id': ObjectId('5df68a23f106fe2d315bbc8c'), 'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34} +{'_id': ObjectId('5df68a23f106fe2d315bbc8e'), 'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25} +``` + +如你所见,John已经从集合中删除。 + +当我们想要删除多个文档时,我们使用*delete_many()*方法,它接受一个查询对象。如果我们将一个空的查询对象传递给*delete_many({})*,它将删除集合中的所有文档。 + +### 删除集合 + +使用_drop()_方法,我们可以从数据库中删除一个集合。 + +```py +# 导入flask +from flask import Flask, render_template +import os # 导入操作系统模块 +import pymongo + +MONGODB_URI = 'mongodb+srv://asabeneh:your_password_goes_here@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 +db.students.drop() +``` + +现在,我们已经从数据库中删除了students集合。 + +## 💻 练习:第27天 + +🎉 恭喜!🎉 + +[<< 第 26 天](./26_python_web_cn.md) | [第 28 天 >>](./28_API_cn.md) \ No newline at end of file diff --git a/Chinese/28_API_cn.md b/Chinese/28_API_cn.md index 32b6d415c..b506a5339 100644 --- a/Chinese/28_API_cn.md +++ b/Chinese/28_API_cn.md @@ -1,143 +1,143 @@ -# 30天Python编程挑战:第28天 - API - -- [第28天](#-第28天) -- [应用程序编程接口(API)](#应用程序编程接口api) - - [API](#api) - - [构建API](#构建api) - - [HTTP(超文本传输协议)](#http超文本传输协议) - - [HTTP的结构](#http的结构) - - [初始请求行(状态行)](#初始请求行状态行) - - [初始响应行(状态行)](#初始响应行状态行) - - [头字段](#头字段) - - [消息体](#消息体) - - [请求方法](#请求方法) - - [💻 练习:第28天](#-练习第28天) - -# 📘 第28天 - -# 应用程序编程接口(API) - -## API - -API是应用程序编程接口(Application Programming Interface)的缩写。我们在本节中将介绍的API类型是Web API。 -Web API是定义好的接口,通过这些接口在企业和使用其资产的应用程序之间进行交互,这也是一种服务级别协议(SLA),用于指定功能提供者并为其API用户公开服务路径或URL。 - -在Web开发的上下文中,API被定义为一组规范,如超文本传输协议(HTTP)请求消息,以及响应消息结构的定义,通常采用XML或JavaScript对象表示法(JSON)格式。 - -Web API已经从基于简单对象访问协议(SOAP)的Web服务和面向服务的架构(SOA)转向更直接的表征状态转移(REST)风格的Web资源。 - -社交媒体服务和Web API已经允许Web社区在社区和不同平台之间共享内容和数据。 - -使用API,在一个地方创建的内容可以动态地在Web上的多个位置发布和更新。 - -例如,Twitter的REST API允许开发人员访问核心Twitter数据,而搜索API提供了开发人员与Twitter搜索和趋势数据互动的方法。 - -许多应用程序提供API端点。一些API的例子,如国家[API](https://restcountries.eu/rest/v2/all),[猫品种API](https://api.thecatapi.com/v1/breeds)。 - -在本节中,我们将介绍一个RESTful API,它使用HTTP请求方法来GET、PUT、POST和DELETE数据。 - -## 构建API - -RESTful API是一种应用程序编程接口(API),使用HTTP请求来GET、PUT、POST和DELETE数据。在前几节中,我们学习了Python、Flask和MongoDB。我们将利用我们获得的知识,使用Python Flask和MongoDB数据库开发一个RESTful API。每个具有CRUD(创建、读取、更新、删除)操作的应用程序都有一个API,用于从数据库创建数据、获取数据、更新数据或删除数据。 - -要构建API,了解HTTP协议和HTTP请求、响应周期是很好的。 - -## HTTP(超文本传输协议) - -HTTP是客户端和服务器之间建立的通信协议。在这种情况下,客户端是浏览器,服务器是你访问数据的地方。HTTP是一种网络协议,用于传递资源,这些资源可以是万维网上的文件,无论是HTML文件、图像文件、查询结果、脚本或其他文件类型。 - -浏览器是HTTP客户端,因为它向HTTP服务器(Web服务器)发送请求,而HTTP服务器再向客户端发送响应。 - -## HTTP的结构 - -HTTP使用客户端-服务器模型。HTTP客户端打开一个连接并向HTTP服务器发送请求消息,HTTP服务器返回响应消息,即请求的资源。当请求响应周期完成时,服务器关闭连接。 - -![HTTP请求响应周期](../images/http_request_response_cycle.png) - -请求和响应消息的格式类似。两种消息都有 - -- 一个初始行 -- 零个或多个头行 -- 一个空行(即单独的CRLF) -- 一个可选的消息体(例如文件、查询数据或查询输出) - -让我们通过导航此站点来看一个请求和响应消息的示例:https://thirtydaysofpython-v1-final.herokuapp.com/ 。这个网站已部署在Heroku免费dyno上,在某些月份可能由于高请求量而无法工作。支持这项工作可以让服务器始终运行。 - -![请求和响应头](../images/request_response_header.png) - -## 初始请求行(状态行) - -初始请求行与响应不同。 -请求行有三个部分,用空格分隔: - -- 方法名(GET、POST、HEAD) -- 请求资源的路径 -- 使用的HTTP版本。例如 GET / HTTP/1.1 - -GET是最常见的HTTP方法,用于获取或读取资源,而POST是常见的请求方法,用于创建资源。 - -### 初始响应行(状态行) - -初始响应行,称为状态行,也有三个用空格分隔的部分: - -- HTTP版本 -- 响应状态码,给出请求的结果,以及描述状态码的原因。状态行的例子有: - HTTP/1.0 200 OK - 或者 - HTTP/1.0 404 Not Found - 注意: - -最常见的状态码是: -200 OK:请求成功,并且生成的资源(例如文件或脚本输出)在消息体中返回。 -500 服务器错误 -完整的HTTP状态码列表可以在[这里](https://httpstatuses.com/)找到。也可以在[这里](https://httpstatusdogs.com/)找到。 - -### 头字段 - -正如你在上面的截图中看到的,头行提供了有关请求或响应的信息,或者有关在消息体中发送的对象的信息。 - -```sh -GET / HTTP/1.1 -Host: thirtydaysofpython-v1-final.herokuapp.com -Connection: keep-alive -Pragma: no-cache -Cache-Control: no-cache -Upgrade-Insecure-Requests: 1 -User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36 -Sec-Fetch-User: ?1 -Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 -Sec-Fetch-Site: same-origin -Sec-Fetch-Mode: navigate -Referer: https://thirtydaysofpython-v1-final.herokuapp.com/post -Accept-Encoding: gzip, deflate, br -Accept-Language: en-GB,en;q=0.9,fi-FI;q=0.8,fi;q=0.7,en-CA;q=0.6,en-US;q=0.5,fr;q=0.4 -``` - -### 消息体 - -HTTP消息可能在头行之后发送数据体。在响应中,这是请求的资源返回给客户端的地方(消息体最常用的用途),或者如果出现错误,这里可能是解释性文本。在请求中,这是用户输入的数据或上传的文件发送到服务器的地方。 - -如果HTTP消息包含一个消息体,通常在消息中有描述该消息体的头行。特别是: - -Content-Type: 头给出消息体中数据的MIME类型(text/html,application/json,text/plain,text/css,image/gif)。 -Content-Length: 头给出消息体中的字节数。 - -### 请求方法 - -GET、POST、PUT和DELETE是我们将实现API或CRUD操作应用程序的HTTP请求方法。 - -1. GET:GET方法用于使用给定的URI从给定服务器检索和获取信息。使用GET的请求应该只检索数据,而不应该对数据有任何其他影响。 - -2. POST:POST请求用于创建数据并将数据发送到服务器,例如使用HTML表单创建新帖子、上传文件等。 - -3. PUT:用上传的内容替换目标资源的所有当前表示,我们使用它来修改或更新数据。 - -4. DELETE:删除数据 - -## 💻 练习:第28天 - -1. 阅读有关API和HTTP的资料 - -🎉 恭喜!🎉 - -[<< 第27天](./27_Day_Python_with_mongodb/27_python_with_mongodb_cn.md) | [第29天 >>](./29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file +# 30天Python编程挑战:第28天 - API + +- [第28天](#-第28天) +- [应用程序编程接口(API)](#应用程序编程接口api) + - [API](#api) + - [构建API](#构建api) + - [HTTP(超文本传输协议)](#http超文本传输协议) + - [HTTP的结构](#http的结构) + - [初始请求行(状态行)](#初始请求行状态行) + - [初始响应行(状态行)](#初始响应行状态行) + - [头字段](#头字段) + - [消息体](#消息体) + - [请求方法](#请求方法) + - [💻 练习:第28天](#-练习第28天) + +# 📘 第28天 + +# 应用程序编程接口(API) + +## API + +API是应用程序编程接口(Application Programming Interface)的缩写。我们在本节中将介绍的API类型是Web API。 +Web API是定义好的接口,通过这些接口在企业和使用其资产的应用程序之间进行交互,这也是一种服务级别协议(SLA),用于指定功能提供者并为其API用户公开服务路径或URL。 + +在Web开发的上下文中,API被定义为一组规范,如超文本传输协议(HTTP)请求消息,以及响应消息结构的定义,通常采用XML或JavaScript对象表示法(JSON)格式。 + +Web API已经从基于简单对象访问协议(SOAP)的Web服务和面向服务的架构(SOA)转向更直接的表征状态转移(REST)风格的Web资源。 + +社交媒体服务和Web API已经允许Web社区在社区和不同平台之间共享内容和数据。 + +使用API,在一个地方创建的内容可以动态地在Web上的多个位置发布和更新。 + +例如,Twitter的REST API允许开发人员访问核心Twitter数据,而搜索API提供了开发人员与Twitter搜索和趋势数据互动的方法。 + +许多应用程序提供API端点。一些API的例子,如国家[API](https://restcountries.eu/rest/v2/all),[猫品种API](https://api.thecatapi.com/v1/breeds)。 + +在本节中,我们将介绍一个RESTful API,它使用HTTP请求方法来GET、PUT、POST和DELETE数据。 + +## 构建API + +RESTful API是一种应用程序编程接口(API),使用HTTP请求来GET、PUT、POST和DELETE数据。在前几节中,我们学习了Python、Flask和MongoDB。我们将利用我们获得的知识,使用Python Flask和MongoDB数据库开发一个RESTful API。每个具有CRUD(创建、读取、更新、删除)操作的应用程序都有一个API,用于从数据库创建数据、获取数据、更新数据或删除数据。 + +要构建API,了解HTTP协议和HTTP请求、响应周期是很好的。 + +## HTTP(超文本传输协议) + +HTTP是客户端和服务器之间建立的通信协议。在这种情况下,客户端是浏览器,服务器是你访问数据的地方。HTTP是一种网络协议,用于传递资源,这些资源可以是万维网上的文件,无论是HTML文件、图像文件、查询结果、脚本或其他文件类型。 + +浏览器是HTTP客户端,因为它向HTTP服务器(Web服务器)发送请求,而HTTP服务器再向客户端发送响应。 + +## HTTP的结构 + +HTTP使用客户端-服务器模型。HTTP客户端打开一个连接并向HTTP服务器发送请求消息,HTTP服务器返回响应消息,即请求的资源。当请求响应周期完成时,服务器关闭连接。 + +![HTTP请求响应周期](../images/http_request_response_cycle.png) + +请求和响应消息的格式类似。两种消息都有 + +- 一个初始行 +- 零个或多个头行 +- 一个空行(即单独的CRLF) +- 一个可选的消息体(例如文件、查询数据或查询输出) + +让我们通过导航此站点来看一个请求和响应消息的示例:https://thirtydaysofpython-v1-final.herokuapp.com/ 。这个网站已部署在Heroku免费dyno上,在某些月份可能由于高请求量而无法工作。支持这项工作可以让服务器始终运行。 + +![请求和响应头](../images/request_response_header.png) + +## 初始请求行(状态行) + +初始请求行与响应不同。 +请求行有三个部分,用空格分隔: + +- 方法名(GET、POST、HEAD) +- 请求资源的路径 +- 使用的HTTP版本。例如 GET / HTTP/1.1 + +GET是最常见的HTTP方法,用于获取或读取资源,而POST是常见的请求方法,用于创建资源。 + +### 初始响应行(状态行) + +初始响应行,称为状态行,也有三个用空格分隔的部分: + +- HTTP版本 +- 响应状态码,给出请求的结果,以及描述状态码的原因。状态行的例子有: + HTTP/1.0 200 OK + 或者 + HTTP/1.0 404 Not Found + 注意: + +最常见的状态码是: +200 OK:请求成功,并且生成的资源(例如文件或脚本输出)在消息体中返回。 +500 服务器错误 +完整的HTTP状态码列表可以在[这里](https://httpstatuses.com/)找到。也可以在[这里](https://httpstatusdogs.com/)找到。 + +### 头字段 + +正如你在上面的截图中看到的,头行提供了有关请求或响应的信息,或者有关在消息体中发送的对象的信息。 + +```sh +GET / HTTP/1.1 +Host: thirtydaysofpython-v1-final.herokuapp.com +Connection: keep-alive +Pragma: no-cache +Cache-Control: no-cache +Upgrade-Insecure-Requests: 1 +User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36 +Sec-Fetch-User: ?1 +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 +Sec-Fetch-Site: same-origin +Sec-Fetch-Mode: navigate +Referer: https://thirtydaysofpython-v1-final.herokuapp.com/post +Accept-Encoding: gzip, deflate, br +Accept-Language: en-GB,en;q=0.9,fi-FI;q=0.8,fi;q=0.7,en-CA;q=0.6,en-US;q=0.5,fr;q=0.4 +``` + +### 消息体 + +HTTP消息可能在头行之后发送数据体。在响应中,这是请求的资源返回给客户端的地方(消息体最常用的用途),或者如果出现错误,这里可能是解释性文本。在请求中,这是用户输入的数据或上传的文件发送到服务器的地方。 + +如果HTTP消息包含一个消息体,通常在消息中有描述该消息体的头行。特别是: + +Content-Type: 头给出消息体中数据的MIME类型(text/html,application/json,text/plain,text/css,image/gif)。 +Content-Length: 头给出消息体中的字节数。 + +### 请求方法 + +GET、POST、PUT和DELETE是我们将实现API或CRUD操作应用程序的HTTP请求方法。 + +1. GET:GET方法用于使用给定的URI从给定服务器检索和获取信息。使用GET的请求应该只检索数据,而不应该对数据有任何其他影响。 + +2. POST:POST请求用于创建数据并将数据发送到服务器,例如使用HTML表单创建新帖子、上传文件等。 + +3. PUT:用上传的内容替换目标资源的所有当前表示,我们使用它来修改或更新数据。 + +4. DELETE:删除数据 + +## 💻 练习:第28天 + +1. 阅读有关API和HTTP的资料 + +🎉 恭喜!🎉 + +[<< 第 27 天](./27_python_with_mongodb_cn.md) | [第 29 天 >>](./29_building_API_cn.md) \ No newline at end of file diff --git a/Chinese/29_building_API_cn.md b/Chinese/29_building_API_cn.md index 07cb454ad..39987e69c 100644 --- a/Chinese/29_building_API_cn.md +++ b/Chinese/29_building_API_cn.md @@ -1,460 +1,460 @@ -# 30天Python编程挑战:第29天 - 构建API - -- [第29天](#第29天) -- [构建API](#构建api) - - [API的结构](#api的结构) - - [使用GET获取数据](#使用get获取数据) - - [通过ID获取文档](#通过id获取文档) - - [使用POST创建数据](#使用post创建数据) - - [使用PUT更新](#使用put更新) - - [使用Delete删除文档](#使用delete删除文档) -- [💻 练习:第29天](#-练习第29天) - -## 第29天 - -## 构建API - -在本节中,我们将介绍一个RESTful API,它使用HTTP请求方法来GET、PUT、POST和DELETE数据。 - -RESTful API是一种应用程序编程接口(API),使用HTTP请求来GET、PUT、POST和DELETE数据。在前几节中,我们学习了Python、Flask和MongoDB。我们将利用我们获得的知识,使用Python Flask和MongoDB开发一个RESTful API。每个具有CRUD(创建、读取、更新、删除)操作的应用程序都有一个API,用于从数据库创建数据、获取数据、更新数据或删除数据。 - -浏览器只能处理GET请求。因此,我们必须有一个工具,可以帮助我们处理所有请求方法(GET、POST、PUT、DELETE)。 - -API示例: - -- 国家API:https://restcountries.eu/rest/v2/all -- 猫品种API:https://api.thecatapi.com/v1/breeds - -[Postman](https://www.getpostman.com/)是API开发领域非常流行的工具。所以,如果你想完成本节内容,你需要[下载Postman](https://www.getpostman.com/)。Postman的替代品是[Insomnia](https://insomnia.rest/download)。 - -![Postman](../images/postman.png) - -### API的结构 - -API端点是一个可以帮助检索、创建、更新或删除资源的URL。结构如下所示: -示例: -https://api.twitter.com/1.1/lists/members.json -返回指定列表的成员。只有当经过身份验证的用户拥有指定列表时,才会显示私人列表成员。 -公司名称后跟版本,然后是API的目的。 -方法: -HTTP方法和URL - -API使用以下HTTP方法进行对象操作: - -```sh -GET 用于对象检索 -POST 用于对象创建和对象操作 -PUT 用于对象更新 -DELETE 用于对象删除 -``` - -让我们构建一个收集关于30DaysOfPython学生信息的API。我们将收集姓名、国家、城市、出生日期、技能和个人简介。 - -为了实现这个API,我们将使用: - -- Postman -- Python -- Flask -- MongoDB - -### 使用GET获取数据 - -在这一步中,让我们使用虚拟数据并将其作为json返回。为了将其作为json返回,我们将使用json模块和Response模块。 - -```py -# 导入flask - -from flask import Flask, Response -import json - -app = Flask(__name__) - -@app.route('/api/v1.0/students', methods = ['GET']) -def students (): - student_list = [ - { - 'name':'Asabeneh', - 'country':'Finland', - 'city':'Helsinki', - 'skills':['HTML', 'CSS','JavaScript','Python'] - }, - { - 'name':'David', - 'country':'UK', - 'city':'London', - 'skills':['Python','MongoDB'] - }, - { - 'name':'John', - 'country':'Sweden', - 'city':'Stockholm', - 'skills':['Java','C#'] - } - ] - return Response(json.dumps(student_list), mimetype='application/json') - - -if __name__ == '__main__': - # 部署时使用 - # 使其在生产和开发环境中都能工作 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -当你在浏览器上请求http://localhost:5000/api/v1.0/students URL时,你将获得以下内容: - -![在浏览器上的GET](../images/get_on_browser.png) - -当你在Postman上请求http://localhost:5000/api/v1.0/students URL时,你将获得以下内容: - -![在Postman上的GET](../images/get_on_postman.png) - -我们不再显示虚拟数据,而是将Flask应用程序与MongoDB连接,并从MongoDB数据库获取数据。 - -```py -# 导入flask - -from flask import Flask, Response -import json -import pymongo - - -app = Flask(__name__) - -# -MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -@app.route('/api/v1.0/students', methods = ['GET']) -def students (): - - return Response(json.dumps(student), mimetype='application/json') - - -if __name__ == '__main__': - # 部署时使用 - # 使其在生产和开发环境中都能工作 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -通过连接Flask,我们可以从thirty_days_of_python数据库中获取学生集合数据。 - -```sh -[ - { - "_id": { - "$oid": "5df68a21f106fe2d315bbc8b" - }, - "name": "Asabeneh", - "country": "Finland", - "city": "Helsinki", - "age": 38 - }, - { - "_id": { - "$oid": "5df68a23f106fe2d315bbc8c" - }, - "name": "David", - "country": "UK", - "city": "London", - "age": 34 - }, - { - "_id": { - "$oid": "5df68a23f106fe2d315bbc8e" - }, - "name": "Sami", - "country": "Finland", - "city": "Helsinki", - "age": 25 - } -] -``` - -### 通过ID获取文档 - -我们可以使用ID访问单个文档,让我们使用ID访问Asabeneh。 -http://localhost:5000/api/v1.0/students/5df68a21f106fe2d315bbc8b - -```py -# 导入flask - -from flask import Flask, Response -import json -from bson.objectid import ObjectId -import json -from bson.json_util import dumps -import pymongo - - -app = Flask(__name__) - -# -MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -@app.route('/api/v1.0/students', methods = ['GET']) -def students (): - - return Response(json.dumps(student), mimetype='application/json') -@app.route('/api/v1.0/students/', methods = ['GET']) -def single_student (id): - student = db.students.find({'_id':ObjectId(id)}) - return Response(dumps(student), mimetype='application/json') - -if __name__ == '__main__': - # 部署时使用 - # 使其在生产和开发环境中都能工作 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -```sh -[ - { - "_id": { - "$oid": "5df68a21f106fe2d315bbc8b" - }, - "name": "Asabeneh", - "country": "Finland", - "city": "Helsinki", - "age": 38 - } -] -``` - -### 使用POST创建数据 - -我们使用POST请求方法创建数据 - -```py -# 导入flask - -from flask import Flask, Response -import json -from bson.objectid import ObjectId -import json -from bson.json_util import dumps -import pymongo -from datetime import datetime - - -app = Flask(__name__) - -# -MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -@app.route('/api/v1.0/students', methods = ['GET']) -def students (): - - return Response(json.dumps(student), mimetype='application/json') -@app.route('/api/v1.0/students/', methods = ['GET']) -def single_student (id): - student = db.students.find({'_id':ObjectId(id)}) - return Response(dumps(student), mimetype='application/json') -@app.route('/api/v1.0/students', methods = ['POST']) -def create_student (): - name = request.form['name'] - country = request.form['country'] - city = request.form['city'] - skills = request.form['skills'].split(', ') - bio = request.form['bio'] - birthyear = request.form['birthyear'] - created_at = datetime.now() - student = { - 'name': name, - 'country': country, - 'city': city, - 'birthyear': birthyear, - 'skills': skills, - 'bio': bio, - 'created_at': created_at - - } - db.students.insert_one(student) - return ; -def update_student (id): -if __name__ == '__main__': - # 部署时使用 - # 使其在生产和开发环境中都能工作 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -### 使用PUT更新 - -```py -# 导入flask - -from flask import Flask, Response -import json -from bson.objectid import ObjectId -import json -from bson.json_util import dumps -import pymongo -from datetime import datetime - - -app = Flask(__name__) - -# -MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -@app.route('/api/v1.0/students', methods = ['GET']) -def students (): - - return Response(json.dumps(student), mimetype='application/json') -@app.route('/api/v1.0/students/', methods = ['GET']) -def single_student (id): - student = db.students.find({'_id':ObjectId(id)}) - return Response(dumps(student), mimetype='application/json') -@app.route('/api/v1.0/students', methods = ['POST']) -def create_student (): - name = request.form['name'] - country = request.form['country'] - city = request.form['city'] - skills = request.form['skills'].split(', ') - bio = request.form['bio'] - birthyear = request.form['birthyear'] - created_at = datetime.now() - student = { - 'name': name, - 'country': country, - 'city': city, - 'birthyear': birthyear, - 'skills': skills, - 'bio': bio, - 'created_at': created_at - - } - db.students.insert_one(student) - return -@app.route('/api/v1.0/students/', methods = ['PUT']) # 这个装饰器创建主页路由 -def update_student (id): - query = {"_id":ObjectId(id)} - name = request.form['name'] - country = request.form['country'] - city = request.form['city'] - skills = request.form['skills'].split(', ') - bio = request.form['bio'] - birthyear = request.form['birthyear'] - created_at = datetime.now() - student = { - 'name': name, - 'country': country, - 'city': city, - 'birthyear': birthyear, - 'skills': skills, - 'bio': bio, - 'created_at': created_at - - } - db.students.update_one(query, student) - # return Response(dumps({"result":"a new student has been created"}), mimetype='application/json') - return -def update_student (id): -if __name__ == '__main__': - # 部署时使用 - # 使其在生产和开发环境中都能工作 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -### 使用Delete删除文档 - -```py -# 导入flask - -from flask import Flask, Response -import json -from bson.objectid import ObjectId -import json -from bson.json_util import dumps -import pymongo -from datetime import datetime - - -app = Flask(__name__) - -# -MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' -client = pymongo.MongoClient(MONGODB_URI) -db = client['thirty_days_of_python'] # 访问数据库 - -@app.route('/api/v1.0/students', methods = ['GET']) -def students (): - - return Response(json.dumps(student), mimetype='application/json') -@app.route('/api/v1.0/students/', methods = ['GET']) -def single_student (id): - student = db.students.find({'_id':ObjectId(id)}) - return Response(dumps(student), mimetype='application/json') -@app.route('/api/v1.0/students', methods = ['POST']) -def create_student (): - name = request.form['name'] - country = request.form['country'] - city = request.form['city'] - skills = request.form['skills'].split(', ') - bio = request.form['bio'] - birthyear = request.form['birthyear'] - created_at = datetime.now() - student = { - 'name': name, - 'country': country, - 'city': city, - 'birthyear': birthyear, - 'skills': skills, - 'bio': bio, - 'created_at': created_at - - } - db.students.insert_one(student) - return -@app.route('/api/v1.0/students/', methods = ['PUT']) # 这个装饰器创建主页路由 -def update_student (id): - query = {"_id":ObjectId(id)} - name = request.form['name'] - country = request.form['country'] - city = request.form['city'] - skills = request.form['skills'].split(', ') - bio = request.form['bio'] - birthyear = request.form['birthyear'] - created_at = datetime.now() - student = { - 'name': name, - 'country': country, - 'city': city, - 'birthyear': birthyear, - 'skills': skills, - 'bio': bio, - 'created_at': created_at - - } - db.students.update_one(query, student) - # return Response(dumps({"result":"a new student has been created"}), mimetype='application/json') - return ; -@app.route('/api/v1.0/students/', methods = ['DELETE']) -def delete_student (id): - db.students.delete_one({"_id":ObjectId(id)}) - return -if __name__ == '__main__': - # 部署时使用 - # 使其在生产和开发环境中都能工作 - port = int(os.environ.get("PORT", 5000)) - app.run(debug=True, host='0.0.0.0', port=port) -``` - -## 💻 练习:第29天 - -1. 实现上述示例并开发[这个](https://thirtydayofpython-api.herokuapp.com/) - -🎉 恭喜!🎉 - -[<< 第28天](./28_Day_API/28_API_cn.md) | [第30天 >>](./30_Day_Conclusions/30_conclusions_cn.md) \ No newline at end of file +# 30天Python编程挑战:第29天 - 构建API + +- [第29天](#第29天) +- [构建API](#构建api) + - [API的结构](#api的结构) + - [使用GET获取数据](#使用get获取数据) + - [通过ID获取文档](#通过id获取文档) + - [使用POST创建数据](#使用post创建数据) + - [使用PUT更新](#使用put更新) + - [使用Delete删除文档](#使用delete删除文档) +- [💻 练习:第29天](#-练习第29天) + +## 第29天 + +## 构建API + +在本节中,我们将介绍一个RESTful API,它使用HTTP请求方法来GET、PUT、POST和DELETE数据。 + +RESTful API是一种应用程序编程接口(API),使用HTTP请求来GET、PUT、POST和DELETE数据。在前几节中,我们学习了Python、Flask和MongoDB。我们将利用我们获得的知识,使用Python Flask和MongoDB开发一个RESTful API。每个具有CRUD(创建、读取、更新、删除)操作的应用程序都有一个API,用于从数据库创建数据、获取数据、更新数据或删除数据。 + +浏览器只能处理GET请求。因此,我们必须有一个工具,可以帮助我们处理所有请求方法(GET、POST、PUT、DELETE)。 + +API示例: + +- 国家API:https://restcountries.eu/rest/v2/all +- 猫品种API:https://api.thecatapi.com/v1/breeds + +[Postman](https://www.getpostman.com/)是API开发领域非常流行的工具。所以,如果你想完成本节内容,你需要[下载Postman](https://www.getpostman.com/)。Postman的替代品是[Insomnia](https://insomnia.rest/download)。 + +![Postman](../images/postman.png) + +### API的结构 + +API端点是一个可以帮助检索、创建、更新或删除资源的URL。结构如下所示: +示例: +https://api.twitter.com/1.1/lists/members.json +返回指定列表的成员。只有当经过身份验证的用户拥有指定列表时,才会显示私人列表成员。 +公司名称后跟版本,然后是API的目的。 +方法: +HTTP方法和URL + +API使用以下HTTP方法进行对象操作: + +```sh +GET 用于对象检索 +POST 用于对象创建和对象操作 +PUT 用于对象更新 +DELETE 用于对象删除 +``` + +让我们构建一个收集关于30DaysOfPython学生信息的API。我们将收集姓名、国家、城市、出生日期、技能和个人简介。 + +为了实现这个API,我们将使用: + +- Postman +- Python +- Flask +- MongoDB + +### 使用GET获取数据 + +在这一步中,让我们使用虚拟数据并将其作为json返回。为了将其作为json返回,我们将使用json模块和Response模块。 + +```py +# 导入flask + +from flask import Flask, Response +import json + +app = Flask(__name__) + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + student_list = [ + { + 'name':'Asabeneh', + 'country':'Finland', + 'city':'Helsinki', + 'skills':['HTML', 'CSS','JavaScript','Python'] + }, + { + 'name':'David', + 'country':'UK', + 'city':'London', + 'skills':['Python','MongoDB'] + }, + { + 'name':'John', + 'country':'Sweden', + 'city':'Stockholm', + 'skills':['Java','C#'] + } + ] + return Response(json.dumps(student_list), mimetype='application/json') + + +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +当你在浏览器上请求http://localhost:5000/api/v1.0/students URL时,你将获得以下内容: + +![在浏览器上的GET](../images/get_on_browser.png) + +当你在Postman上请求http://localhost:5000/api/v1.0/students URL时,你将获得以下内容: + +![在Postman上的GET](../images/get_on_postman.png) + +我们不再显示虚拟数据,而是将Flask应用程序与MongoDB连接,并从MongoDB数据库获取数据。 + +```py +# 导入flask + +from flask import Flask, Response +import json +import pymongo + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') + + +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +通过连接Flask,我们可以从thirty_days_of_python数据库中获取学生集合数据。 + +```sh +[ + { + "_id": { + "$oid": "5df68a21f106fe2d315bbc8b" + }, + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "age": 38 + }, + { + "_id": { + "$oid": "5df68a23f106fe2d315bbc8c" + }, + "name": "David", + "country": "UK", + "city": "London", + "age": 34 + }, + { + "_id": { + "$oid": "5df68a23f106fe2d315bbc8e" + }, + "name": "Sami", + "country": "Finland", + "city": "Helsinki", + "age": 25 + } +] +``` + +### 通过ID获取文档 + +我们可以使用ID访问单个文档,让我们使用ID访问Asabeneh。 +http://localhost:5000/api/v1.0/students/5df68a21f106fe2d315bbc8b + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') + +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +```sh +[ + { + "_id": { + "$oid": "5df68a21f106fe2d315bbc8b" + }, + "name": "Asabeneh", + "country": "Finland", + "city": "Helsinki", + "age": 38 + } +] +``` + +### 使用POST创建数据 + +我们使用POST请求方法创建数据 + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo +from datetime import datetime + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students', methods = ['POST']) +def create_student (): + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.insert_one(student) + return ; +def update_student (id): +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +### 使用PUT更新 + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo +from datetime import datetime + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students', methods = ['POST']) +def create_student (): + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.insert_one(student) + return +@app.route('/api/v1.0/students/', methods = ['PUT']) # 这个装饰器创建主页路由 +def update_student (id): + query = {"_id":ObjectId(id)} + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.update_one(query, student) + # return Response(dumps({"result":"a new student has been created"}), mimetype='application/json') + return +def update_student (id): +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +### 使用Delete删除文档 + +```py +# 导入flask + +from flask import Flask, Response +import json +from bson.objectid import ObjectId +import json +from bson.json_util import dumps +import pymongo +from datetime import datetime + + +app = Flask(__name__) + +# +MONGODB_URI='mongodb+srv://asabeneh:your_password@30daysofpython-twxkr.mongodb.net/test?retryWrites=true&w=majority' +client = pymongo.MongoClient(MONGODB_URI) +db = client['thirty_days_of_python'] # 访问数据库 + +@app.route('/api/v1.0/students', methods = ['GET']) +def students (): + + return Response(json.dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students/', methods = ['GET']) +def single_student (id): + student = db.students.find({'_id':ObjectId(id)}) + return Response(dumps(student), mimetype='application/json') +@app.route('/api/v1.0/students', methods = ['POST']) +def create_student (): + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.insert_one(student) + return +@app.route('/api/v1.0/students/', methods = ['PUT']) # 这个装饰器创建主页路由 +def update_student (id): + query = {"_id":ObjectId(id)} + name = request.form['name'] + country = request.form['country'] + city = request.form['city'] + skills = request.form['skills'].split(', ') + bio = request.form['bio'] + birthyear = request.form['birthyear'] + created_at = datetime.now() + student = { + 'name': name, + 'country': country, + 'city': city, + 'birthyear': birthyear, + 'skills': skills, + 'bio': bio, + 'created_at': created_at + + } + db.students.update_one(query, student) + # return Response(dumps({"result":"a new student has been created"}), mimetype='application/json') + return ; +@app.route('/api/v1.0/students/', methods = ['DELETE']) +def delete_student (id): + db.students.delete_one({"_id":ObjectId(id)}) + return +if __name__ == '__main__': + # 部署时使用 + # 使其在生产和开发环境中都能工作 + port = int(os.environ.get("PORT", 5000)) + app.run(debug=True, host='0.0.0.0', port=port) +``` + +## 💻 练习:第29天 + +1. 实现上述示例并开发[这个](https://thirtydayofpython-api.herokuapp.com/) + +🎉 恭喜!🎉 + +[<< 第 28 天](./28_API_cn.md) | [第 30 天 >>](./30_conclusions_cn.md) \ No newline at end of file diff --git a/Chinese/30_conclusions_cn.md b/Chinese/30_conclusions_cn.md index dbec8a5ba..833c5e111 100644 --- a/Chinese/30_conclusions_cn.md +++ b/Chinese/30_conclusions_cn.md @@ -1,22 +1,22 @@ -# 30天Python编程挑战:第30天 - 总结 - -- [第30天](#第30天) - - [总结](#总结) - - [感言](#感言) - -# 第30天 - -## 总结 - -在准备这些材料的过程中,我学到了很多,你们也激励我做得更多。恭喜你达到这个水平。如果你完成了所有的练习和项目,现在你有能力走向数据分析、数据科学、机器学习或网络开发的道路。[支持作者提供更多教育材料](https://www.paypal.com/paypalme/asabeneh)。 - -## 感言 - -现在是时候表达你对作者和30天Python挑战的想法了。你可以在这个[链接](https://www.asabeneh.com/testimonials)上留下你的感言。 - -提供反馈: -http://thirtydayofpython-api.herokuapp.com/feedback - -🎉 恭喜!🎉 - -[<< 第29天](./29_Day_Building_API/29_building_API_cn.md) \ No newline at end of file +# 30天Python编程挑战:第30天 - 总结 + +- [第30天](#第30天) + - [总结](#总结) + - [感言](#感言) + +# 第30天 + +## 总结 + +在准备这些材料的过程中,我学到了很多,你们也激励我做得更多。恭喜你达到这个水平。如果你完成了所有的练习和项目,现在你有能力走向数据分析、数据科学、机器学习或网络开发的道路。[支持作者提供更多教育材料](https://www.paypal.com/paypalme/asabeneh)。 + +## 感言 + +现在是时候表达你对作者和30天Python挑战的想法了。你可以在这个[链接](https://www.asabeneh.com/testimonials)上留下你的感言。 + +提供反馈: +http://thirtydayofpython-api.herokuapp.com/feedback + +🎉 恭喜!🎉 + +[<< 第 29 天](./29_building_API_cn.md) \ No newline at end of file diff --git a/Chinese/README.md b/Chinese/README.md index 76747b167..dc5762f98 100644 --- a/Chinese/README.md +++ b/Chinese/README.md @@ -9,29 +9,29 @@ | 05 | [列表](./05_lists.md) | | 06 | [元组](./06_tuples.md) | | 07 | [集合](./07_sets.md) | -| 08 | [字典](./08_Day_Dictionaries/08_dictionaries.md) | -| 09 | [条件](./09_Day_Conditionals/09_conditionals.md) | -| 10 | [循环](./10_Day_Loops/10_loops.md) | -| 11 | [函数](./11_Day_Functions/11_functions.md) | -| 12 | [模块](./12_Day_Modules/12_modules.md) | -| 13 | [列表解析](./13_Day_List_comprehension/13_list_comprehension.md) | -| 14 | [高阶函数](./14_Day_Higher_order_functions/14_higher_order_functions.md) | -| 15 | [类型错误](./15_Day_Python_type_errors/15_python_type_errors.md) | -| 16 | [Python 日期时间](./16_Day_Python_date_time/16_python_datetime.md) | -| 17 | [异常处理](./17_Day_Exception_handling/17_exception_handling.md) | -| 18 | [正则表达式](./18_Day_Regular_expressions/18_regular_expressions.md) | -| 19 | [文件处理](./19_Day_File_handling/19_file_handling.md) | -| 20 | [包管理器](./20_Day_Python_package_manager/20_python_package_manager.md) | -| 21 | [类和对象](./21_Day_Classes_and_objects/21_classes_and_objects.md) | -| 22 | [网页抓取](./22_Day_Web_scraping/22_web_scraping.md) | -| 23 | [虚拟环境](./23_Day_Virtual_environment/23_virtual_environment.md) | -| 24 | [统计](./24_Day_Statistics/24_statistics.md) | -| 25 | [Pandas](./25_Day_Pandas/25_pandas.md) | -| 26 | [Python 网页](./26_Day_Python_web/26_python_web.md) | -| 27 | [Python 与 MongoDB](./27_Day_Python_with_mongodb/27_python_with_mongodb.md) | -| 28 | [API](./28_Day_API/28_API.md) | -| 29 | [构建 API](./29_Day_Building_API/29_building_API.md) | -| 30 | [结论](./30_Day_Conclusions/30_conclusions.md) | +| 08 | [字典](./08_dictionaries.md) | +| 09 | [条件](./09_conditionals.md) | +| 10 | [循环](./10_loops.md) | +| 11 | [函数](./11_functions.md) | +| 12 | [模块](./12_modules.md) | +| 13 | [列表解析](./13_list_comprehension.md) | +| 14 | [高阶函数](./14_higher_order_functions.md) | +| 15 | [类型错误](./15_python_type_errors_cn.md) | +| 16 | [Python 日期时间](./16_python_datetime_cn.md) | +| 17 | [异常处理](./17_exception_handling_cn.md) | +| 18 | [正则表达式](./18_regular_expressions_cn.md) | +| 19 | [文件处理](./19_file_handling_cn.md) | +| 20 | [包管理器](./20_python_package_manager_cn.md) | +| 21 | [类和对象](./21_classes_and_objects_cn.md) | +| 22 | [网页抓取](./22_web_scraping_cn.md) | +| 23 | [虚拟环境](./23_virtual_environment_cn.md) | +| 24 | [统计](./24_statistics_cn.md) | +| 25 | [Pandas](./25_pandas_cn.md) | +| 26 | [Python 网页](./26_python_web_cn.md) | +| 27 | [Python 与 MongoDB](./27_python_with_mongodb_cn.md) | +| 28 | [API](./28_API_cn.md) | +| 29 | [构建 API](./29_building_API_cn.md) | +| 30 | [结论](./30_conclusions_cn.md) | 🧡🧡🧡 快乐编码 🧡🧡🧡 @@ -56,7 +56,7 @@ -[第 2 天 >>](./02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) +[第 2 天 >>](./02_variables_builtin_functions.md) ![30DaysOfPython](.././images/30DaysOfPython_banner3@2x.png) From 70748a0042bf1c66604401604490a4e4fb2dc077 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Mon, 3 Nov 2025 10:27:12 +0200 Subject: [PATCH 62/63] sponsorship text has been modified --- readme.md | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/readme.md b/readme.md index 2d75f551b..92af49713 100644 --- a/readme.md +++ b/readme.md @@ -44,7 +44,7 @@

Current Sponsor


- + @@ -56,8 +56,17 @@ -

Dictation that understands code

-

Ship 4x faster with developer-first dictation that works in every app.

+

+ + Talk to code, stay in the Flow. + +

+ +

+ + Flow is built for devs who live in their tools. Speak and give more context, get better results. + +

--- From 1a207e6aa2186a06f833b809fb2ca8f40791e685 Mon Sep 17 00:00:00 2001 From: Asabeneh Date: Sun, 16 Nov 2025 20:15:27 +0200 Subject: [PATCH 63/63] Petrosky logo added in the sponsors list --- images/petrosky-logo-black.png | Bin 0 -> 22680 bytes images/petrosky-logo-white.png | Bin 0 -> 22470 bytes readme.md | 28 +++++++++++++++++++++++++++- 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 images/petrosky-logo-black.png create mode 100644 images/petrosky-logo-white.png diff --git a/images/petrosky-logo-black.png b/images/petrosky-logo-black.png new file mode 100644 index 0000000000000000000000000000000000000000..9716cf77712a843ced87e9a544cb3a35745ea176 GIT binary patch literal 22680 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
v)_5#o{8F^&2 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 mxad(0gclT1PIKkaLxXaD& z{ja<3xBKPZvnDoYj?S59p1t=o3H>H7`5KE13jhGTmih`&0svkFBEMf?z61bJYJbk2 zB7eO4@m13i0Kmro-wS18$>#w8paw`m#8lkUkCrT4$orbWC%#K@h@^<4KUK7(5p-EP z;ec9yKjy{>EY$MOO)Ru>(K9T}3ekU9P;1e*$>918|6i=`@p6l=H{C^?{H+6oRGihF z)qg&(@bT7TW;gpuxWbibL?I9eAUi_uav}83Q(fqah{nwTE>Vm(zON7;`k1uWaT$iG z2;hwE5z?9>weJ{%zP!BLdN$wC;O@Yj_!RV!FbGRV?* zA@~~{BI;2wu3q|mQ8FF)&v7?1^eM${g%wj&7YTRtB@6rVhtHl(eZS`hU!^j`>MvHP zP~6I&g^NM#d-`Vw#kUo^kM)CYqj-o0*SO_G*YHpw-~4!w*0V)YzfdJhvrBI}iydIh zYk(ObSh|?`7ToWt&&chRkj1hW+V+t*6nrsI<8BktD<$YFT!Ay#9K;BlvP>QF?OR^K z_>t_46W5yNm6+dAu}x1KdCpAL&qQEXOJrM1^z`C`U=&+M{Ncxs9$selCi>i3w|Iab zfYmv7Vyt)(Mue20zh)nUvMu|wNC~Kx$p_Ux|KsV_V3M~?R_WG?NTY{1EItcX>eZPM z@us!IOCCZ=s~e-K9yS1{1+fAOOAz55K9@41E&M||1105|f8a?Yg{TJ1r<<@g3=P0+ z|IjS#!{XFtW=}06Fhzgae9QUV+$1 zl&9Z&RnguKUzU~aTNcxrTjdM93E9I|#rZ+o%Fi4Znm?MTGSKWnYq~_%F-?EwvU5g~ zc0oC$U3x&K{VrZf5^z?YFSD-hGHq3z+2KLEe9W+TT=Y+RP@SMlJuX~-ZvR}$*U_!5 z2qy~nbj9S{?Bv0H3j+BYj95{SW#}>(S2N4l3%yC#&XqH^_VpN z5C|HYaY;~$%bzJ|6+X9<>Knom@GHgJ2(MbTH6w5pzbA3;qM>T4uRqH)?#DhTsO!2P zJtymi#t&b}o6KbGuGhuOK%&&2YEv%n4w<(%#jp0Q{ zTNTM%p}S64FHPGJP4@;%Pq_Z%s=j-)=F5X%9P_9$EViPv7Moqzx$L`4@pxrGr(|R3 z?XM@43pDDPtbqr#_Lj1fyfnU$0@>hwlQxo*YnuLhl*ECS$W4M|C*}ve6}HL7wDOmL zos0}sZ=gvs&i6CgCLCGHxr{5`PR|9bibA2*%)wiR`Wa=;jI)AxvNFN5;19SL233-b zqe)NrH4^2$eLm&es?VMczo~R>l;PGAF|gMhVMCt7`{x!kb04GZg%xr;i&{|d2Rjpt zZ9qH`B8DHdF*@BYn>LwGS}Y_L6c-dqL)i)|#Vdx>29NUp{Ui6G26>i8SAkB4;I08a z{>HuM0#hPUrJCIv`67Bxm#yiUp!TPK7%wL$)e382x1A4IvizD=9jx(6X;Kw+r0+8> z(+4~q<_SM87jUy ze+t`Vx4m?4;&&R`3^`+2vkPrdFt|i}!if8)mRvy}P(e@5jA*+1dgmDoX9pc&zta8O z?ukC}HNCD@*7wpbNn!O!9_-4Wx{9OUTmH8eD||s(7X0)+)u)@wGB+uCQ8(5q$CV$; z)j@vKp*dyXRjaZsPh8lr?$^6-Z0o`cRHEYx*Jr$Z^!DJ5CYe};RTASak_}^_*EW-u zWLgghSAjveN^Rp-2!4!Y)pNA(nBhZRy?(9F&?MZ+W@t0l6`e@Cf{wi`KJhIefKr$W z``DGFaYe43Eas$PYX#Ag0fWdhR0$f-FYUEj|H3Ph&9pdTwrGag?u9qou&6In02h)q_NJCwQ%^G!vLXwQ5(JGF z&791A`5ACd_k|$K@Zp+J!v!IiJ#U9&|=C3#jU1)Qj1H1_kHu|y=Pd+a0TA_d& zAD7ep>&3rebgnb;RAU5y7fJ4#lK3|M)6#BCj@HdS2u?OS8l3PE1?(6T=cyjm#^w}n zFV&pZ4P8Bda{}-@Or57cZ>Nw}o7Tz}GG$h7SR^BR_!ICG|gQggP#g+_ZWt&bhq6 zkxvNIzx9VijNi8SwcBA~Zha@~$22AbazCBoY?&~|!a-%NW~K4_2OC@X5tCz72MGEPh zY|P|o`yClczv(8A!dd<(UT`zQys_0~nz(?Py6Xm&^PRcQAJ5{O<7|MWJ3AB7cA}PL zJ2<4ep0TYrYNk&$?A=?jt|fDgt%S>%4f7-^Sqfl)b#|T7yveIg5X-m$N7& z+#bg(Mc14qcmq>={n}(ow(I7x{B*5N9nx9bn!n9sd2?$r7Gp&wsY)NI%w?IJ(8xEZ zX;-|@6O#NqP<7TOgl^EvdwAAT4ILdx!qBWrt3{oZ7N$zeOv_!8oFg%e$?63svBjF* zIMO@UwSVqAy;mN-&xyn*ehfXJf2?}-?ys}bcvw_%M_lb+*6{hy^JkeMAcy2638gxx z%h_h>b|#DBapr3FZjpnDor7-JC}n%5&f=PFVQB(Mzj%=mGc(Dj&)uoQ2UAr#7_g~w zs8>Klox|(ND$6;&s_5A;n>+79>Ef-k=-blg@wKIhole6^JmX-dT~iqFcqcZ=?O$z zEI5t4LYD*`uy}+6d^UR4ZH#Y)5)H-&UhlW;D(P4R&(QO7Jwcx__u2Tu5u18RdSTqfSaA1b&~@7m)>ZMc7R9)I_>H_;tuT||r+kEXfEN+vR+ z>dS#2>u?(__t_nAluh`D&zrdiop`kyCpHn(!;Xx)v@bry&yuc~>?620ge)Qjn-Frw zV3!NaO9Ww7mwHkocMDb+9jK`CprT_GTw8scUwffwb-zhZs7w;`2aGzqHpk zQ`Dre&DO6T_3&}=wZ!pKrtN1ZqNl==6Do?*R#S&33Pri^;uBVbDly^Djb`i0Hmfru{IQ~DMUmXSV4_WFBcj>_Bv>(^DKi?jG z@IKW)9+Qb5uw|P3y&`|-(Qget}4<$Kwut zw6wC5k4^duj%$y4PD=>qx6t>@<^Hbz&YLSPSHMS4usr`(kaG#l)s?21W3m;R`lq$_ z)@1s{51n<5FReA+oG)&ZG_e`);bpU30tXqmN2f;%&x!$1Q@{(GTG@Q!xuRxPp zD7l{&b6uZ->>M`VTX=2MJRj0s`g!i_E#ip=>o}n@RX~Y2DYT)w2W-P`DHwasA>Y|e zp83OoF{Nz9f0#^(1kB;X4?n&1o3l7ZQIRIz7X4nhhT9n%(M#sbax=?T8b&2PY25vB zC1c}u&N7hm%B;DP7& zA5guxZPwr_-!4!iCh%HQanm5Xd?E+XF#(13S$W%JV(aM1_Fq2P z;51LT{Hkj*uWA`{oxG50b+@I9*I3~zQ^U2d$#AbZ(Z%17Q!PrZPkp0Ln3NCC=8F zKYHMmFMk)k0W(a$>XK#zXW@=nzA1Gu^kCtl@fsUBbaU0cxriOBok~$aKc5x zZw}sZ&-1BN1>tXUw0&aAyJTOh!@8x3S0ZYK#<6uSwPJtRx(Q)as8f43i1qm^&fpR~ z8M^8eo7iN1yB9rXiQJg;T2;)zh`z#jex~HB$p8eic*B!N5(&u;5V#?H5J5J`foNmA zJxHTm2t3dv^!DZ?K4>?`d%P#zZez=-S_{Lfw%Vv*BOr*;Teea%nrux|?>o6EUa647 zF7L9B_`NPQf$<~h-XeW1?bXRn)ST|fw#JiBH3r`(`_$#z{H60>%l%h!(#7YNt$pOG zCA;L}o8K6T>{Pg#89zvMU_LJ@-gqb-_edi2S6%2^$Z7n-zcF&3#5rupep|;#Fi_z^ zfyH8we9*z1hCt4wOXD}L*UZs0U7Rmm3RM7QHme7rs|N$w-}xisRp1|0l@p(jKXSsR z`b|8T?}#hp-nlT+V&u^Gj`QrWi_o<$k*>K&igB>d`Cg;x!{SSMSTk=chD+4cq#<|C zJ6#ezmS{9RGf3>R6!EtG5N(a#WZ8O|!?Ca?NZ?&dj-^yIJADAVI-7(#$y!EKcg9Hn z4VP-3M))b&86+E8HkAdyTN2%W2}UdZ(-b)+@ZE4!iDgdjHmJY?S#dp(~wl= zAag5zGBo0aHKR}xIPl*G1PEWBugv()ebVQUw)w4&)FFDMkm)H~SW8BJj-^X9Y`x;$ zURrnS$H)E&A!b#BB`(p4-59`Jd<+h^V>_Savj-b71<-Ev6YZXwu)TX z`&^Wp5(MMYu%Ro^hm+Wgv%P<}Z3J-5Z~AUmGh<&|&$A-$N5zJ5SxWU)+|%0wV(Z=~ z9{IbNITuLFv7;=rp_<4~=*0!6+*#UXs+zy>RP{kLUDWphrc>3k*||iiX3c*j9(P8I z;g7x-TZ@R_GS89v+3hURL=3PgF5m#!kpr28VG?VZw&>6!P61MCm)Ip`=CQz^5rVeHfL@RVzMXp@|2A}iAxqRTQ1Z>pP=CJRT z?C;;RvslKr#*T@1*qr)wZ=rK@H@;nHy)i%HU8r6d?&b83sc#u3o`16=A0-BPNym=M z>Ha>s^~YSX0+Pb~e@&ZRa|4_s@@QuCumc-HpGr+8WWNc~M9|mRYbejIugbe|m**&9!uLa^Z&oWW6qo04^C}Xc&{Cq6_X4tx ztu+}!=G#egjDCrec~2h?Oo$ti#aTqqbKIo3huNMgg=D?2cIIdRNH<5_5i#-L zX}@a6Sm~7<6f?vPoP+mZ?}C%Pv*so)yFVh@Q)>j=PgJthGcy(3hi9OK?FJM-bT%4M z_WB@nVT1@0e~Zszvwd%B+INfz?E^(@Y7*6#i=mb7A+5zt+6Hh9vk-J6(bS1gWMQli z7M_`Rhi_`W03K)ciSLB4JLW8rXM;F+Gd9n34Cv?k=jl-$@Gf~6EYD^3{%s;1B+!{` zt?lUIDGgzk#9mvHCE)RNKXS^In5jnjnVw42+%30BaVX zpzjbQ3XEiX<$B`d8Gm*!OTg@t-0o}ie6BH8H7!&^b0fi64(fPggP0o~#6yR6uDf;0p-LVzfS(l5HI8e6u@ zQPEWT^O|E-Y{U4$@-9#qA$$xUksQ=|C@+f>-V4d+M!N>2$}E9L;X(DUzD*w3uSCs3=VNcr~P`9rHqdy zS63y--t}6iIG4Ki@rVf)zvbMZS^t^9EOiC664KH25$PbN+}dinbaYj3H_nZ;C+o@e zLHWDBj5VpmKz);D(xEE$nI1#owo7*`a@feVpoS50i7UhOz?v;{J`rg)LC7tDl-1z+A=y2M8i2`< zN8R7&I$7|EtMJxp4h{01kECQ`FbvW?D-QecPAriPP5iqi@1=~{;K(e9sZuN7AY;Ul z4CrpFiFsVoFZd*xhN%mYu9(lu8%ykxp%+I2W{JQR`M6X|9{Un+AmxhnD6oR|Lq{PL z-8SK^7rw(6+w)5nJx`Nw{^hUhStj~z=4-7-7R>LUYD*mxj=$t%rZc9VK;Cfz!Qxb{ z?I~$2e}15~wAy|rB>V!%;<2Yz_qRoh8!yxDr=rD%guk+mw+3+!dZqxIw%88s3R#oA zNo6n^;gtEp_Y)q!hJ}UATT-GE@XdoS36OTsacbMT9FH+m5 zw_8|G$-!+;GMAFXEo*H~O6DvlV)AI$XVM+IPo7~8=P6#KYd?`Du9@)NSWZGS9!on_ z9=TT$x?!mC9E1o%x>zh`W7jyv_SX^2XnnR_X|TCkub#U0NT$M|GxCxUKYT@J5BR$m ztGg-bvoRH`vj|rgpl8TDB=!?p){Yb0w*SEpP0{+JMR_o%-L}ge*~J+){0# zTrDzx6Y4&q8^UQ!y(70T_@tdwxqq7c6YTY3N>)HGjN2C|6JHe6vT=UG16 z+L)YyaBJa~D09cA{lAQAc+JgCg)0}}AN(=1c_YOnJQ7Jyb#T(D*l^R?DUx-Lt=nkU z34US>mZ+H;wp_obUqJfiEkGdnNSW-OCEj=DsA0Ee#^2$)aMl(r<)bTzl}0 z9OpRKQBfe42c451&w`(qiv)TCiit6WiO>{-g`uokK?+-D(Ra{^CF?=4szG+|6 z7MA$5)g6)}E_?;auNY((Y-b<;iqN@p>j^BBO@(CWBev+KR*qTlsNC=1n|SaF9^g!m zdYs!h(ml;+8W+&S3*H87dn?nxJ3~iaJNWrwcmEn`W5c-*W=FX9fA+GO)(tmRrVp23 zfW@zIzNx|&(~iJ@H@m}Fh~@+ z%EoZ~lwl%v4%WYAkhu=M)hhCKk7(~53So;b(>8BVdk!v&UWVrRe93EXal0`0ke!js zm3g|uL^y5l1g&R81sJHDr)ET-Y(XyaoM}7Oa1u3j?v{_8g6Z_HQ^`o%%ju)8p9x~P zW-NHp_b67>=3b=mR9K`8yMwB$J~B1tJ@1vs?2KImmA~}-bH^~5xe};LU|sCf6Hhn# z;nX-8=hta{p|SH%lVcZ`9}RiPje2)lhvBMXvtl{mWc8t?X+iT~*u#dQB`9w6k1f|U z1XQgv>;58h$D11|V6I%$HD@!bgpMJbpc7PK%!^J!r=IBJNGJJa)LtXTq-$S&TlQ~= zaxyrKIK7hb>(!tNu`CT3NScgGR?T2gcDoR~w-QI0o4~)_IMcK!>rufa)@paU68EcK z^mjLEC-Jd!`VqXYoaK%Juo?;#^xvX%iLEKF5cb*A{g*a!rjx#xbe#ODEbK8g`#c{i z9d@KVCw;3U33!Ss37URJtqj$wsJ!)V&W$Gv>&M(a_>y!4_KJ9jbjnKpuvsGIG@u}M z)7uyl4hL)97*RaO9BueqJ8%uP$zM-+9?UK+tM@+ZNv?&T(g3g*5m65m-`n=cD^Ks@ zzIIe4R7G%5lFOs-b)N*MC#kQ1QOMCpdaFXR`JEr-iOS-Qlnu<>(XJgCBEjBQV&dWP z+TJ2}b<lzs)V{2pUS1-#8ADfwI&m3BP?UU9GyS6w)3ZlbES)y ze%bo4sd}+(i$}xQDp<87)&D34t;8jux_c;9u2kL#`x7}!-Y{Z@zu|G0|HupezheQS zM*rqg6*5~K^S$HPU>lv=izQ)tX-ls%YF~x>TiPn11~{~%CI3^CkHk@O0M~ece@{Vq z980o&w3i~uS45Tl&<57YH#FbMd-RroP`jb-2a07$RDq&0>jU$2!*0tj&GXMJf5?iN znP8*h;1%Z!<2eP+2?VKXOargCtl7@{BgYxWvayNtKU$5+5MfEey-241X(IO>P~ytg zi!pbJ+RM0^T_vy>t`{YZ3k%|fYrK-~f@0m^@W@+ue;*+1dJ?~)77=H z{de^2v1)B|e}0DKkRWyOleW~c}W5wI8)@mxyMK{2%HO(v5h;z^&ivWNed5%#K(IwGyrE$~ov z=*^frZxI6+2}ropT6f_Y=%D{UlJpOkiLSZOUCEB)Lp)Gsp7tiJNr zK+oP531Q@d)bTPiC|>MtwOU3EV`vj?21B9KI=ue_Hr{}cM1)81ipcEsFLETXq1$K2 z^cAo`;bl!3#PxYLP!Z;WK%ADQwDF!?9I&#tIC|wCp1QgXJs^FKY4w2ub$ZKyD5Okg$W9e;x&ij*50QAdsnVaKgZjOltsd$)-lhvd6bW zt|t$RyT7P*LbFbZ^dJyc@N>a9n7$A%UCd95(oX(w;;qo%Gy;DEn#7Tp%juZQ=_*9S z_&`PR2ckeb`Il}RFsiY{xzm;O!@Y;Ak9wD1NuZBsb0API-i-yBHy2k5p?-o~Yg>kJ z?8R_t(E218sd-!4G9Ru>Ysv`hIh{{ zp6~3k91?SBe)6UXe5s8bl=LJ`H{a8*$u~FW|1Lk;A}3BFby2c0K@;;y&@(K{?7i#? zb#7;9e=t-q!6-^Re}`A(uMXvPv!&7GF56S%{}5cE=9^B=G%@xmuPRx8n}|WRP9DC4`E99QDo#LAhVLR);=@5AHoPP6QIew#L?R@ zVq+%71Cn5y6WTL@tY5#<;F64dD!NDM>5TLX--Gt2D226n{BlL94Z9HE1o|Qjv3#d? zqiYJQo>w}fYq$bcFxy*@aT)gHAfpBW%orE|s|)t}U4oLqLoMqw-XEDz0=oTo21LXEh<+<3-hki-HIQsI?9>&9aGg7b^3BqRPs;9x4 zOpg6<*efES?!?(@-Eh*p4a?<~#_%Ka*hO=3{NOu-zJhVfD(ZiUx_;gwH7RlN`q>^z zed4qrPeA5&`^m?HTebJbVj5Yf=je|2M-EYD)uc^|?~5jp``!}=4&a{XNyKem!wT#u zkVv)H|#OD&T z@(H`!(tc_;XgK}z$=e~J*Sdm!Ut0esB53Og%kd6g@o5pnWI_a9QB<%@`4&9$;Kd~N zZM^9uG6tk)g^TI#bO#Q7{#IBR`;^t)3&or5x<69fuc;_RvJ8SdhEdlGbN5V%-&~I- zu1}rgrW^^WhSkmOH-B%N6?oGV_favzJ~Dr3K5735s$RY2MH_4I&Z@77_fR`&I~DxI zpZlBXx!tG7d08@yVnG42%Vc?W?-qQ$z*L9l#eK92SE2S`Rqlu;){{f8D5(D_GaaRI zctAH!=@3w)|M$lG6|Qr{nxq}2*glr+4J?7u!fg9UC^;OB@+lmAx zkoQon)mDi`?b$X5w&S8X^P)MTuzekVf#dR1P-kuu-KZki7#s$XscF(Hx76gQr6?q) z&^6#=w1#Xp$&Z>io}B4iP!vd|Qf^r~wg)Gc(aAG^#E(SfQ7q!_vWx31DTa%NVp*?C z2(*c;!l%AtIwe$}TNNFff`+z}7Q1MOxTS=ZrD5uczlTE33lx(&Lc-dAE*31QIzMj@ zou&9L;n+?tISQw0vlPI1DgBSjGzm|HG`1x?u{+g{hO;}3-=WiyFjW+gyKxf*s$!yc zlIqFLLGpW3KbKTCL=8K#b#!2jidTqoWpajYx9VZ@ch@tbk(@HhxhM1_7+C{OC~50KKq|WO^^!XO7)4Ql-toSAQmRCLq~{&^lF3HE1<< zG($RbA4T0t&R3#jMRdR>PlvlLjVGLpWTND^9sW&u>~Wxt-2>7+B7Vj5T&8-&n?*d=a(Ne;~CMeKb;WUiHL&c;1Jev_oJ+HIIT-Wwj1D zTp-W~>>Y?G_&K#>SMU0xri@y{EiAjf6iW*IvuT_Q%^{!tlT0Rx0r7bs1wid*`TO3TT zeX=Q*I-pq`)ByfP!|ryZ#QL0uxEk#4OC0{8hD{&7rBy^M_f07Ix|dMTs4Ogi_bH{< z+Hj9|BM8gsIcu2Gn=UWh+ogvE;1y65@X0l!vBXM^C5bn1jaZR?g3HpR$f(rYU@yCSLvoXSWD3S04&2cp3Ph)AVg}2vxHm+6mAxOh{`#RbksA9E*=uL*)1v~g8>wsC=ZN^!1`0UR5(8;qD#wYY^)Urs zf_#%q+7YN_oI&*>=SzZGs-G|knK74^RnT>7KjyaF*1pLON(@2$5sGejB(3*vdiX~P zOFK;*k(mc(1$C`n25hw|0*hX>8Q%;zrfU=O$R z?YYI>>k2rf2P>Lk$_hW_0lP(Q(&=h(bx<};qWrT`HQu3iYwJn=cJk*(DNUyjIx}Sb z3V&9N07Of()A3W&O(nG4L)?Ol`(Y!3R!g1$Ny7im{KZVC*mc*cs zq~4|NVZV#ae)w|{WK_k_pk$e!7sA9WFY|6CDCdbS;(q(x>j*9z%Z7|3i{{MYIB8`D z^fje7=f$f|6BQRlAX`dNlCmp6*%fA4y+iWxyu&vdXA>ms7bHvY@*NeUjL_sEA}5)s zx@c*}tK^Hqes|jPJ0(yc`+Zl3Wrd~>;~!j;_B0jV02>5Kkb+@KCi5h4 zab!es7yUh;*2!u2?2n=lF?9RB>P(GW*Wj|j_VEI`t5o~i>8-bg9;Qh=FOq()RKEXk zzB}GEL(nx7=YP2aHJ)SuChS-f8YfVU*nNtez|Rv74}+P zm1)1LR9!gHLWvhexZQ0g%t(4zXS~u84&H$c0{4Kc)5}f5W694%_7N5I*o()3AEnZm zI=6LlWq1;luz^*Kms6WkdhaqdBd~tMO}`1P_6MGuDt2xOb_-;nA3G6tThJr+P&xAp zv_XS8X|uAAJ<82;P8M(epvoPy9VZl^!!2{H2;2CzhOV%#3HA|A!Ofx<^&fx23Y$f( z;TbWgi3#Bc=Eya_yI8rtfn<8EKB0?MO3fAu?+2G zH14!Dx8-*@k&UB;15#yBx)|HjKV)rkq)9aV*wMOno<9^__2ATR{^!OKo9B31wTCT7 zZ2oJ=6PQ_M_`NZWhvb{D2oHLH@K48GX3Vn*7A%#jKl4i?bbhReKF%6{_IHt+7iLt* zaA#M6^JXq3`XP6TX)9J!U`*uit7t3Kp=}0|N7=vHueQc_syfbgl&KO5n|-+43Dy%H zkIzji=<|-NwwOMGjGWrNxx-Oa%eXxnxcZi&K411MrhU)H?wnUoGY6^HJT^6Oj-BP6?ak@9?izGoUOI*f} zS~5_MT?oV+n65-U~IL;|_rzc75bXPFyyvcBss{mM{? zr?bC1EO}SZC(EaXVLB9^QQ|SE;J@K4eN~9ds<*)97C9r9e0eBrUs3b3h~T=pf@r?C z&1&gQ@_@_hKOf_MIV)>Uyne9oH?6H(NSbi4>5Bx7*P5X44}R^-$BPh{LeF)sDPLA9 zW*pwFPdMr(B7?!7mkDaHFgZKPx z;-Z{i>#zK)z7x+(yD|nmvCosuEiT>_+#l}=Yx?)zrCBgX`60QHyAu#Hu;5<~f zgwT6h)Q?!g$!lM*WYouuOtV8mXK8v1AKpD=CH#CMv^zBAKmoNonEk z9pkQ@4WIS~3Z^OCd_?1;Xp#j>cFSnA{{ zsW1EYHhNoE(UL#;Kn!fLPs;7F_KgHu_Qy=*kaDf3yqhelo5r)5PP@-8NBf85AzmIn zy(KS6aY?JHuWq4%>&QE;@|GMHA zLPV)R#DbQjI51`rjH6>ftI8t&(~{153zhqf_@|und8n2>@b3IJ6}OT>85pW8{rcjTB4IQ!=0(P}LE*%1 zf!4wU5h;Ue5x$biCsJw1+nE`3Bg6xH7VLs{q7D|XwM(9Mu-&KY{erw%`Wxe=><(Nr z^}V9>uuyt5xc17pBB;BZt! zxuS|=d+v@e@xh`LNpH4 zRN?=YMcnO!J!YyGx_^e8cO!(|$1%o?P`*N(Qo;i&kG*M11a4S3o6l@W7T$yqQN=-b z=NYu|rgbq-LZQ$1hTrP2kUKLgkvj*%l>ue(W+c0nui~N5MNG%*(2*Wi zfK=Q{3kzB(bk`%Lb=Tmm`*K(5{|{>O|4SVX5O{`v9g-VG9YY0J3%`XY6a1g*jBzl- zc?ISGCxoIR8>%z_3>>`w9-m=Q!NHWv$hZJd7|juwo1v@{AWQN71OAs38F4TtA6%+Y zR$mcbr5CckMVakGP|2nj%KaB!@*Rp|xM)W&1ob0>2~}t*9$dU-A*Ec1rI%>rXf3+U$c%UJ< zQXD)rb_2yP01UVAwvhiaRF*wnA~T%uhS3k<=>%EZNS|u@XWn4+!@+Gmc{CpS9JUTx zN%-LTm;VkADpe3gGO?7oIoWaubQU8LJ9kR8yApUkxg*4#>~;w6zg{N57yV9#rLYzK zCQ86G{%-gF3y!xEb}cCM3$_#hx8R03&#(Whjxg2~Jb)S$MI+3jf+en zQto_lGKIKiM$V|4r{^Z(?SE~5&*eigB*e*tXGC^J01nrWj@)xxC0F(wifrEH3cX!f z-lmNB??7&IdC{ApQjFEcW9umvtn6h*py*@uAv(motu)QeEbWW*e`kpa2{O1un-!-0(=>&#s)`gP}bZ04j#S#n}L`Y!>=%B6l#fjsIW%T?%k)wK9N-JaQqiUv;)ci zY5ry%*YEjnFB#gqWCigQYBCgb!1LI%2nvU~^sw$0oE}Kp*#q*DF5WKP5wi+MF?6N_ zT*+LbK79&TLsJzSMbA%#_BUT+j~YiOK|QAFr5V|fq_N5`s5M~s#SOEcWF{_wet&s` z!vlPV4R2}X8Fv+W?FM>A_L`^W_dQN0%9BPV$w{FmcISIFPn5JEmaE=$EYo(yazc*LGGHnzDHc*zEroN#=>>?rDw`UF0#fm&nutw zx|5AVJY*QQ$Vg%jH*erkH`_96)hupI8?K+SuKjA=S4bo=Hrktm5g9<@^)=U$vNVK` z_j_$?BJNof;BaH6ieC8SUex;=KvhU zG3dEDYjMq75W?TvXn|{Q7$emF+!+!-GCw@1vCg|}C>*}Zr#{;2ebua!5f4ojU8%{O z$%uXl#R%4J?IX~Ir~Ca%W%%E5=$g1Xnl9{+Gd z=?B_rLSN-;&tiRkcPULg{6;q?Uded}rO1hE>ouSc(3~0l1@c{-J@#zs+>jU`tSJ3j zhwgWSE9rZt!qGhKOF$kJ9zq0LqOv8yHo~bl1#vjgXg!K+iRo*eBBV z9S&blKyGbER>t~$%1~{wgmiI^lBEnrkuD^GSf9U{C=<0u^~GN5IiJ}Ne{;&qf&&AN za3#y~_<2<_zdi;ZU#k7@yj1D^pB+6g=fpJ%-}}92oyjEexW1kw&Lx&>6PGmEsYYLY zyP}Zv9HqwNT`~MQckSXAOm6htJTt8SS3=mTmyYX8=zg}ORIMPb?>7^?WN|w-Uo?&3 z1PUgYi}!Z8c?Nf3NaeBIWW|gzZWr6K74ze49qvngg?l$4p`L?c(H~e{c>v)V0?b^& zwoJ;6%UZL`6b9aA)D6cL%q#qt5J+bCQRT;6y4$our;r@9pC$21FP5y5i4WiHQi{F& z386*f1owYcaTh5UAh%+fmppw8X!ENmWNplP@h#zh#>>a^o2$g&SQ@?n$sk2H3&;UW zgms4irn2Su>T=mA`bX8x=b_X0NEYMl;YDYRlI1b)c*KVRh?r+0g5$1s+>b3Q-z8r2&zBQZ2%&w``afWjp59 zmE~IGS&##tSb9L!mAgucMNcRK)BssSmw6an#ZT#GZrodyT_=xO6@kt{bIz$RfP9lg zt;&!tYfSX>YJ4B27%sN*8f4r*4XE$#0V`M9uw&aA1pwKMfu`?!WxOwa*(c0ajtz_{ zKtorzVKwhfj z1fe4PYGnOH^t;8%!%GkDqc!*^tf*YnW`uB>*aG0>LJ-r3+dE2q5^2VAw}CNj8nh3u zx-kLg*3?=$W~3BX2P1eyG@y{X25|8G@<6wfUo#GB7EL;UW0cab#^i^FtLfla&ku{? zz04A>Mk>p;TAej#0D%8jih%Iny!lS%1OR}<;D7%M&^h#e2IauGZx3dvCW;9F&l9|x zWdNi>)uQsTX#l$K0JiHA3*|v{`{=Ehe!0^diTBn#(=@BC*C&J(1&>IZwx(78cYn|} zk2w+=(DOwX1-CgNk?jv^m(P-W=%kSK5TH)g(PdDJ=PKe7?}z?&=ET-z>t9Gd;+B#_ z>{C3Kg&`Fc%CI4{?Y!BrXp3XuMO&^1Z7K=g-z9VQA9+H&2o!=tQI1yz{e}tA=x7+s zZGOEzqAPN5-t+!6VD}q^2TEcGeDMMkdG!&=?0vS@h#H-q<-a6-8!U%>JOzKTC`!Yx zIqFM{05muu(;W*(l5zsg?{&0$LF(@EHP;RHP13zu!SQX;3o@#AV6g-t5BY*2&-wiQ z1mCoGc;(G=lxwCf;b}WB6Q8 zq~0XrTI*ap1@SmtG;Lfkkux>d>LDG(;VV?|!acva62N8Eu2Gx_7ht_VTJtmQ2+3iA zu=@3dU@aWFs^3Vu%``?cqXkEWRD6m7?{Ho^vt8KH6bY*47m~|*u;EWGv|nbGt%+;hhfe#*vEjVtpPqORg)-spsfdf5V>>Py2fjcU{Z1Zc z*%~=>b7xcsv;lcH#jttRUZ8S8-Zu{Avx?|+I^7x_VY8A)pIDG2gk_4-n>1_(+gF(l zIO=g5_Etl)%LM&8Q;ukXrAb`ukL&7r)5%3qVCj8QNWO2?>jHg_ z*qC-^{!IghEby-8}+i}5IYntod?KFm4zXQFah|CNX{=I$EZk(9i#uhGL z!29f0ONwZ~z>V9~x@99G*7669BOng%?&A!9NPT!6jbj zw9Fr1zQNtTHHC_?Z@?h53D$E)p|r^$$NI3>tP#hB_F z6~+}VsVbYCojDfmyfntgF3A>0;9C%krc_bX6Q@Rg>jl1eW%oOQ5st?X%zc<*Mitj$ zHx`3H#|r-XLFrnZ99hEky~O+-KDO7joBI%}!Y&}W^Pav#7g!uFv29@=^E}~MTh_EJ zRXHcX`i^Qjmxs9d@ld8Us`j+2{_;l=82bZG=K)~|<%9~&=h5mB6ap}%7 z7rFlFKl%=RtfZ$4R&2e@iS7(VcKwHwt%d$x0JS=^=80B6yO&bM!0*&*80BV#sI!ub0Pu}o z2kM8;{$vLia$c4uvKxg#0t#52AmEy@P1Ghl&a3i!|MNPrbK_-7vddbWBvvcGUr~4R zv{?*>D9vLr%0{8G4+P9AEqXnj8+?&Q*;S{&loYUPX-R%f0-L|0+JbJpSDXM#mzqms z;*+$J(#*5>!gOsz0fgZ@X(-4mRPAQPoQ5=t#mleo2cdTdLr={Z-Q$TCaN(TgE1gfy z4tEk|DxqYC6Nh@gjC?F9Th+7)@{HP*Y3=plL{r>b?3hBhxwl{$mdW9Y6t zy~iJsxkeDg%Sr#YJi?3NP7AWBdbP<$;19)13qp*>-Xd%23#f`ZpIY#3SQ;q*ai3<~ z;Y$Aq!m52KktW-nvKU1g-x>CAjGFaWO&<6}HoEjdq7w_Z;OcCELfN)fKwF**4-~mo znd%?gq0r$Vw4nmZP*K;;3}fM#iCJ|SLW&uSjWjJO=j;I?(Ms3*rFe}<2tT(c?Xd3_ zL9bl{gtZ1zay7>m`cljY%GHGOFxVtjq2xVv}bXRF??w_k1zk+tDd!-0wgBxDF03KL7H5AdB? z2doV&M%B6nH?R|4_7l|l-u{}kbwIrwreOO%FptDpLZHS6A6h;ULs$w zMKgfYVi{EJ`gXBh#zKDWfu2E7$7*q5W+7Tz;F-iy=_`86;gGfYuJ-pv#|HxCW6u&H zKY~g5?TH7ocZL_k@g6scu^^VNMs?n|g1V#+pTV7a&Du|F61y7oo3@XJuR0<)JZ)b1 zUUPJqFHBsmZFH{1T#zC@H9obhPd^v1Bu?#Yh+jTp%(sBWP)7mw6D5ffAB*d|e30tA z+~qZqk~O+!mFU^@>42OyNfC(7c(Q7%_a$ycK~_Ot!gm(yoCGTB-PflF}`GiXSuHH`5AQ^2B$qLR(X}TO&RC%Wp}Q(ype;j43NCvPRV(9U!ah zu8ntt@asYMZSpf`h1^o3kgo<)rAQ;D(HZ~7c!3-`+(tD=;o@_fGrUKwqwy{d5p`(I zG;T1I&M@3w&}xSk@75o!yS>fE5I4<%q`GhKX^=Pr83u%O^f)jL_oJ#8mbJwhfpNd^ z2}5ow*$q-%0*1xm0@rW9kfCjFlBY%ErwbN0Ku`){1Ke2&g<8_pB6uDr;+2gt?!`Zr zfZV?evQt<5xsIrhA2Kq0(?wT%e7q`Hq{k6G5!!v17gYoy;rL~1gz)G*4FW*5%Ghp& zdidk}OxfW)Jaoo|99m@QeczwwNmP@W?{~=yZRZ_X0KCMDC(Due0ahwwNUUgQUUXUF zufkVMVA7_}q{CJudlVy{g^0Xbv_Jr1&abZ`?{sv4@G6D{Ebx}+n2SQf0ZWpcK)W0C zZy)Dx;`Xmp&+-luw%qe>J8}eyKTc4^#p1CK#|j>?qwpJcL`cl$J0rs(pkufW@|G=H}534>imzyHAJz%Wpc#m2S`DDe$j9Da8^keMt&O$gUu9TRc(- zvd(mqXsHYkkR%ZkIK;M8zRUT1H|DT8k2Bo~tmVok#->!k5=4Q3c|~54A;uXjku#=u z9iDH(5#t)E#dj!3HXoSl-oFwHRAcy72iww9`xP0r=V<~RX^5AmHszMOFDJR~ zEerAbyrNAxY0anuCo>nP;j`W4r53R5NYulv3|~AlKg5FhgC;^_+FkT#Wn#-ravga5 z(YN%MSCX!Y({=`Y25*we0llD_7Hr%yz49+DZ2gWa!A)+HwR1Ae@0yzhXpQV^veF9* z(OIi$FN|#J1OD6+Tu{O3XQ_*3K0y}CznuelOr`DSs$M?a(hD~;n>RPShvbMF(D$?D zAZ>IQGX$w65mA<(aq8DY@US@{fv`8xMMLrCVvqYg(cE0&eXj?KHGGuJ?1`}^7DBRw zu^B9!=Ij2bt>AF0KRoEp;Qg<**9yr4rZuxi-2A_AXAf%$Ez{?|6-ZVUDdtDMjvnW6 zn_RaYFq6hAV@DHqwVz%AhCYO-$k@sRGS|dSz~V7F-5s76`+iON>@;Gs>J?6ApPDH& zx!q}dRmN6(f`s^jS`19DiWj2rQ}6eEN6I<=0(F;x9V9?v6~3TgRh8GfLyQow} z``^K8r|)QZ@)cin7y>H9+5J%jV1QV?1nh=a@L^wCOZ^~B-qiVC0a^p>=^(&@$Q9&Y zD@l&?$SLEXp23$RlXW_EX9f6uI(0XnZg0s7n*;M;v4qLZrw6G%VKoS&ykKZ%mM zng2jX)up5&_S?j|(MlH2V~4{z(A6#|&f-^L@%y>{T19^6SP3Gs+Cdq1i{GzEIAQ88 zkMTc@$44NV8h-v97wKHsVvoT$6hEucIvc03cRvL&mf6%T>$ri5-|~EY_n%uU+wD~) z13emjO0y0syHB?p8-7lVt4T^l&6+P(ceUN$LZvctTcND!O@99Ke+#YtF&OG$+NOk6 z#afbf^JEk1p$umE@feDa3^sR(pK1k0ntWyioj0Gi3QrM{C7ejcE{pT&Cf7Plha?-5 z|I9w~58u@e{D=}hLadx8D6=U?#sr8m!Ot11vicPdX*|1ZRvDk@&7>LM@yA%)%2I^a zwvmVTtzj0YA?E6wNmG|+^>xRofYcFIws3t&3OPDCwL;4JVqKAXtL+2~@D$a0{|4U; zPYi#HUDoiw+4Mobl+ATNv6f}t?Kss9o?}a?G&8xfv%NcOh=grz=Nii}9EMT?)kFep zxk#9annsGP%-iZZZrFHr^`Fs&S5SVm7od*!w8X9{QU$QCk;=|Tf6if9X4Z3yiX#dn zvlMu4KS6<@{slW6_ou!bIa8F|1$X_`5{u4j?{*6X7>z$sWL0PQH5XF4-}268Lods^ zpK;oDY$m(+p|Tbax}MQw0#?@jjzzO;c;g6hQNMuXe8f=GIvtKMR5&ypQt(p_s*R`C z#fRzo zyfJE6ZqIi4+JpSHj9w$XB<*_9q@_xFrwND_C*~_Sc-NFaFxWZtVM8ORez9@sn=QrSVpgEK@H$~oa!rDYI2#Fg$MwVj?*-Z=q~i}{w=EBFYl8?Imp$8^ zF?F(DZT*+5T!OeN*H0ampmq{8dD!1d#EO|!WC*R8Jy<}I6fkJ^6|+kB{fJ0Nhn%VU zY(Q*Cw27lPinD0m^tQ%?tpP{TR#j^DU7rLg4QYuWVGms*wfKOQcLzw zWrp?$@pN8G^wr?3#a+GEI_D)vcE2j@ahE!V*A!>o3^<$XvWERRYon%cIta8b0n+FXo!R$4CNT*&_nMlaESd(K*P9f zM4m3MZ#K}>*6tG9EpG)Ha$7-IxtHe$1rE{zs_$`~K`)Idn*_D{a`CH4OT2ys^I?gR z=FR`{rh)v1uB<1Vr=+=YCxq$4!c+uv@(%C!f-5^7BSMaL*l}Iy0Hy?|!h;ZBx;eD9 zWo8sn^fgM{-KYSO?yL&j-h`*qfdl8h=l$M&qfokV3m_A3MX2R+J~|#Zl8=~4!LU5S z>E<)mf5{67+L1ObQf0~$8dm>RrWV06DCZPwEm_|39FIQ=y+_?D^PM2*z za4TS$Gg}s`Wf{U%dO6?83>+wmw>fGZ$@h__zGEWG=m{&??+G#OvBGL{#k;*Nb)`xd zFC5c0=fnA1IwY~Sqr42o$SR@cbMFh!2RbVcM=0!o4wMvkZk1tIl8(aMZm(apfCtRiG3t?3&Fa`isaM_oSBi2$Cug!eo@e`sR2#tT+hl~Q3l;c+VFf= z6J*r{3Y~1ZLq?Xt&jB|YS>~67Y6TAd^23wWq*}R3^!IsyHCXom@Yrx1{thf2bsy z*IR08s*FY?1kkw)N>*XTc@w6Kv+RZU)qU~(zC zDgoSq#3!NgmUIB^v36e84Rv_0G5q~= zvfk5)2uJdyQq}Jo`@inf+@gu>N|w_u zK;qr+cm2RF;-ddOB%hUoAa9m(7zwG`)CBvpDq;l+wLzwyRKx%0cIn=+_(6d;a^kq{ S2Cy(M$kgbDVXc8n%>MzxtK;(k literal 0 HcmV?d00001 diff --git a/readme.md b/readme.md index 92af49713..76adb400b 100644 --- a/readme.md +++ b/readme.md @@ -41,7 +41,7 @@

Our amazing sponsors for supporting my open-source contribution and the 30 Days of Challenge series!

-

Current Sponsor

+

Current Sponsors


+
+ ---