Basic Syntax in Python

The syntax of Python refers to the rules and structure of the language, dictating how Python code must be written to ensure it is valid. Here are key elements of Python’s basic syntax:


1. Case Sensitivity

  • Python is case-sensitive, meaning Name and name are treated as two different variables.

2. Writing the First Program

  • A simple “Hello, World!” program looks like this: print("Hello, World!")
  • The print() function is used to display output on the screen.

3. Indentation

  • Python uses indentation (spaces or tabs at the beginning of a line) to define blocks of code, such as loops, functions, and conditionals.
  • Example: if 5 > 3: print("5 is greater than 3")
  • Incorrect indentation will result in an IndentationError.

4. Comments

  • Comments are used to explain the code and are ignored by the interpreter.
  • Single-line comments:# This is a comment print("Hello, Python!") # This prints a message
  • Multi-line comments:""" This is a multi-line comment. It spans multiple lines. """

5. Variables

  • Variables are used to store data and are created when you assign a value: x = 10 # Integer y = 3.14 # Float name = "Alice" # String
  • No need to declare variable types explicitly—Python infers the type automatically.

6. Statements

  • Each instruction is usually written on a new line:pythonCopy codeprint("Line 1") print("Line 2")
  • For multiple statements on a single line, use a semicolon (;):x = 5; y = 10; print(x + y)

7. Dynamic Typing

  • Python does not require you to specify the data type of a variable. The type is determined automatically: a = 10 # Integer b = "Hello" # String

8. No Need for Semicolons

  • Unlike many other languages, Python does not require semicolons to terminate a statement. However, they can be used optionally: print("Hello")

9. Line Continuation

  • To extend a single statement over multiple lines, use a backslash (\):total = 10 + 20 + 30 + \ 40 + 50
  • Alternatively, parentheses can also be used for readability: total = (10 + 20 + 30 + 40 + 50)

CATEGORIES:

BASICS

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *