Python을 간단하게: 초급부터 고급까지 | 블로그
Python 코스 코드 예
제가 파이썬 학습을 위해 사용하고 만든 파이썬 코드에 대한 문서입니다.
이해하기 쉽고 배우기 쉽습니다. 여기에서 자유롭게 배워보세요.
조만간 더 고급 주제로 블로그를 업데이트하겠습니다.
목차
- 첫 번째 프로그램
- 변수 및 데이터 유형
- 문자열
- 숫자
- 사용자 의견 얻기
- 기본 계산기 만들기
- 퍼스트 매드립
- 목록
- 목록 기능
- 튜플
- 기능
- 반품 명세서
- If 문
- 비교한다면
- 맞추기 게임 2
- For 루프
- 지수함수
- 2D 목록 및 For 루프
첫 번째 프로그램
이 프로그램은 print() 명령이 어떻게 작동하는지 보여주기 위해 사용됩니다.
# This is a simple "Hello World" program that demonstrates basic print statements # Print the string "Hello world" to the console print("Hello world") # Print the integer 1 to the console print(1) # Print the integer 20 to the console print(20)
변수 및 데이터 유형
Python의 변수는 값을 저장하기 위해 예약된 메모리 위치입니다.
데이터 유형은 변수가 보유할 수 있는 데이터 유형(예: 정수, 부동 소수점, 문자열 등)을 정의합니다.
# This program demonstrates the use of variables and string concatenation # Assign the string "Dipsan" to the variable _name _name = "Dipsan" # Assign the integer 20 to the variable _age _age = 20 # Assign the string "piano" to the variable _instrument _instrument = "piano" # Print a sentence using string concatenation with the _name variable print("my name is" + _name + ".") # Print a sentence using string concatenation, converting _age to a string print("I'm" + str(_age) + "years old") # Converting int to string for concatenation # Print a simple string print("i dont like hanging out") # Print a sentence using string concatenation with the _instrument variable print("i love " + _instrument + ".")
문자열
텍스트를 저장하고 조작하는 데 사용되는 문자 시퀀스입니다. 텍스트를 작은따옴표('Hello'), 큰따옴표("Hello") 또는 여러 줄 문자열의 경우 삼중따옴표('''Hello''')로 묶어서 만듭니다. 예: "Hello, World!".
# This script demonstrates various string operations # Assign a string to the variable 'phrase' phrase = "DipsansAcademy" # Print a simple string print("This is a string") # Concatenate strings and print the result print('This' + phrase + "") # Convert the phrase to uppercase and print print(phrase.upper()) # Convert the phrase to lowercase and print print(phrase.lower()) # Check if the uppercase version of phrase is all uppercase and print the result print(phrase.upper().isupper()) # Print the length of the phrase print(len(phrase)) # Print the first character of the phrase (index 0) print(phrase[0]) # Print the second character of the phrase (index 1) print(phrase[1]) # Print the fifth character of the phrase (index 4) print(phrase[4]) # Find and print the index of 'A' in the phrase print(phrase.index("A")) # Replace "Dipsans" with "kadariya" in the phrase and print the result print(phrase.replace("Dipsans", "kadariya"))
숫자
숫자는 다양한 수치 연산과 수학 함수에 사용됩니다.
# Import all functions from the math module from math import * # Importing math module for additional math functions # This script demonstrates various numeric operations and math functions # Print the integer 20 print(20) # Multiply 20 by 4 and print the result print(20 * 4) # Add 20 and 4 and print the result print(20 + 4) # Subtract 4 from 20 and print the result print(20 - 4) # Perform a more complex calculation and print the result print(3 + (4 - 5)) # Calculate the remainder of 10 divided by 3 and print the result print(10 % 3) # Assign the value 100 to the variable _num _num = 100 # Print the value of _num print(_num) # Convert _num to a string, concatenate with other strings, and print print(str(_num) + " is my fav number") # Converting int to string for concatenation # Assign -10 to the variable new_num new_num = -10 # Print the absolute value of new_num print(abs(new_num)) # Absolute value # Calculate 3 to the power of 2 and print the result print(pow(3, 2)) # Power function # Find the maximum of 2 and 3 and print the result print(max(2, 3)) # Maximum # Find the minimum of 2 and 3 and print the result print(min(2, 3)) # Minimum # Round 3.2 to the nearest integer and print the result print(round(3.2)) # Rounding # Round 3.7 to the nearest integer and print the result print(round(3.7)) # Calculate the floor of 3.7 and print the result print(floor(3.7)) # Floor function # Calculate the ceiling of 3.7 and print the result print(ceil(3.7)) # Ceiling function # Calculate the square root of 36 and print the result print(sqrt(36)) # Square root
사용자로부터 입력 받기
이 프로그램은 사용자 입력을 얻기 위해 input() 함수를 사용하는 방법을 보여주는 데 사용됩니다.
# This script demonstrates how to get user input and use it in string concatenation # Prompt the user to enter their name and store it in the 'name' variable name = input("Enter your name : ") # Prompt the user to enter their age and store it in the 'age' variable age = input("Enter your age. : ") # Print a greeting using the user's input, concatenating strings print("hello " + name + " Youre age is " + age + " .")
기본 계산기 만들기
이 프로그램은 두 숫자를 더하는 간단한 계산기를 만듭니다.
# This script creates a basic calculator that adds two numbers # Prompt the user to enter the first number and store it in 'num1' num1 = input("Enter first number : ") # Prompt the user to enter the second number and store it in 'num2' num2 = input("Enter second number: ") # Convert the input strings to integers and add them, storing the result result = int(num1) + int(num2) # Print the result of the addition print(result)
최초의 Madlib
이 프로그램은 간단한 Mad Libs 게임을 만듭니다.
# This program is used to create a simple Mad Libs game. # Prompt the user to enter an adjective and store it in 'adjective1' adjective1 = input("Enter an adjective: ") # Prompt the user to enter an animal and store it in 'animal' animal = input("Enter an animal: ") # Prompt the user to enter a verb and store it in 'verb' verb = input("Enter a verb: ") # Prompt the user to enter another adjective and store it in 'adjective2' adjective2 = input("Enter another adjective: ") # Print the first sentence of the Mad Libs story using string concatenation print("I have a " + adjective1 + " " + animal + ".") # Print the second sentence of the Mad Libs story print("It likes to " + verb + " all day.") # Print the third sentence of the Mad Libs story print("My " + animal + " is so " + adjective2 + ".")
기울기
목록은 순서가 지정되고 변경 가능한 Python 항목의 모음입니다. 목록의 각 항목(또는 요소)에는 0부터 시작하는 인덱스가 있습니다. 목록에는 다양한 데이터 유형(예: 정수, 문자열 또는 기타 목록)의 항목이 포함될 수 있습니다.
목록은 대괄호 []를 사용하여 정의되며 각 항목은 쉼표로 구분됩니다.
# This script demonstrates basic list operations # Create a list of friends' names friends = ["Roi", "alex", "jimmy", "joseph"] # Print the entire list print(friends) # Print the first element of the list (index 0) print(friends[0]) # Print the second element of the list (index 1) print(friends[1]) # Print the third element of the list (index 2) print(friends[2]) # Print the fourth element of the list (index 3) print(friends[3]) # Print the last element of the list using negative indexing print(friends[-1]) # Print a slice of the list from the second element to the end print(friends[1:]) # Print a slice of the list from the second element to the third (exclusive) print(friends[1:3]) # Change the second element of the list to "kim" friends[1] = "kim" # Print the modified list print(friends)
목록 기능
이 스크립트는 다양한 목록 방법을 보여줍니다.
# This script demonstrates various list functions and methods # Create a list of numbers numbers = [4, 6, 88, 3, 0, 34] # Create a list of friends' names friends = ["Roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"] # Print both lists print(numbers) print(friends) # Add all elements from 'numbers' to the end of 'friends' friends.extend(numbers) # Add "hulk" to the end of the 'friends' list friends.append("hulk") # Insert "mikey" at index 1 in the 'friends' list friends.insert(1, "mikey") # Remove the first occurrence of "Roi" from the 'friends' list friends.remove("Roi") # Print the index of "mikey" in the 'friends' list print(friends.index("mikey")) # Remove and print the last item in the 'friends' list print(friends.pop()) # Print the current state of the 'friends' list print(friends) # Remove all elements from the 'friends' list friends.clear() # Print the empty 'friends' list print(friends) # Sort the 'numbers' list in ascending order numbers.sort() # Print the sorted 'numbers' list print(numbers)
튜플
튜플은 순서가 지정되어 있지만 변경할 수 없는(불변) Python의 항목 모음입니다. 튜플을 생성한 후에는 해당 요소를 추가, 제거 또는 변경할 수 없습니다. 목록과 마찬가지로 튜플에는 다양한 데이터 유형의 항목이 포함될 수 있습니다.
튜플은 괄호()를 사용하여 정의되며 각 항목은 쉼표로 구분됩니다.
# This script introduces tuples and their immutability # Create a tuple with two elements values = (3, 4) # Print the entire tuple print(values) # Print the second element of the tuple (index 1) print(values[1]) # The following line would cause an IndexError if uncommented: # print(values[2]) # This would cause an IndexError # The following line would cause a TypeError if uncommented: # values[1] = 30 # This would cause a TypeError as tuples are immutable # The following line would print the modified tuple if the previous line worked: # print(values)
기능
함수는 특정 작업을 수행하는 재사용 가능한 코드 블록입니다. 함수는 입력(인수라고 함)을 받아 처리하고 출력을 반환할 수 있습니다. 함수는 코드를 구성하고, 모듈화하고, 반복을 방지하는 데 도움이 됩니다.
n Python에서 함수는 def 키워드와 함수 이름, 괄호() 및 콜론 :을 사용하여 정의됩니다. 함수 내부의 코드는 들여쓰기되어 있습니다.
이 코드는 함수를 정의하고 호출하는 방법을 보여줍니다.
# This script demonstrates how to define and call functions # Define a function called 'greetings' that prints two lines def greetings(): print("HI, Welcome to programming world of python") print("keep learning") # Print a statement before calling the function print("this is first statement") # Call the 'greetings' function greetings() # Print a statement after calling the function print("this is last statement") # Define a function 'add' that takes two parameters and prints their sum def add(num1, num2): print(int(num1) + int(num2)) # Call the 'add' function with arguments 3 and 4 add(3, 4)
반품 명세서
return 문은 함수에서 호출자에게 값을 다시 보내는(또는 "반환") 데 사용됩니다. return이 실행되면 함수가 종료되고 return 이후에 지정한 값이 함수가 호출된 위치로 다시 전송됩니다.
이 프로그램은 함수에서 return 문을 사용하는 방법을 보여줍니다.
# This script demonstrates the use of return statements in functions # Define a function 'square' that returns the square of a number def square(num): return num * num # Any code after the return statement won't execute # Call the 'square' function with argument 2 and print the result print(square(2)) # Call the 'square' function with argument 4 and print the result print(square(4)) # Call the 'square' function with argument 3, store the result, then print it result = square(3) print(result)
If 문
if 문은 조건(True 또는 False를 반환하는 표현식)을 평가합니다.
조건이 True이면 if 문 아래의 코드 블록이 실행됩니다.
elif : "else if"의 줄임말로 여러 조건을 확인할 수 있습니다.
평가할 조건이 여러 개 있고 첫 번째 True 조건에 대해 코드 블록을 실행하려는 경우에 사용됩니다.
else: else 문은 앞의 if 또는 elif 조건 중 어느 것도 True가 아닌 경우 코드 블록을 실행합니다.
# This script demonstrates the use of if-elif-else statements # Set boolean variables for conditions is_boy = True is_handsome = False # Check conditions using if-elif-else statements if is_boy and is_handsome: print("you are a boy & youre handsome") print("hehe") elif is_boy and not (is_handsome): print("Youre a boy but sorry not handsome") else: print("youre not a boy")
비교하는 경우
이 코드는 if 문의 비교 연산을 보여줍니다.
# This script demonstrates comparison operations in if statements # Define a function to find the maximum of three numbers def max_numbers(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 # Test the max_numbers function with different inputs print(max_numbers(20, 40, 60)) print(max_numbers(30, 14, 20)) print(max_numbers(3, 90, 10)) print("For min_number") # Define a function to find the minimum of three numbers def min_numbers(num1, num2, num3): if num1 <= num2 and num1 <= num3: return num1 elif num2 <= num1 and num2 <= num3: return num2 else: return num3 # Test the min_numbers function with different inputs print(min_numbers(20, 40, 60)) print(min_numbers(30, 14, 20)) print(min_numbers(3, 90, 10))
추측 게임 2
이 스크립트는 더 많은 기능으로 추측 게임을 개선합니다:
# This script improves the guessing game with more features import random # Generate a random number between 1 and 20 secret_number = random.randint(1, 20) # Initialize the number of attempts and set a limit attempts = 0 attempt_limit = 5 # Loop to allow the user to guess the number while attempts < attempt_limit: guess = int(input(f"Guess the number (between 1 and 20). You have {attempt_limit - attempts} attempts left: ")) if guess == secret_number: print("Congratulations! You guessed the number!") break elif guess < secret_number: print("Too low!") else: print("Too high!") attempts += 1 # If the user does not guess correctly within the attempt limit, reveal the number if guess != secret_number: print(f"Sorry, the correct number was {secret_number}.")
For 루프
for 루프는 목록, 튜플, 문자열 또는 범위와 같은 일련의 요소를 반복하는 데 사용됩니다.
이 코드는 for 루프를 소개합니다:
# List of numbers numbers = [1, 2, 3, 4, 5] # Iterate over each number in the list for number in numbers: # Print the current number print(number) # Output: # 1 # 2 # 3 # 4 # 5 # List of friends friends = ["Roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"] # Iterate over each friend in the list for friend in friends: # Print the name of the current friend print(friend) # Output: # Roi # alex # jimmy # joseph # kevin # tony # jimmy # Use range to generate numbers from 0 to 4 for num in range(5): print(num) # Output: # 0 # 1 # 2 # 3 # 4
지수함수
지수 함수는 상수 밑이 변수 지수로 올라가는 수학 함수입니다.
이 스크립트는 math.pow 함수를 사용하는 방법을 보여줍니다.
# This script demonstrates the use of the exponential function def exponentialFunction(base,power): result = 1 for index in range(power): result = result * base return result print(exponentialFunction(3,2)) print(exponentialFunction(4,2)) print(exponentialFunction(5,2)) #or you can power just by print(2**3) #number *** power
2D List and For Loops
A 2D list (or 2D array) in Python is essentially a list of lists, where each sublist represents a row of the matrix. You can use nested for loops to iterate over elements in a 2D list. Here’s how you can work with 2D lists and for loops:
# This script demonstrates the use of 2D List and For Loops # Define a 2D list (list of lists) num_grid = [ [1, 2, 3], # Row 0: contains 1, 2, 3 [4, 5, 6], # Row 1: contains 4, 5, 6 [7, 8, 9], # Row 2: contains 7, 8, 9 [0] # Row 3: contains a single value 0 ] # Print specific elements in num_grid print(num_grid[0][0]) # Print value in the zeroth row, zeroth column (value: 1) print(num_grid[1][0]) # Print value in the first row, zeroth column (value: 4) print(num_grid[2][2]) # Print value in the second row, second column (value: 9) print("using nested for loops") for row in num_grid : for col in row: print(col)
This is how we can use 2D List and For Loops.
위 내용은 Python을 간단하게: 초급부터 고급까지 | 블로그의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undress AI Tool
무료로 이미지를 벗다

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

예, ApythonclasscanhavemultiplecontructorsthrowaltiveTechniques.1.usedefaultargumentsinthe__init__methodtoallowflexibleinitializationswithvaryingnumbersofparameters.2.defineclassmethodsasaltistuctructorsforcecalobbebcreati

Python에서 범위 () 함수와 함께 루프를 사용하는 것은 루프 수를 제어하는 일반적인 방법입니다. 1. 루프 수를 알고 있거나 인덱스별로 요소에 액세스 해야하는 경우 사용하십시오. 2. 범위 (정지) 0에서 STOP-1, 범위 (시작, 중지) 시작부터 정지 -1까지, 범위 (시작, 정지) 단계 크기를 추가합니다. 3. 범위는 최종 값을 포함하지 않으며 Python 3의 목록 대신 반복 가능한 객체를 반환합니다. 4. 목록을 통해 목록 (range ())로 변환하고 리버스 순서로 음수 단계 크기를 사용할 수 있습니다.

QUML (Quantum Machine Learning)을 시작하려면 선호되는 도구는 Python이며 Pennylane, Qiskit, Tensorflowquantum 또는 Pytorchquantum과 같은 라이브러리를 설치해야합니다. 그런 다음 Pennylane을 사용하여 양자 신경망을 구축하는 것과 같은 예제를 실행하여 프로세스에 익숙해 지십시오. 그런 다음 데이터 세트 준비, 데이터 인코딩, 구축 파라 메트릭 양자 회로 구축, 클래식 옵티마이 저 트레이닝 등의 단계에 따라 모델을 구현하십시오. 실제 전투에서는 처음부터 복잡한 모델을 추구하지 않고 하드웨어 제한에주의를 기울이고, 하이브리드 모델 구조를 채택하며, 최신 문서와 공식 문서를 지속적으로 언급하여 개발에 대한 후속 조치를 취해야합니다.

Python을 사용하여 WebApi를 호출하여 데이터를 얻는 것의 핵심은 기본 프로세스와 공통 도구를 마스터하는 것입니다. 1. 요청을 사용하여 HTTP 요청을 시작하는 것이 가장 직접적인 방법입니다. Get 메소드를 사용하여 응답을 얻고 JSON ()을 사용하여 데이터를 구문 분석하십시오. 2. 인증이 필요한 API의 경우 헤더를 통해 토큰 또는 키를 추가 할 수 있습니다. 3. 응답 상태 코드를 확인해야합니다. 예외를 자동으로 처리하려면 response.raise_for_status ()를 사용하는 것이 좋습니다. 4. 페이징 인터페이스에 직면하여 다른 페이지를 차례로 요청하고 주파수 제한을 피하기 위해 지연을 추가 할 수 있습니다. 5. 반환 된 JSON 데이터를 처리 할 때 구조에 따라 정보를 추출해야하며 복잡한 데이터를 데이터로 변환 할 수 있습니다.

Python의 Onelineifelse는 XifconditionElsey로 작성된 3 배 연산자로 간단한 조건부 판단을 단순화하는 데 사용됩니다. 상태 = "성인"ifage> = 18else "minor"와 같은 가변 할당에 사용할 수 있습니다. 또한 defget_status (Age)와 같은 함수를 직접 반환하는 데 사용될 수 있습니다. 반환 "성인"ifage> = 18else "minor"; 중첩 된 사용이 지원되지만 결과 = "a"i

이 기사는 여러 상위 Python "완성 된"프로젝트 웹 사이트 및 고급 "블록버스터"학습 리소스 포털을 선택했습니다. 개발 영감, 마스터 레벨 소스 코드 관찰 및 학습 또는 실제 기능을 체계적으로 개선하든, 이러한 플랫폼은 놓치지 않아야하며 파이썬 마스터로 빠르게 성장할 수 있도록 도울 수 있습니다.

Python의 Ifelse 진술을 작성하는 핵심은 논리적 구조와 세부 사항을 이해하는 것입니다. 1. 인프라는 조건이 설정되면 코드를 실행하는 것입니다. 그렇지 않으면 다른 부분이 실행되면 선택 사항입니다. 2. 다중 조건 판결은 ELIF와 함께 시행되며, 순차적으로 실행되며 일단 충족되면 중지됩니다. 3. 추가 세분 판단에 사용되는 경우 중첩 된 경우 두 층을 초과하지 않는 것이 좋습니다. 4. 3 배의 표현은 간단한 시나리오에서 간단한 ifelse를 대체하는 데 사용될 수 있습니다. 들여 쓰기, 조건부 질서 및 논리적 무결성에주의를 기울임으로써 우리는 명확하고 안정적인 판단 코드를 작성할 수 있습니다.

For Loop을 사용하여 파일을 라인별로 읽는 것은 큰 파일을 처리하는 효율적인 방법입니다. 1. 기본 사용법은 WithOpen ()을 통해 파일을 열고 폐쇄를 자동으로 관리하는 것입니다. ForlineInfile과 결합하여 각 라인을 가로 지릅니다. line.strip ()는 선 파단과 공백을 제거 할 수 있습니다. 2. 줄 번호를 기록 해야하는 경우 열거 번호 (파일, start = 1)를 사용하여 줄 번호가 1에서 시작하도록 할 수 있습니다. 3. ASCII가 아닌 파일을 처리 할 때는 인코딩 오류를 피하기 위해 UTF-8과 같은 인코딩 매개 변수를 지정해야합니다. 이러한 방법은 간결하고 실용적이며 대부분의 텍스트 처리 시나리오에 적합합니다.
