Welcome to the third topic in our Python journey! In this tutorial, we will dive into the fundamental syntax rules of Python. Understanding these rules is crucial as they form the building blocks for writing clear and error-free code. We'll cover indentation, case sensitivity, line continuation, and finally, how to write your very first complete Python program.
Python uses indentation to define the scope in the code. Unlike languages that use curly braces {} or keywords like begin/end, Python relies on consistent indentation (usually 4 spaces) to group statements. This rule is enforced by the Python interpreter, and not following it will result in a syntax error.
Example:
1if True:2print("This is indented")3print("This is not indented")
10 20
Best Practice: Use a consistent naming convention to avoid confusion. For variables and functions, use snake_case, and for classes, use PascalCase.
Python allows you to continue long statements over multiple lines using parentheses (), brackets [], or braces {}. This is particularly useful when dealing with complex expressions.
Example:
1total = (1 + 2 +23 + 4)3print(total) # Output: 10
The sum of 5 and 3 is 8
Explanation:
num1 and num2 with values 5 and 3, respectively.sum.print() function.Let's expand our first program to include user input. The program will ask the user for two numbers and then display their sum.
Example:
1# This is a simple calculator program with user input2num1 = float(input("Enter the first number: "))3num2 = float(input("Enter the second number: "))45# Adding two numbers6sum = num1 + num278# Printing the result9print("The sum of", num1, "and", num2, "is", sum)
$ python3 practical_example.pyEnter the first number: 7.5Enter the second number: 4.2The sum of 7.5 and 4.2 is 11.7
The sum of 7.5 and 4.2 is 11.7
Explanation:
input() function to get user input, which returns a string by default.float() so that we can perform arithmetic operations.| Concept | Description |
|---|---|
| Indentation | Python uses indentation (4 spaces) to define code blocks. |
| Case Sensitivity | Python is case-sensitive; variable names with different cases are distinct. |
| Line Continuation | Statements can be continued over multiple lines using parentheses, brackets, or braces. |
| First Program | A simple calculator program that adds two numbers and prints the result. |
Now that you have a solid understanding of Python syntax and how to write your first program, it's time to explore comments and keywords in Python. In the next topic, we'll learn about different types of comments and reserved words in Python, which will help you write more readable and structured code.
Stay tuned for the next tutorial!