Python Syntax

Kom i gang. Det er Gratis
eller tilmeld med din email adresse
Python Syntax af Mind Map: Python Syntax

1. Basic Syntax

1.1. (a) Variables and Data Types

1.1.1. x = 5 # Integer name = "Alice" # String pi = 3.14 # Float is_valid = True # Boolean

1.2. b. Comments

1.2.1. Single-line comments: Use # to add comments.

1.2.2. Multi-line comments: Use triple quotes (''' or """).

1.3. c. Indentation

1.3.1. Python uses indentation (spaces or tabs) to define blocks of code.

1.3.2. 4 spaces per indentation level is the convention.

2. Data Structures

2.1. a. Lists

2.1.1. Ordered, mutable collection of elements.

2.1.1.1. fruits = ["apple", "banana", "cherry"] fruits.append("orange") # Add an element fruits[0] # Accessing element by index

2.2. b. Tuples

2.2.1. Ordered, immutable collection of elements.

2.2.1.1. coordinates = (10, 20)

2.3. c. Dictionaries

2.3.1. Unordered collection of key-value pairs.

2.3.1.1. person = {"name": "Alice", "age": 25} person["name"] # Access by key

2.4. d. Sets

2.4.1. Unordered collection of unique elements.

2.4.1.1. unique_numbers = {1, 2, 3, 4} unique_numbers.add(5) # Add an element

2.5. e. Strings

2.5.1. Immutable sequences of characters.

2.5.1.1. message = "Hello, World!" length = len(message) # Length of the string

3. Control Flow

3.1. a. Conditional Statements

3.1.1. if, elif, else to control the flow based on conditions.

3.1.1.1. if x > 10: print("x is greater than 10") elif x == 10: print("x is equal to 10") else: print("x is less than 10")

3.2. b. Loops

3.2.1. For Loop: Iterates over a sequence (like a list or string).

3.2.1.1. for i in range(5): # Loop from 0 to 4 print(i)

3.2.2. While Loop: Repeats a block of code as long as a condition is True.

3.2.2.1. while x < 5: print(x) x += 1 # Increment

3.3. c. Break, Continue, and Pass

3.3.1. break: Exits the loop. continue: Skips the current iteration. pass: Placeholder for future code.

3.3.1.1. for i in range(5): if i == 3: continue print(i)

4. Functions

4.1. a. Defining Functions:

4.1.1. Use def to define a function.

4.1.1.1. def greet(name): return "Hello, " + name print(greet("Alice"))

4.2. b. Arguments and Return Values

4.2.1. Functions can accept parameters and return values.

4.2.1.1. def add(a, b): return a + b result = add(2, 3)

4.3. c. Lambda Functions (Anonymous Functions)

4.3.1. Short functions that are defined using lambda.

4.3.1.1. multiply = lambda x, y: x * y print(multiply(2, 3))

4.4. d. Variable Scope

4.4.1. Local variables: Defined inside a function. Global variables: Defined outside functions.

4.4.1.1. global_var = 10 # Global variable def example(): local_var = 5 # Local variable print(global_var)

5. Object-Oriented Programming (OOP)

5.1. a. Classes and Objects

5.1.1. Create classes with the class keyword and instantiate objects.

5.1.1.1. class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name}.") p = Person("Alice", 25) p.greet()

5.2. b. Inheritance

5.2.1. A class can inherit methods and attributes from another class.

5.2.1.1. class Student(Person): def __init__(self, name, age, grade): super().__init__(name, age) self.grade = grade def greet(self): print(f"Hello, I am {self.name} and I am in grade {self.grade}.") s = Student("Bob", 20, "A") s.greet()

5.3. c. Encapsulation

5.3.1. Control access to class variables using methods.

5.3.1.1. class BankAccount: def __init__(self, balance): self.__balance = balance # Private variable def deposit(self, amount): self.__balance += amount def get_balance(self): return self.__balance account = BankAccount(100) account.deposit(50) print(account.get_balance())

5.4. d. Polymorphism

5.4.1. Ability for different classes to be treated as instances of the same class through inheritance.

5.4.1.1. class Animal: def speak(self): pass class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" animals = [Dog(), Cat()] for animal in animals: print(animal.speak())

5.5. e. Abstraction

5.5.1. Hiding complex implementation and exposing only necessary details.

5.5.1.1. from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2

6. 6. Exception Handling

6.1. a. Try, Except, Finally

6.1.1. Handle errors gracefully using try, except, and finally.

6.1.1.1. try: num = int(input("Enter a number: ")) except ValueError: print("That's not a number!") finally: print("Execution finished.")

6.2. b. Custom Exceptions

6.2.1. You can define custom exceptions.

6.2.1.1. class CustomError(Exception): pass try: raise CustomError("Something went wrong!") except CustomError as e: print(e)

7. 7. File Handling

7.1. a. Reading and Writing Files

7.1.1. Open files using open(), and use methods like .read(), .write(), and .close().

7.1.1.1. with open("file.txt", "w") as file: file.write("Hello, World!") with open("file.txt", "r") as file: content = file.read() print(content)

7.2. b. Working with Directories

7.2.1. You can use os and pathlib to interact with directories.

7.2.1.1. import os os.mkdir("new_directory")

8. 8. Modules and Packages

8.1. a. Importing Modules

8.1.1. Use import to include external modules.

8.1.1.1. import math print(math.sqrt(16))

8.2. b. Creating Modules

8.2.1. You can create your own modules by saving functions or classes in .py files.

8.2.1.1. # my_module.py def greet(): print("Hello from my_module!")

8.3. c. Packages

8.3.1. Organize related modules into directories (packages). Create an __init__.py file to mark a directory as a package.

9. 9. Advanced Topics

9.1. A function that modifies the behavior of another function.

9.1.1. def decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @decorator def say_hello(): print("Hello!") say_hello()

9.2. b. Generators

9.2.1. Functions that yield values one at a time using yield.

9.2.1.1. def count_up_to(limit): count = 1 while count <= limit: yield count count += 1

9.3. c. Context Managers

9.3.1. Handle resources (like files) efficiently using with.

9.3.1.1. with open("file.txt", "r") as file: content = file.read()

10. z