on
ai 주식투자
- Get link
- X
- Other Apps
This guide will take you from zero to a solid understanding of fundamental Python concepts. We'll cover data types, conditional statements, loops, functions, and exception handling with more detail than before.
1. Data Types: The Building Blocks of Information
Data types define the kind of values a variable can hold. Python is dynamically typed, meaning you don't need to explicitly declare the type of a variable; Python figures it out automatically.
Checking Data Types:
You can use the type() function to determine the data type of a variable:
x = 10
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
-2. Conditional Statements: Making Decisions
Conditional statements allow your program to execute different code blocks based on whether certain conditions are true or false.
age = 18
if age >= 18:
print("You are eligible to vote.")
-
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")-3. Loops: Repeating Actions
Loops allow you to execute a block of code repeatedly.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit) # Prints each fruit on a new line
-
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
-
count = 0
while count < 5:
print(count)
count += 1 # Increment count to avoid an infinite loop
-4. Functions: Reusable Code Blocks
Functions are named blocks of code that perform a specific task. They help you organize your code and make it more reusable.
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!") # f-strings are a convenient way to format strings
greet("Alice") # Calling the function with the argument "Alice"
def add(x, y):
"""This function adds two numbers and returns the result."""
result = x + y
return result
sum_result = add(5, 3)
print(sum_result) # Output: 8
-5. Exception Handling: Dealing with Errors
Exceptions are errors that occur during program execution. Exception handling allows you to gracefully handle these errors and prevent your program from crashing.
try:
result = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input value.")
except Exception as e: # Catch any other exception
print(f"An unexpected error occurred: {e}")
finally:
print("This code always executes, regardless of whether an exception occurred.")
-
Resources for Further Learning:
Comments
Post a Comment