1679135340
소스 코드가 있는 초보자를 위한 상위 5개 Python 프로젝트. 이 자습서에서는 Python 초보자에게 완벽한 5가지 간단한 코드 예제를 제공합니다. Python에서 숫자 추측 게임을 빌드합니다. Python에서 간단한 암호 생성기를 빌드합니다. Python에서 암호 검사기를 빌드합니다. Python에서 웹 스크레이퍼를 빌드합니다. 파이썬에서 환율 계산기 만들기
Mark Twain은 출세의 비결은 시작하는 것이라고 말했습니다. 프로그래밍은 초보자에게 벅차게 보일 수 있지만 시작하는 가장 좋은 방법은 바로 뛰어들어 코드 작성을 시작하는 것입니다.
간단한 코드 예제는 초보자가 발을 적시고 프로그래밍의 기초를 배울 수 있는 좋은 방법입니다. 이 기사에서는 Python 초보자에게 완벽한 일련의 간단한 코드 예제를 제공합니다.
이러한 예제는 다양한 프로그래밍 개념을 다루며 프로그래밍의 견고한 기반을 개발하는 데 도움이 됩니다. 프로그래밍이 처음이든 기술을 연마하고 싶든 이 코드 예제는 코딩 여정을 시작하는 데 도움이 될 것입니다.
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.")
설명 :
암호 생성기는 이름에서 알 수 있듯이 다양한 문자 조합과 특수 문자를 사용하여 특정 길이의 임의 암호를 생성합니다.
코드 :
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)
설명 :
이것은 매우 간단한 암호 생성기이며 보안이 중요한 실제 시나리오에서 사용하기에 적합하지 않을 수 있습니다.
이 섹션에서는 비밀번호 검사기를 만들 것입니다. 그것의 임무는 우리가 설정한 몇 가지 기준에 따라 암호가 충분히 강력한지 확인하는 것입니다. 암호 기준 중 하나라도 충족되지 않으면 오류가 인쇄됩니다.
코드 :
# 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)
설명 :
웹 스크레이퍼는 웹 페이지에서 데이터를 스크랩/가져와서 원하는 형식(.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)
설명 :
통화 변환기는 사용자가 한 통화의 가치를 다른 통화로 변환하는 데 도움이 되는 프로그램입니다. 해외 구매 비용 계산, 여행 경비 추정, 재무 데이터 분석 등 다양한 용도로 사용할 수 있습니다.
참고: 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}")
설명 :
이 모든 프로젝트는 매우 간단하고 구축하기 쉽습니다. 정말로 Python 기술을 향상시키고 싶다면 코드를 가져와서 수정 및 편집하고 빌드하는 것이 좋습니다. 원하는 경우 이러한 간단한 프로젝트를 훨씬 더 복잡한 애플리케이션으로 전환할 수 있습니다.
일부 Python 기본 사항을 배워야 하는 경우 다음 유용한 리소스를 확인하세요.
행복한 코딩!
#python
1626775355
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.
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.
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
1602968400
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.
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
1602666000
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.
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
#python-programming #python-tutorials #learn-python #python-project #python3 #python #python-skills #python-tips
1597751700
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.
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
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
1593156510
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
III Built-in data types in Python
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
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
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 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).
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