최  호민

최 호민

1679135340

소스 코드 초보자를 위한 5가지 Python 프로젝트

소스 코드가 있는 초보자를 위한 상위 5개 Python 프로젝트. 이 자습서에서는 Python 초보자에게 완벽한 5가지 간단한 코드 예제를 제공합니다. Python에서 숫자 추측 게임을 빌드합니다. Python에서 간단한 암호 생성기를 빌드합니다. Python에서 암호 검사기를 빌드합니다. Python에서 웹 스크레이퍼를 빌드합니다. 파이썬에서 환율 계산기 만들기

Mark Twain은 출세의 비결은 시작하는 것이라고 말했습니다. 프로그래밍은 초보자에게 벅차게 보일 수 있지만 시작하는 가장 좋은 방법은 바로 뛰어들어 코드 작성을 시작하는 것입니다.

간단한 코드 예제는 초보자가 발을 적시고 프로그래밍의 기초를 배울 수 있는 좋은 방법입니다. 이 기사에서는 Python 초보자에게 완벽한 일련의 간단한 코드 예제를 제공합니다.

이러한 예제는 다양한 프로그래밍 개념을 다루며 프로그래밍의 견고한 기반을 개발하는 데 도움이 됩니다. 프로그래밍이 처음이든 기술을 연마하고 싶든 이 코드 예제는 코딩 여정을 시작하는 데 도움이 될 것입니다.

Python 기본 사항을 배워야 하는 경우 이 자습서의 끝에 유용한 리소스를 추가했습니다.

목차:

  1. Python에서 숫자 추측 게임을 만드는 방법
  2. Python에서 간단한 비밀번호 생성기를 만드는 방법
  3. Python에서 암호 검사기를 빌드하는 방법
  4. Python에서 웹 스크레이퍼를 구축하는 방법
  5. 파이썬에서 통화 변환기를 만드는 방법

Python에서 숫자 추측 게임을 만드는 방법

이 프로젝트에서는 사용자가 1에서 100 사이의 임의의 숫자를 추측할 수 있는 간단한 숫자 추측 게임을 만들 것입니다. 프로그램은 추측할 때마다 사용자에게 힌트를 제공하여 추측이 너무 높거나 낮은지 여부를 나타냅니다. 사용자는 정확한 숫자를 추측합니다.

코드 :

import random

secret_number = random.randint(1, 100)

while True:
    guess = int(input("Guess the number between 1 and 100: "))
    
    if guess == secret_number:
        print("Congratulations! You guessed the number!")
        break
    elif guess < secret_number:
        print("Too low! Try again.")
    else:
        print("Too high! Try again.")

설명 :

  • random난수를 생성할 수 있는 모듈을 가져오는 것으로 시작합니다 .
  • randint()모듈 의 함수를 사용하여 1에서 100 사이의 난수를 생성 random하고 변수에 할당합니다.
  • 사용자가 올바르게 추측할 때까지 숫자를 추측할 수 있는 루프를 만듭니다. 루프 내에서 사용자에게 함수를 사용하여 추측을 입력 input()하고 함수를 사용하여 입력을 정수로 변환하라는 메시지를 표시합니다 int().
  • 사용자의 추측이 맞는지, 너무 높은지 또는 너무 낮은지 확인하는 조건문을 루프 내에 추가합니다. 추측이 맞으면 축하 메시지를 출력하고 루프에서 빠져나옵니다. 추측이 너무 높거나 너무 낮으면 사용자가 숫자를 올바르게 추측하는 데 도움이 되는 힌트 메시지를 인쇄합니다.
  • 프로그램을 실행하고 숫자 추측 게임을 해보세요!

Python에서 간단한 비밀번호 생성기를 만드는 방법

암호 생성기는 이름에서 알 수 있듯이 다양한 문자 조합과 특수 문자를 사용하여 특정 길이의 임의 암호를 생성합니다.

코드 :

import random
import string

def generate_password(length):
    """This function generates a random password
    of a given length using a combination of
    uppercase letters, lowercase letters,
    digits, and special characters"""
    
    # Define a string containing all possible characters
    all_chars = string.ascii_letters + string.digits + string.punctuation
    
    # Generate a password using a random selection of characters
    password = "".join(random.choice(all_chars) for i in range(length))
    
    return password

# Test the function by generating a password of length 10
password = generate_password(10)
print(password)

설명 :

  • 임의의 값을 생성하고 문자열로 작업하는 데 사용하는 random및 모듈을 각각 가져옵니다 .string
  • 다음으로 생성해야 하는 암호의 길이를 지정하는 generate_password단일 매개 변수를 사용하는 함수를 정의합니다 .length
  • 함수 내에서 all_chars암호를 생성하는 데 사용할 수 있는 모든 가능한 문자를 포함하는 라는 문자열을 정의합니다. string.ascii_letters, string.digits및 상수를 사용하여 string.punctuation이 문자열을 만듭니다.
  • 그런 다음 list comprehension을 사용하여 함수를 사용하여 문자열 length에서 임의 의 문자 목록을 생성합니다 . 마지막으로 함수를 사용하여 이러한 문자를 단일 문자열로 결합 하고 결과를 반환합니다.all_charsrandom.choice()"".join()
  • 함수를 테스트하기 위해 인수 10 으로 호출하여 길이 10의 암호를 생성하고 결과를 인쇄합니다.

이것은 매우 간단한 암호 생성기이며 보안이 중요한 실제 시나리오에서 사용하기에 적합하지 않을 수 있습니다.

Python에서 암호 검사기를 빌드하는 방법

이 섹션에서는 비밀번호 검사기를 만들 것입니다. 그것의 임무는 우리가 설정한 몇 가지 기준에 따라 암호가 충분히 강력한지 확인하는 것입니다. 암호 기준 중 하나라도 충족되지 않으면 오류가 인쇄됩니다.

코드 :

# Define a function to check if the password is strong enough
def password_checker(password):
    # Define the criteria for a strong password
    min_length = 8
    has_uppercase = False
    has_lowercase = False
    has_digit = False
    has_special_char = False
    special_chars = "!@#$%^&*()-_=+[{]}\|;:',<.>/?"
    
    # Check the length of the password
    if len(password) < min_length:
        print("Password is too short!")
        return False
    
    # Check if the password contains an uppercase letter, lowercase letter, digit, and special character
    for char in password:
        if char.isupper():
            has_uppercase = True
        elif char.islower():
            has_lowercase = True
        elif char.isdigit():
            has_digit = True
        elif char in special_chars:
            has_special_char = True
    
    # Print an error message for each missing criteria
    if not has_uppercase:
        print("Password must contain at least one uppercase letter!")
        return False
    if not has_lowercase:
        print("Password must contain at least one lowercase letter!")
        return False
    if not has_digit:
        print("Password must contain at least one digit!")
        return False
    if not has_special_char:
        print("Password must contain at least one special character!")
        return False
    
    # If all criteria are met, print a success message
    print("Password is strong!")
    return True

# Prompt the user to enter a password and check if it meets the criteria
password = input("Enter a password: ")
password_checker(password)

설명 :

  • password_checker()이 코드에서는 암호를 인수로 사용하고 강도에 대한 특정 기준을 충족하는지 확인하는 함수를 정의합니다 .
  • 먼저 최소 길이 8자, 대문자 1개, 소문자 1개, 숫자 1개, 특수 문자 1개 등 강력한 비밀번호 기준을 정의합니다.
  • 그런 다음 암호의 각 문자를 반복하는 for 루프를 사용하여 암호의 길이와 필요한 유형의 문자가 포함되어 있는지 확인합니다.
  • 암호가 기준을 충족하지 못하는 경우 오류 메시지를 인쇄하고 False암호가 충분히 강하지 않음을 나타내기 위해 돌아갑니다. 그렇지 않으면 성공 메시지를 인쇄하고 를 반환합니다 True.
  • 마지막으로 사용자에게 함수를 사용하여 비밀번호를 입력하라는 메시지를 표시 input()하고 password_checker()기준을 충족하는지 확인하기 위해 함수에 전달합니다.

Python에서 웹 스크레이퍼를 구축하는 방법

웹 스크레이퍼는 웹 페이지에서 데이터를 스크랩/가져와서 원하는 형식(.csv 또는 .txt)으로 저장합니다. 이 섹션에서는 Beautiful Soup이라는 Python 라이브러리를 사용하여 간단한 웹 스크레이퍼를 빌드합니다.

코드 :

import requests
from bs4 import BeautifulSoup

# Set the URL of the webpage you want to scrape
url = 'https://www.example.com'

# Send an HTTP request to the URL and retrieve the HTML content
response = requests.get(url)

# Create a BeautifulSoup object that parses the HTML content
soup = BeautifulSoup(response.content, 'html.parser')

# Find all the links on the webpage
links = soup.find_all('a')

# Print the text and href attribute of each link
for link in links:
    print(link.get('href'), link.text)

설명 :

  • requests이 코드에서는 먼저 HTTP 요청을 만들고 HTML 콘텐츠를 구문 분석하는 데 사용되는 및 모듈을 각각 가져옵니다 BeautifulSoup.
  • 다음으로 이라는 변수에 스크랩하려는 웹 페이지의 URL을 설정합니다 url.
  • 그런 다음 이 함수를 사용하여 requests.get()URL에 HTTP GET 요청을 보내고 응답으로 웹 페이지의 HTML 콘텐츠를 검색합니다.
  • 파서 를 사용하여 응답의 HTML 콘텐츠를 파싱하는 BeautifulSoup객체를 생성합니다 .souphtml.parser
  • 그런 다음 이 방법을 사용하여 soup.find_all()웹 페이지의 모든 링크를 찾고 이라는 변수에 저장합니다 links.
  • 마지막으로 for 루프를 사용하여 각 링크를 반복하고 메서드 links를 사용하여 각 링크의 텍스트 및 href 속성을 인쇄합니다 link.get().

파이썬에서 통화 변환기를 만드는 방법

통화 변환기는 사용자가 한 통화의 가치를 다른 통화로 변환하는 데 도움이 되는 프로그램입니다. 해외 구매 비용 계산, 여행 경비 추정, 재무 데이터 분석 등 다양한 용도로 사용할 수 있습니다.

참고: ExchangeRate-API를 사용하여 환율 데이터를 가져옵니다. 이는 환율에 대한 무료 오픈 소스 API입니다. 그러나 사용 제한이나 요구 사항이 다를 수 있는 다른 API도 있습니다.

암호:

# Import the necessary modules
import requests

# Define a function to convert currencies
def currency_converter(amount, from_currency, to_currency):
    # Set the API endpoint for currency conversion
    api_endpoint = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
    
    # Send a GET request to the API endpoint
    response = requests.get(api_endpoint)
    
    # Get the JSON data from the response
    data = response.json()
    
    # Extract the exchange rate for the target currency
    exchange_rate = data["rates"][to_currency]
    
    # Calculate the converted amount
    converted_amount = amount * exchange_rate
    
    # Return the converted amount
    return converted_amount

# Prompt the user to enter the amount, source currency, and target currency
amount = float(input("Enter the amount: "))
from_currency = input("Enter the source currency code: ").upper()
to_currency = input("Enter the target currency code: ").upper()

# Convert the currency and print the result
result = currency_converter(amount, from_currency, to_currency)
print(f"{amount} {from_currency} is equal to {result} {to_currency}")

설명 :

  • currency_converter()이 코드에서는 금액, 소스 통화 코드 및 대상 통화 코드를 인수로 사용하고 변환된 금액을 반환하는 호출된 함수를 정의합니다 .
  • 먼저 GET 요청을 엔드포인트로 보내는 모듈 from_currency과 매개변수를 사용하여 통화 변환을 위한 API 엔드포인트를 설정합니다 .requests
  • 그런 다음 매개 변수를 사용하여 API가 반환한 JSON 데이터에서 대상 통화에 대한 환율을 추출 to_currency하고 환율에 매개 변수를 곱하여 변환된 금액을 계산합니다 amount.
  • 마지막으로 사용자에게 함수를 사용하여 , 및 를 입력 하고 amount통화 from_currency를 변환하는 함수 에 전달하라는 메시지를 표시합니다. 변환된 금액은 문자열 형식을 사용하여 인쇄됩니다.to_currencyinput()currency_converter()

결론

이 모든 프로젝트는 매우 간단하고 구축하기 쉽습니다. 정말로 Python 기술을 향상시키고 싶다면 코드를 가져와서 수정 및 편집하고 빌드하는 것이 좋습니다. 원하는 경우 이러한 간단한 프로젝트를 훨씬 더 복잡한 애플리케이션으로 전환할 수 있습니다.

일부 Python 기본 사항을 배워야 하는 경우 다음 유용한 리소스를 확인하세요.

  • 첫 번째 Python 프로젝트를 빌드하는 방법
  • 모두를 위한 Python – Dr. Chuck의 전체 대학 과정

행복한 코딩!

출처: https://www.freecodecamp.org

#python

What is GEEK

Buddha Community

소스 코드 초보자를 위한 5가지 Python 프로젝트
Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development

Art  Lind

Art Lind

1602666000

How to Remove all Duplicate Files on your Drive via Python

Today you’re going to learn how to use Python programming in a way that can ultimately save a lot of space on your drive by removing all the duplicates.

Intro

In many situations you may find yourself having duplicates files on your disk and but when it comes to tracking and checking them manually it can tedious.

Heres a solution

Instead of tracking throughout your disk to see if there is a duplicate, you can automate the process using coding, by writing a program to recursively track through the disk and remove all the found duplicates and that’s what this article is about.

But How do we do it?

If we were to read the whole file and then compare it to the rest of the files recursively through the given directory it will take a very long time, then how do we do it?

The answer is hashing, with hashing can generate a given string of letters and numbers which act as the identity of a given file and if we find any other file with the same identity we gonna delete it.

There’s a variety of hashing algorithms out there such as

  • md5
  • sha1
  • sha224, sha256, sha384 and sha512

#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips

How To Compare Tesla and Ford Company By Using Magic Methods in Python

Magic Methods are the special methods which gives us the ability to access built in syntactical features such as ‘<’, ‘>’, ‘==’, ‘+’ etc…

You must have worked with such methods without knowing them to be as magic methods. Magic methods can be identified with their names which start with __ and ends with __ like init, call, str etc. These methods are also called Dunder Methods, because of their name starting and ending with Double Underscore (Dunder).

Now there are a number of such special methods, which you might have come across too, in Python. We will just be taking an example of a few of them to understand how they work and how we can use them.

1. init

class AnyClass:
    def __init__():
        print("Init called on its own")
obj = AnyClass()

The first example is _init, _and as the name suggests, it is used for initializing objects. Init method is called on its own, ie. whenever an object is created for the class, the init method is called on its own.

The output of the above code will be given below. Note how we did not call the init method and it got invoked as we created an object for class AnyClass.

Init called on its own

2. add

Let’s move to some other example, add gives us the ability to access the built in syntax feature of the character +. Let’s see how,

class AnyClass:
    def __init__(self, var):
        self.some_var = var
    def __add__(self, other_obj):
        print("Calling the add method")
        return self.some_var + other_obj.some_var
obj1 = AnyClass(5)
obj2 = AnyClass(6)
obj1 + obj2

#python3 #python #python-programming #python-web-development #python-tutorials #python-top-story #python-tips #learn-python

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type