LearnFrenzy
Sign in Take a free test

Python Programming · Topic 1 of 25

Python Basics and Syntax Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Python Basics and Syntax · Study material

Python is the language most students write their first program in – and the one data scientists, AI engineers, testers and DevOps teams use every day. Its syntax is short and readable: no semicolons, no braces, no type declarations. But that simplicity hides rules that written tests love to ask about: indentation defines blocks, input() always returns text, print() has sep and end, and a file behaves differently when it is imported. This topic covers how Python runs, its syntax rules, and basic input and output. Then test yourself with 50 practice questions – 15 MCQs, 15 predict-the-output puzzles, 10 find-the-error programs and 10 coding problems – every one run on Python 3. Each example below has a Run button: try it in your browser, change it, and run it again.

On this page

  • How Python runs: source → bytecode → Python virtual machine
  • Indentation and blocks
  • print() with sep and end, and input()
  • Statements, semicolons and line continuation
  • Comments, docstrings, identifiers and keywords
  • f-strings, type() and the __name__ == "__main__" guard

How a Python program runs

You write hello.py and run python hello.py. The standard interpreter, CPython, first compiles the whole file to bytecode (that is when syntax errors are found – before a single line runs), then its virtual machine executes the bytecode statement by statement. Bytecode of imported modules is cached in __pycache__/*.pyc files so the next start is faster. Typing python alone opens the REPL (the >>> prompt), which runs each line as you type it – perfect for quick experiments.

TermWhat it is
CPythonthe reference interpreter, written in C – what you install from python.org
Bytecodecompact instructions the Python virtual machine executes; cached as .pyc
REPLRead–Eval–Print Loop: the interactive >>> prompt
Scripta .py file run directly
Modulea .py file imported by another file
PyPy, Jython, MicroPythonother implementations of the same language

A program needs no class and no main(): statements run from the top of the file to the bottom.

# A Python program is just statements, run from top to bottom – no class or main() needed
print("Hello, LearnFrenzy!")          # print() writes a line and adds a newline
print("Python", 3, "is", "fun")       # several values: separated by a space
language = "Python"                   # a variable is created by assigning to it
print("I am learning", language)

Output

Hello, LearnFrenzy!
Python 3 is fun
I am learning Python

Indentation defines blocks

Where C, C++ and Java use braces, Python uses a colon followed by an indented block. Every line of the block must be indented by the same amount – PEP 8, Python's style guide, says 4 spaces. A missing indent raises IndentationError: expected an indented block; an extra one raises IndentationError: unexpected indent; mixing tabs and spaces inconsistently raises TabError.

marks = 72

# The colon starts a block; the indented lines (4 spaces) belong to it
if marks >= 40:
    print("Passed")
    print("Well done")      # still inside the if-block
else:
    print("Try again")

print("Result printed")     # back at the left margin: runs in every case

Output

Passed
Well done
Result printed

Output with print()

print(*values, sep=' ', end='\n') converts each value to text, puts sep between them and end after the last one. Change end to keep printing on the same line; change sep to join values with a different separator.

print("2026", "11", "30", sep="-")        # sep goes BETWEEN the values
print("Loading", end="...")               # end replaces the newline
print("done")
print("a", "b", "c", sep="")              # no separator at all
print()                                   # an empty line
print("Total:", 450, "rupees", sep=" | ")

Output

2026-11-30
Loading...done
abc

Total: | 450 | rupees

Input with input()

input(prompt) prints the prompt (without a newline), reads one line from the keyboard and returns it as a string, without the trailing newline. To do arithmetic, convert it first with int() or float(). In the run below, the typed lines "Asha" and "20" do not appear in the output – only the prompts do.

name = input("Your name: ")         # the prompt is printed, then one line is read
age = input("Your age: ")           # input() ALWAYS returns a str
print(type(age))
age = int(age)                      # convert before doing arithmetic
print(f"{name} will be {age + 1} next year")

Input

Asha
20

Output

Your name: Your age: <class 'str'>
Asha will be 21 next year

Statements, semicolons and line continuation

One statement per line is the norm. A semicolon allows several statements on one line, but PEP 8 discourages it. A long statement can continue on the next line implicitly inside parentheses, brackets or braces (preferred), or explicitly with a backslash at the very end of the line.

a = 10; b = 20; c = a + b            # semicolons: several statements on one line (legal, but avoid)

# Inside (), [] or {} a statement may run over several lines
total = (a +
         b +
         c)

# A backslash at the end of a line also continues it
average = total \
          / 3

print(c, total, average)

Output

30 60 20.0

Comments, docstrings, identifiers and keywords

A # starts a comment that runs to the end of the line. Python has no multi-line comment syntax: use several # lines. A string literal written as the first statement of a module, function or class is its docstring, stored in __doc__ and shown by help().

Identifiers (names) may contain letters, digits and underscores, cannot start with a digit, are case-sensitive (total, Total and TOTAL are three names) and cannot be one of the 35 keywords such as if, class, def, None, True and False. print, input and list are not keywords – they are built-in functions, so you can reassign them (and then lose them), which is a classic bug. PEP 8 names: snake_case for variables and functions, PascalCase for classes, UPPER_CASE for constants.

f-strings and type()

An f-string (f"...") evaluates the expressions inside { } and inserts their values; a format spec after a colon controls decimals, width and alignment. type(x) tells you what kind of object a value is.

item, qty, price = "Notebook", 3, 45.5

print(f"{qty} x {item} = {qty * price}")       # any expression inside { }
print(f"Price: {price:.2f} | Qty: {qty:03d}")   # format specs after a colon
print(f"{item:<10}|{item:>10}|")                # left / right align in 10 characters
print(type(qty), type(price), type(item))
print(type(print))                              # even functions are objects

Output

3 x Notebook = 136.5
Price: 45.50 | Qty: 003
Notebook  |  Notebook|
<class 'int'> <class 'float'> <class 'str'>
<class 'builtin_function_or_method'>

The if __name__ == "__main__" guard

Every module has a __name__. When a file is run directly it is "__main__"; when it is imported, it is the module's own name. Putting the program's start under this guard lets the same file be run as a script and imported for its functions without the program running on import.

"""Module docstring: what this file does."""


def greet(name):
    """Return a greeting for name."""      # a function docstring
    return f"Hello, {name}!"


def main():
    print(greet("Ravi"))
    print(greet.__doc__)


# True when the file is run directly; False when another file imports it
if __name__ == "__main__":
    main()

Output

Hello, Ravi!
Return a greeting for name.

Common mistakes

  • Inconsistent indentation – IndentationError or TabError; configure your editor to insert 4 spaces.
  • Forgetting the colon after if, for, def, class – SyntaxError.
  • Doing arithmetic on input() – input() + 1 is a TypeError; input() + input() joins text.
  • Python 2 habits – print "hi" is a SyntaxError in Python 3.
  • Wrong case – Print and True vs true: names are case-sensitive.
  • Naming a variable list, str or input – it hides the built-in for the rest of the program.

Key points to remember

  • CPython compiles the file to bytecode first, so syntax errors stop the program before anything runs.
  • A colon plus consistent indentation (4 spaces) forms a block.
  • print() puts sep between values and end after them (defaults: a space and a newline).
  • input() always returns a str.
  • Implicit continuation inside brackets is preferred over a backslash.
  • # starts a comment; a first-statement string is a docstring.
  • Run-directly code goes under if __name__ == "__main__":.

Frequently asked questions

Is Python compiled or interpreted?

Both, in a sense: CPython compiles source code to bytecode, and a virtual machine interprets that bytecode. There is no separate compile step you run yourself, which is why Python is usually called interpreted.

Python 2 or Python 3?

Python 3 only. Python 2 reached end of life in January 2020. Everything on LearnFrenzy uses Python 3.

Can I use tabs instead of spaces?

Python accepts either inside a block as long as you are consistent, but mixing them is an error and PEP 8 recommends 4 spaces. Every modern editor can insert spaces when you press Tab.

Where can I learn more?

Read Your First Python Program, Python Input and Output and Python Variables in the Python tutorial, or open the online Python compiler and practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links