PYTHON

Basic syntax and structure


Basics of Python syntax and structure.

  • Printing to the screen
  • Variables and data types
  • Comments
  • Basic arithmetic operations
  • Control structures (if-else)
  • Loops (for and while)
  • Functions

1. Printing to the Screen

To display text or variables on the screen, use the print() function.

print("Hello, World!")

2. Variables and Data Types

Variables are used to store data. You don't need to declare the type; Python figures it out based on the value.

name = "Rohit"        # String
age = 25              # Integer
height = 5.9          # Float
is_student = True     # Boolean

 

3. Comments

Comments are used to explain code and are ignored by the Python interpreter. Use # for single-line comments and ''' or """ for multi-line comments.

# This is a single-line comment
"""
This is a
multi-line comment
"""

 

4. Basic Arithmetic Operations

You can perform arithmetic operations like addition, subtraction, multiplication, and division.

a = 10
b = 5
sum = a + b         # Addition
difference = a - b  # Subtraction
product = a * b     # Multiplication
quotient = a / b    # Division

 

5. Control Structures (if-else)

Use if, elif, and else to execute code based on conditions.

x = 10
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

 

6. Loops

i.) For Loop

A for loop is used to iterate over a sequence (like a list, tuple, or string).

for i in range(5):
    print(i)  # Prints numbers from 0 to 4

2.) While Loop

A while loop repeats as long as a condition is true.

count = 0
while count < 5:
    print(count)
    count += 1  # Increments count by 1

 

7. Functions

Functions are blocks of code that perform a specific task. Define a function using def, followed by the function name and parentheses.

def greet(name):
    print("Hello, " + name + "!")
greet("Rohit")

That's a basic overview of Python syntax and structure.


PYTHON