Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Python Syntax Essentials | Getting Started with Python
Introduction to Python

bookPython Syntax Essentials

Swipe um das Menü anzuzeigen

hello.py

hello.py

hello.java

hello.java

hello.js

hello.js

copy
Note
The Importance of Indentation in Python

Unlike many other programming languages that use braces {} or keywords to define code blocks, Python uses indentation (spaces or tabs at the beginning of a line) to indicate a block of code. This means that the way you indent your code directly affects how Python interprets and executes it. Incorrect indentation will lead to errors or unexpected behavior. Consistent indentation is essential for defining structures like functions, loops, and conditional statements, making your code both readable and syntactically correct.

Comments and Whitespace in Python

Proper use of comments and whitespace is essential for writing clear and readable Python code.

Comments

Comments are lines in your code that are ignored by the Python interpreter. They are used to explain what the code does, making it easier for others (and your future self) to understand your logic. In Python, comments start with the # symbol:

# This is a single-line comment
x = 5  # This is an inline comment

Python does not have a specific syntax for multi-line comments, but you can use several single-line comments in a row:

# This is a comment
# that spans multiple lines

Alternatively, multi-line strings (triple quotes) can be used as docstrings for documentation, but they are not true comments:

"""
This is a docstring, often used
to describe modules, classes, or functions.
"""

Whitespace

Whitespace refers to any space, tab, or newline in your code. In Python, whitespace is significant and affects how code is interpreted. Proper use of whitespace improves code readability and structure.

  • Indentation: Python uses indentation (spaces or tabs at the beginning of a line) to define code blocks. Consistent indentation is required.
  • Blank Lines: Use blank lines to separate logical sections of code, making it easier to read.
  • Spacing Around Operators: Adding spaces around operators and after commas improves clarity.

Example:

# Good use of whitespace
if x > 0:
    print("Positive number")

# Less readable
if(x>0):print("Positive number")

By using comments to explain your code and whitespace to structure it, you make your programs easier to read, maintain, and debug.

question mark

Which of the following code snippets is syntactically correct in Python?

Select the correct answer

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 3

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 3
some-alt