Skip to main content
Published / updated

Python Setup and Basics

Before you start

You need: nothing. No programming background assumed.

You need installed: Python 3.12 and VS Code with the Python extension. On Windows, tick Add python.exe to PATH in the installer — missing it causes most first-day problems.

Time: about 45 minutes, plus the practice.

New to all of this? Start here explains what an application is made of and introduces the school system every example uses. Any word you do not recognise is in the glossary.

Learning objective

Install Python, run a program three different ways, and write correct code using variables, types and operators.

Topics

  • What Python is used for
  • Installing Python and VS Code
  • Running code
  • Variables and naming
  • Types and conversion
  • Operators
  • Strings and f-strings
  • Input and output
  • Comments and style

What Python is for

Python is a general-purpose language used across automation, scripting, data work, backend APIs and machine learning. It reads close to English, has an enormous standard library, and needs no compilation step.

This track builds a standalone foundation: programming, small applications, file processing, and an introductory FastAPI backend. It is not a machine-learning course.

PythonC#
TypingDynamic, optional hintsStatic, enforced
CompilationInterpretedCompiled
BlocksIndentationBraces
Namingsnake_casePascalCase / camelCase
Runs onAnything.NET runtime

Coming from C#, the two adjustments are indentation as syntax and no compile-time type checking.

Installing

Download from python.org — version 3.12 or later.

On Windows, tick "Add python.exe to PATH" during installation. Without it, python is not recognised in a terminal, which is the first problem most people hit.

python --version # Windows
python3 --version # macOS and Linux

macOS ships an old Python 2-era binary as python. Always use python3 there.

Install VS Code and the Python extension from Microsoft. It provides IntelliSense, debugging, formatting and the interpreter selector.

Ctrl+Shift+P → Python: Select Interpreter tells VS Code which Python to use. When code runs in the terminal but VS Code reports import errors, this is why.

Running code

# A file
python hello.py

# The interactive REPL — for trying one expression
python
>>> 2 + 2
4
>>> exit()

# A one-liner
python -c "print('Hello')"

In VS Code, F5 runs with the debugger and Ctrl+F5 without. Use F5 — breakpoints are the point.

# hello.py
print("Hello from NexCoding Academy")

Variables

student_name = "Ravi Kumar"
roll_number = "NCA-2024-0012"
marks_obtained = 87
percentage = 87.5
is_active = True
address = None

No declaration keyword and no type annotation required. A variable exists once assigned.

Names are snake_case — this is not a preference, it is what every Python codebase uses. studentName marks code as written by someone who has not read the style guide.

MAX_MARKS = 100 # a constant, by convention — Python does not enforce it
_internal_cache = {} # leading underscore means "internal"
class_ = "10th" # trailing underscore avoids a keyword clash

Reassignment can change the type, which is the cost of dynamic typing:

value = 87
value = "eighty-seven" # legal, and a source of bugs

Type hints document intent and are checked by tools, not at run time:

student_name: str = "Ravi Kumar"
marks_obtained: int = 87

Use them. They cost nothing, make editors far more useful, and mypy catches real errors before they run.

Types

name = "Ravi Kumar" # str
marks = 87 # int
percentage = 87.5 # float
is_active = True # bool
address = None # NoneType

type(marks) # <class 'int'>
isinstance(marks, int) # True
TypeNotes
intUnlimited size — no overflow
float64-bit, same precision problems as everywhere
strImmutable, Unicode
boolTrue / False — capitalised
NoneThe absence of a value

True and False are capitalised. Lowercase true is a NameError.

int has no size limit:

2 ** 100 # 1267650600228229401496703205376

Floats and money

0.1 + 0.2 # 0.30000000000000004
0.1 + 0.2 == 0.3 # False

Same binary floating-point problem as C# and JavaScript. Never use float for money:

from decimal import Decimal

total = Decimal("50000.00")
paid = Decimal("8000.50")
outstanding = total - paid # Decimal('41999.50') — exact

Construct Decimal from a string, not a float — Decimal(0.1) carries the float's error into it.

Conversion

int("87") # 87
int(87.9) # 87 — truncates, does not round
float("87.5") # 87.5
str(87) # "87"
bool(0) # False
bool("") # False
bool("0") # True — a non-empty string

int("abc") # ValueError
int("") # ValueError

int() truncates. Use round() when you mean to round — and note it uses banker's rounding, so round(2.5) is 2, not 3.

Conversion of untrusted input needs a guard:

raw = input("Marks: ")

try:
marks = int(raw)
except ValueError:
print("Please enter a whole number.")

Operators

7 + 3 # 10
7 - 3 # 4
7 * 3 # 21
7 / 3 # 2.3333333333333335 — always a float
7 // 3 # 2 — floor division
7 % 3 # 1
7 ** 3 # 343

-7 // 2 # -4 — floors toward negative infinity, not toward zero
-7 % 2 # 1 — the sign follows the divisor

/ always produces a float, even for 6 / 3. Use // when you want an integer.

The negative behaviour differs from C#, where -7 / 2 is -3 and -7 % 2 is -1. It catches people writing index arithmetic.

marks == 87
marks != 87
35 <= marks <= 100 # chained — reads as it means

is_active and has_paid
is_active or has_paid
not is_active

"Kumar" in student_name
"x" not in student_name

a is None # identity — the correct None test
a == None # works, but not idiomatic

Chained comparison is a genuine Python advantage. 35 <= marks <= 100 is one expression, not two joined by and.

Use is None, never == None. is compares identity; a class can override == and produce a surprising answer.

and and or return an operand, not a boolean:

name = user_name or "Guest" # "Guest" when user_name is falsy

Handy, and a trap when 0 or "" are valid values — the same problem as || in JavaScript.

Truthiness

Falsy: False, None, 0, 0.0, "", [], {}, (), set().

if students: # non-empty list
if not students: # empty list
if marks: # WRONG when 0 marks is valid
if marks is not None: # correct

if marks: treats a genuine 0 as missing. Test for None explicitly whenever zero is a legitimate value — the same absent-versus-zero bug as everywhere else in this curriculum.

Strings

name = "Ravi Kumar"
name = 'Ravi Kumar' # identical
text = """Multi-line
string"""
name.upper() # "RAVI KUMAR"
name.lower()
name.title() # "Ravi Kumar"
name.strip() # remove surrounding whitespace
name.replace("Ravi", "Rav")
name.split(" ") # ["Ravi", "Kumar"]
"-".join(["NCA", "2024", "0012"])
name.startswith("Ravi")
name.find("Kumar") # index, or -1
len(name)

Strings are immutable. Every method returns a new string; none modifies in place.

name[0] # "R"
name[-1] # "r" — last character
name[0:4] # "Ravi"
name[:4] # "Ravi"
name[5:] # "Kumar"
name[::-1] # reversed

Negative indexing and slicing are used constantly in Python. [-1] for the last item is idiomatic.

f-strings

name = "Ravi Kumar"
marks = 87
percentage = 87.5

print(f"{name} scored {marks}")
print(f"Percentage: {percentage:.1f}%")
print(f"Total: {50000:,}")
print(f"{name:>20}") # right-aligned in 20 characters
print(f"{marks / 100:.1%}") # 87.0%
print(f"{name=}, {marks=}") # debugging: name='Ravi Kumar', marks=87

f-strings are the only string formatting to use in new code. % formatting and .format() appear in older code and are strictly worse.

{value=} prints both the expression and its value — the fastest debugging aid Python has.

Expressions work inside the braces:

print(f"Grade: {'Pass' if marks >= 35 else 'Fail'}")

Input and output

name = input("Student name: ")
raw_marks = input("Marks obtained: ")

input() always returns a string. Comparing it to a number silently fails:

marks = input("Marks: ")

if marks > 35: # TypeError: '>' not supported between 'str' and 'int'
...
raw = input("Marks: ").strip()

if not raw.isdigit():
print("Please enter a whole number.")
else:
marks = int(raw)

.strip() removes the trailing whitespace users paste in.

print("Ravi Kumar")
print("Name:", name, "Marks:", marks) # spaces between arguments
print("Ravi", "Kumar", sep="-") # Ravi-Kumar
print("Loading", end="") # no newline
print(f"{'Name':<20}{'Roll':<15}{'Marks':>6}") # aligned columns

sep and end control the separator and the line ending. end="" is how you build a progress line.

Comments and style

# A single-line comment

def calculate_percentage(marks_obtained: int, max_marks: int) -> float:
"""Return the percentage for the given marks.

Raises:
ValueError: if max_marks is not positive.
"""
if max_marks <= 0:
raise ValueError("max_marks must be positive")

return (marks_obtained / max_marks) * 100

A docstring is the first statement in a module, function or class. Tools and help() read it; a # comment above the function does not.

Python has no block comment. Consecutive # lines are the convention.

PEP 8

The style guide every Python codebase follows:

  • 4 spaces for indentation, never tabs
  • snake_case for variables and functions
  • PascalCase for classes
  • UPPER_CASE for constants
  • Lines up to 79 characters (88 with Black)
  • Two blank lines between top-level definitions
pip install black ruff
black student_records.py # formats
ruff check student_records.py # lints

Use a formatter from day one. Black reformats to one canonical style, so formatting stops being a discussion.

Indentation

Indentation is syntax, not style.

if marks >= 35:
print("Pass")
print("Well done")
print("Always runs")
if marks >= 35:
print("Pass") # IndentationError

Mixing tabs and spaces gives TabError. Configure your editor to insert spaces and the problem disappears.

An empty block needs pass:

def not_implemented_yet():
pass

Errors you will hit

MessageCauseFix
'python' is not recognizedNot on PATHReinstall with the PATH box ticked; reopen the terminal
IndentationError: unexpected indentMixed tabs and spaces, or wrong levelUse four spaces; VS Code can convert
SyntaxError: invalid syntax pointing at a fine lineMissing bracket or colon on the line aboveLook at the previous line
NameError: name 'x' is not definedTypo, or used before assignmentCheck spelling and order
TypeError: can only concatenate str (not "int") to strMixed types with +Convert with str() or use an f-string
VS Code cannot find a module you installedWrong interpreter selectedCtrl+Shift+P → Python: Select Interpreter

The interpreter selection is the single most common VS Code Python problem. The package is installed — just not in the environment VS Code is using.

Common mistakes

  • Not adding Python to PATH on Windows
  • Using python instead of python3 on macOS
  • The wrong interpreter selected in VS Code
  • true instead of True
  • camelCase instead of snake_case
  • Comparing input() output to a number
  • float for money
  • Decimal(0.1) instead of Decimal("0.1")
  • if marks: where 0 is valid
  • == None instead of is None
  • Expecting / to give an integer
  • Expecting int() to round
  • Mixing tabs and spaces
  • % or .format() instead of f-strings
  • No formatter or linter

Practice

The course exercise is solve logic problems.

  1. Install Python and confirm the version in a terminal. Select the interpreter in VS Code.
  2. Write and run hello.py three ways: file, REPL, and python -c.
  3. Write a program taking a student's name, marks and max marks, and printing the percentage to one decimal place with an f-string.
  4. Compare input() output to a number without converting. Record the TypeError.
  5. Enter abc where a number is expected. Record the ValueError, then guard with .isdigit().
  6. Print 0.1 + 0.2. Then compute a fee total with Decimal and compare.
  7. Construct Decimal(0.1) and Decimal("0.1") and print both.
  8. Write if marks: with marks of 0. Confirm the bug, then use is not None.
  9. Evaluate 7 / 3, 7 // 3, -7 // 2 and -7 % 2. Explain each.
  10. Use chained comparison to check a mark is between 35 and 100.
  11. Slice a roll number into school code, year and sequence.
  12. Print a formatted table of three students with aligned columns.
  13. Use {value=} to debug a calculation.
  14. Deliberately mis-indent a block and read the IndentationError.
  15. Run black and ruff on your file and fix what they report.

Exercises 6 and 8 correspond to two bugs that reach production.

You can now

  • Install Python and run a script from VS Code
  • Select the right interpreter and say why it matters
  • Write correct variables, types and expressions
  • Read a traceback and find the line
  • Fix an IndentationError

Review questions

  1. Why must money use Decimal rather than float?
  2. What does input() always return, and what does that break?
  3. Why is if marks: wrong when zero marks is valid?
  4. What is the difference between / and //?

Next: Control flow