- print()
- 여러 인자를 받을 수 있고, 기본적으로 인자들을 스페이스로 구분하여 출력함
- input()
name = input("Enter your name: ")
- Basic Input
name = input("Enter your name: ) print(f"Hello, {name}!")
- Numeric Input
- You can use input() to receive numeric input, but you need to convert the input to the desired data type (e.g., int or float).
age = int(input("Enter your age: ")) if age >= 18: print("Your are an adult.") else: print("Your are a minor.")
- Multiple Inputs:
name = input("Enter your name: ") age = int(input("Enter your age: ")) print(f"Hello, {name}! You are {age} years old.")
- Using input() in a Loop
while True: user_input = input("Enter 'quit' to exit: ") if user_input.lower() == 'quit': break
- Handling Exceptions
try: age = int(input("Enter your age: )) print(f"You entered {age} yeaers old.") except ValueError: print("Invalid input. Please enter a valid number.")
- Using input() with eval()
expression = input("Enter a mathmatical expression: ") result = eval(expression)
- Basic Input
- len(): returns the number of items in an object, such as a string, list, or tuple
length = len("Python")
- type(): returns the type of an object
x = 5 t = type(x)
- int(), float(), str(), list(), tuple(), dict(), set(): used for type conversion between different data types.
x = int("42") y = str(3.14)
- range(): generates a sequence of numbers within a specified range
numbers = list(range(1, 6)) # Generates [1, 2, 3, 4, 5]
- sum(), max(), min(), abs(): perform mathematical operations on data
numbers = [1, 2, 3, 4, 5] total = sum(numbers) largest = max(numbers)
- sorted(): returns a sorted version of a list, without modifying the original list.
numbers = [5, 2, 9, 1, 3] sorted_numbers = sorted(numbers)
- zip(): combines two or more iterables element-wise.
names = ["Alice", "Bob", "Charlie"] scores = [85, 92, 78] combined = list(zip(names, scores))
- map(), filter(): used for functional programming operations on iterable data structures
numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
- all(), any(): check if all or any elements of an iterable evaluate to True
nums = [True, True, False, True] all_true = all(nums) # False any_true = any(nums) # True
- open(): Used to open files for reading or writing.
with open("example.txt", "r") as file: content = file.read()
- help(): Displays documentation and help for Python objects and modules.
help(list)
- dir(): lists all attributes and methods of an object.
- the output of dir() can be quite extensive, especially for complex objects and modules
- includes both built-in methods and user-defined attributes and methods
- can use this function to discover what functionality is available for a particular object or module and to aid in debugging and exploration during development
dir(list)
- Built-in Functions and Modules
- can use dir() to explore the attributes and methods of built-in functions and modules
print(dir(len)) # List attributes and methods of the len function import math print(dir(math)) # List attributes and functions in the math module
- Data Types
- can use dir() to examine the methods and attributes available for various data types, such as strings, lists, and dictionaries.
s = "Hello, World!" print(dir(s)) # List attributes and methods of a string numbers = [1, 2, 3, 4, 5] print(dir(numbers)) # List attributes and methods of a list
- Custom Classes
- when you define your own classes, you can use dir() to inspect the attributes and methods of instances of those classes.
class Person: def __init__(self, name, age): self.name = name self.age = age person = Person("Alice", 30) print(dir(person)) # List attributes and methods of a custom class instance
- Modules and Packages
- dir() can also be used to explore modules and packages you create or import.
# Assuming you have a custom module named mymodule.py import mymodule print(dir(mymodule)) # List attributes and functions in your custom module
- Objects with Special Methods:
- Some objects, such as iterators and context managers, have special methods (e.g., iter, enter, exit) that you can inspect using dir().
numbers = [1, 2, 3, 4, 5] iterator = iter(numbers) print(dir(iterator)) # List special methods for an iterator
- Built-in Types and Modules:
- You can explore the attributes and methods of built-in types and modules, such as list, str, and math.
print(dir(list)) # List attributes and methods of the list type print(dir(str)) # List attributes and methods of the str type print(dir(math)) # List attributes and functions in the math module
- eval(): used to dynamically evaluate a single Python expression (a piece of Python code that produces a value) from a string
- Basic Mathematical Evaluation:
expression = "2 + 3 * 4" result = eval(expression) print(result) # Output: 14
- User Input Evaluation
expression = input("Enter a mathematical expression: ") try: result = eval(expression) print("Result:", result) except Exception as e: print("Error:", e)
- Basic Mathematical Evaluation:
- map()
- 주어진 함수를 순회 가능한(iterable) 객체의 각 요소에 적용하여 새로운 순회 가능한 객체를 생성하는 함수
map(function, iterable, ...)
- function: 각 요소에 적용할 함수를 지정
- iterable: 함수를 적용할순회 가능한 객체를 지정. 여러 개의 iterable을 지정할 수 있으며, map()은 모든 iterable에서 동시에 요소를 가져와 함수를 적용함. iterable의 길이가 다를 경우 가장 짧은 iterable의 길이에 맞춰 처리됨
- 함수를 벡터화하고 반복적으로 적용하는 데 사용됨. 이를 통해 코드를 더 간결하게 만들고, 여러 값을 한 번에 변환하거나 처리하는 데 유용함
- map 함수는 결과를 즉시 계산하지 않고, 지연 평가(lazy evaluation)를 사용하여 요소를 계산하지 않고 기다림