Python Fundamentals
What Python is, how to install it and run your first program, plus the core building blocks — variables, constants, every built-in data type, type conversion, input/output and operators — that every Python program is built from.
Welcome to your first step into Python programming. This file covers everything a beginner needs before writing real programs — what Python is, how to set it up, and the basic building blocks (variables, data types, operators) that every single Python program is made of.
Take your time here. Everything later in this course — loops, functions, OOP, even machine learning — is built on top of what you learn in this file.
1. What is Python?
What is it?
Python is a programming language — a way of giving instructions to a computer using text that follows specific rules (called syntax). It was created by Guido van Rossum and released in 1991.
What makes Python special is how close it reads to plain English. Look at this line:
pythonprint("Hello, World!")
Even someone who has never coded before can guess this line displays the text "Hello, World!" on the screen. That readability is Python's biggest strength.
Python is used everywhere today — websites, mobile app backends, data analysis, artificial intelligence, automation scripts, games, and even software that controls hardware. It is one language that can do almost everything a beginner or a professional developer needs.
Why do we use it?
We use Python because:
- It's easy to learn — the syntax is simple and readable.
- It's versatile — one language for web apps, data science, AI, scripting, automation, and more.
- It has a huge community — if you get stuck, someone has probably already asked (and answered) your question online.
- It has thousands of ready-made libraries — pre-written code you can just import and use instead of writing everything from scratch.
- It's in high demand — Python is consistently one of the top languages companies hire for.
How does it work?
Python is an interpreted language. This means you don't need to "convert" your code into a separate program before running it (unlike languages like C or Java, which need a compilation step). Instead, a program called the Python interpreter reads your code line by line and executes it directly.
This makes Python great for beginners — write a line, run it, see the result immediately.
Real-World Example
- Instagram's backend uses Python (via Django).
- YouTube used Python extensively in its early infrastructure.
- Data scientists use Python daily with libraries like Pandas and NumPy.
- Companies use Python scripts to automate boring repetitive tasks like renaming thousands of files or sending scheduled emails.
Important Points
- Python is beginner-friendly but powerful enough for large-scale professional software.
- Python code is interpreted, not compiled like C/C++.
- Python is open-source and free to use.
- Python works on Windows, macOS, and Linux.
2. Why is Python Popular? (Features of Python)
Here are the core features that explain Python's popularity:
| Feature | What it Means |
|---|---|
| Simple & Readable Syntax | Code looks close to English, easy to understand |
| Interpreted | Runs line-by-line, no separate compile step needed |
| Dynamically Typed | You don't need to declare a variable's type in advance |
| Free & Open Source | Anyone can use and modify Python for free |
| Large Standard Library | Comes with built-in tools for many common tasks |
| Huge Ecosystem | Thousands of third-party packages (Flask, Django, NumPy, TensorFlow, etc.) |
| Cross-Platform | Same code runs on Windows, macOS, Linux |
| Community Support | Massive global community, tons of tutorials and forums |
Python Use Cases
- Web Development — Flask, Django, FastAPI
- Data Analysis & Visualization — Pandas, Matplotlib, Seaborn
- Machine Learning & AI — Scikit-learn, TensorFlow, PyTorch
- Automation & Scripting — automating files, emails, Excel sheets
- Web Scraping — collecting data from websites
- Game Development — Pygame
- Software Testing — writing automated test scripts
- Cybersecurity — writing security tools and scripts
Definition: Python is a high-level, interpreted, general-purpose programming language known for its simple syntax and wide range of real-world applications.
3. Installing Python
What is it?
Before writing Python code, you need the Python interpreter installed on your computer — this is the program that actually reads and runs your .py files.
How does it work? (Step-by-Step)
Windows / macOS:
- Go to python.org/downloads
- Download the latest stable version (e.g., Python 3.12+)
- Run the installer.
- Important: On Windows, check the box "Add Python to PATH" before clicking Install.
- After installation, open a terminal (Command Prompt / Terminal) and type:
bashpython --version
Expected Output:
Python 3.12.3If you see a version number, Python is installed correctly.
Linux: Most Linux systems already have Python installed. Check with python3 --version. If missing, install using your package manager, e.g. sudo apt install python3.
Common Mistakes
- Forgetting to check "Add Python to PATH" on Windows, which causes
'python' is not recognizederrors. - Installing Python but running the command
python3when onlypythonwas set up (or vice versa) — try both if one doesn't work. - Not restarting the terminal after installation.
Important Points
- Always install Python 3, not Python 2 (Python 2 is outdated and no longer supported).
python --versionorpython3 --versionconfirms a successful install.- Adding Python to PATH lets you run
pythonfrom any folder in the terminal.
4. The Python Interpreter
What is it?
The Python interpreter is the program that reads your Python code and executes it. There are two main ways to use it:
- Interactive Mode (Python Shell / REPL) — type one line at a time and see instant results. Great for quick testing.
- Script Mode — write code in a
.pyfile and run the whole file at once. This is how real programs are written.
Simple Example — Interactive Mode
Open your terminal and type python (or python3), then try:
python>>> print(2 + 3) 5 >>> name = "Anita" >>> print(name) Anita
Simple Example — Script Mode
Create a file called hello.py with this content:
pythonprint("Hello, World!")
Run it from the terminal:
bashpython hello.py
Output:
Hello, World!Explanation
>>>is the prompt shown in interactive mode — it means Python is waiting for input.- In script mode, you save code in a file and run the entire file with one command — this is what you'll do for almost all real projects.
Important Points
- Use interactive mode for quick experiments.
- Use script mode (
.pyfiles) for actual programs. - File names should end in
.pyand should not contain spaces (use underscores instead, e.g.,my_program.py).
5. Setting Up VS Code for Python
What is it?
VS Code (Visual Studio Code) is a free, popular code editor that makes writing Python much easier — with features like syntax highlighting, auto-completion, and built-in error detection.
How does it work? (Step-by-Step)
- Download VS Code from code.visualstudio.com.
- Install it and open it.
- Go to the Extensions panel (icon on the left sidebar) and search for "Python" (by Microsoft). Click Install.
- Create a folder for your projects, and open it in VS Code (File → Open Folder).
- Create a new file, e.g.
main.py. - Write some code and run it using the Run button (▶) at the top right, or open a terminal inside VS Code (Terminal → New Terminal) and type
python main.py.
Important Points
- The Python extension gives you helpful features like error underlining and auto-suggestions.
- VS Code's built-in terminal lets you run code without switching windows.
- Always save your file (Ctrl+S / Cmd+S) before running it.
6. Your First Python Program
Simple Example
python# This is my first Python program print("Hello, World!")
Output:
Hello, World!Explanation of the Code
- The line starting with
#is a comment — Python ignores it completely. It's just a note for humans reading the code. print()is a built-in function that displays whatever is inside its parentheses on the screen.- The text
"Hello, World!"is called a string — text data, always written inside quotes.
Real-World Example
Every programming language tutorial starts with a "Hello, World!" program because it confirms your setup works and introduces the most basic building block: displaying output.
Practice
- Write a program that prints your own name.
- Write a program that prints three different lines of text using three separate
print()statements.
7. Python Syntax Basics
What is it?
Syntax refers to the set of rules that define how Python code must be written so the interpreter can understand it.
Key Syntax Rules
- Indentation matters. Python uses indentation (spaces at the start of a line) to define blocks of code, instead of curly braces
{}like other languages. Standard practice is 4 spaces per indent level. - No semicolons required. Each line is usually one statement (unlike Java or C which end lines with
;). - Case-sensitive.
Nameandnameare treated as two different things.
Simple Example
pythonage = 20 if age >= 18: print("You are an adult") # this line is indented — part of the "if" block else: print("You are a minor")
Output:
You are an adultCommon Mistakes
- Mixing tabs and spaces for indentation — this causes
IndentationError. Stick to spaces (VS Code does this automatically). - Forgetting the colon
:at the end of lines likeif,for,while, and function definitions. - Inconsistent indentation levels within the same block.
Important Points
- Indentation is not optional in Python — it defines your program's structure.
- 4 spaces is the standard, community-agreed indentation size (PEP 8 style guide).
8. Comments
What is it?
A comment is a line in your code that Python ignores completely. It exists purely to help humans understand the code.
Why do we use it?
- To explain why code does something (not just what it does).
- To temporarily disable a line of code while testing.
- To make code easier for teammates (or future you) to understand.
Syntax
python# This is a single-line comment """ This is a multi-line comment, often called a docstring when used at the top of a function or file. """
Simple Example
python# Calculate the area of a rectangle length = 5 width = 3 area = length * width # multiply length and width print(area)
Output:
15Common Mistakes
- Over-commenting obvious code (e.g.,
x = 5 # set x to 5adds no value). - Under-commenting complex logic that genuinely needs explanation.
- Leaving outdated comments that no longer match the actual code.
Important Points
- Comments start with
#for single lines. - Triple quotes
"""..."""are used for multi-line comments/docstrings. - Good comments explain why, not just what.
Practice
- Write a program with at least 3 comments explaining each step of a simple calculation.
9. Variables
What is it?
A variable is a name that refers to a value stored in the computer's memory. Think of it as a labeled box where you can keep some data and refer to it later using its label (name).
Definition: A variable is a named location used to store data that can be used and changed later in a program.
Why do we use it?
Without variables, you'd have to retype values every single time you need them. Variables let you store a value once and reuse it, update it, or pass it around your program.
How does it work?
In Python, you create a variable simply by assigning a value to a name using =. Python figures out the data type automatically — you don't need to declare it in advance.
Syntax
pythonvariable_name = value
Simple Example
pythonstudent_name = "Rahul" student_age = 21 print(student_name) print(student_age)
Output:
Rahul
21Explanation of the Code
student_name = "Rahul"creates a variable namedstudent_nameand stores the text"Rahul"in it.student_age = 21creates another variable holding the number21.print()displays the current value stored in each variable.
Real-World Example
In a college portal application, variables would store things like student_name, roll_number, marks, or attendance_percentage — each piece of information the program needs to work with.
Rules for Naming Variables
- Must start with a letter or underscore (not a number).
- Can only contain letters, numbers, and underscores (no spaces or special symbols).
- Cannot be a Python keyword (like
if,for,class). - Case-sensitive:
ageandAgeare different variables. - Should be descriptive:
marksis better thanm.
Common Mistakes
- Starting a variable name with a number:
2name = "Aditi"→SyntaxError. - Using spaces in variable names:
student name = "Aditi"→ error. Usestudent_nameinstead. - Using Python keywords as variable names, e.g.
class = "A"→ error. - Forgetting that Python is case-sensitive, causing confusing bugs (
Namevsname).
Important Points
- No need to declare a variable's type — Python infers it automatically.
- A variable's value can be changed anytime by reassigning it.
- Use meaningful, descriptive variable names — this is a core best practice in real jobs.
- By convention, Python variable names use
snake_case(lowercase with underscores), e.g.total_marks.
Practice
- Create variables to store your name, age, and city, then print all three.
- Create a variable
price = 100, then update it to150and print both values (before and after).
10. Constants
What is it?
A constant is a value that is not supposed to change while the program runs — for example, the value of pi, or the number of days in a week.
Why do we use it?
Constants make code more readable and safer. If a special value is used in many places (like a tax rate), giving it a clearly named constant avoids "magic numbers" scattered through the code and mistakes when updating that value later.
How does it work?
Python does not have a built-in way to enforce that a value truly cannot change (unlike some other languages). Instead, Python programmers follow a convention: constant names are written in ALL_CAPS to signal "please don't change this."
Syntax
pythonCONSTANT_NAME = value
Simple Example
pythonPI = 3.14159 GST_RATE = 0.18 radius = 5 area = PI * radius * radius print("Area:", area)
Output:
Area: 78.53975Explanation of the Code
PIis written in capital letters to show it's meant to stay constant.- Nothing technically stops you from changing
PIlater, but by convention, other developers know not to.
Real-World Example
An e-commerce app might define TAX_RATE = 0.18 once at the top of the program and use it everywhere tax needs to be calculated, instead of typing 0.18 repeatedly.
Common Mistakes
- Assuming Python actually prevents changing a constant's value — it doesn't; it's only a naming convention.
- Not using ALL_CAPS, which makes it hard for others to recognize a value is meant to be constant.
Important Points
- Python has no real "constant" keyword — it's purely a naming convention (ALL_CAPS).
- Constants are usually defined once, near the top of a file.
- Common examples:
PI,MAX_USERS,TAX_RATE.
Practice
- Define a constant
SPEED_OF_LIGHT = 299792458and use it in a simple calculation.
11. Data Types in Python
Python has several built-in data types. We'll cover each one separately, since each behaves differently.
11.1 Integers (int)
What is it? Whole numbers, without a decimal point — positive, negative, or zero.
Syntax & Example:
pythonage = 25 temperature = -5 print(age, temperature)
Output:
25 -5Real-World Example: Counting items in a cart, storing someone's age, storing a bank account number.
Common Mistakes: Writing numbers with commas like 1,000 (invalid in Python) — use 1000 or 1_000 instead.
Important Points:
- No size limit — Python integers can be arbitrarily large.
- Check type using
type(age)→<class 'int'>.
11.2 Floating-Point Numbers (float)
What is it? Numbers that contain a decimal point — used for values needing fractional precision.
Syntax & Example:
pythonprice = 99.99 pi_value = 3.14 print(price, pi_value)
Output:
99.99 3.14Real-World Example: Product prices, temperature readings, GPA/percentage calculations.
Common Mistakes: Expecting floats to be perfectly precise — due to how computers store decimals, 0.1 + 0.2 gives 0.30000000000000004, not exactly 0.3. This is normal and expected in almost every programming language.
Important Points:
- Use
round(value, 2)to round a float to 2 decimal places when needed. - Type check:
type(price)→<class 'float'>.
11.3 Complex Numbers (complex)
What is it? Numbers with a real and an imaginary part, written as a + bj. Mostly used in scientific/engineering calculations — rare in everyday beginner programs, but good to know it exists.
Syntax & Example:
pythonz = 3 + 4j print(z) print(z.real) print(z.imag)
Output:
(3+4j)
3.0
4.0Important Points:
jrepresents the imaginary unit in Python (instead ofiused in math).- Rarely used outside scientific computing.
11.4 Strings (str)
What is it? Text data — any sequence of characters, written inside quotes.
Syntax & Example:
pythonname = "Priya" message = 'Hello there!' print(name) print(message)
Output:
Priya
Hello there!Real-World Example: Names, addresses, messages, product descriptions — almost every app deals with text.
Common Mistakes:
- Forgetting to close a quote:
name = "Priya→SyntaxError. - Mixing quote types incorrectly:
'Hello"→ error.
Important Points:
- Both single
'...'and double"..."quotes work the same way — pick one style and stay consistent. - Strings are covered in much more depth in the dedicated Strings file (03-strings equivalent, file 05 in our roadmap).
11.5 Boolean (bool)
What is it? A data type with only two possible values: True or False. Used to represent yes/no, on/off type decisions.
Syntax & Example:
pythonis_student = True is_working = False print(is_student) print(10 > 5)
Output:
True
9 > 5 evaluates to: True(Note: `10 > 5` prints as `True`)
Real-World Example: is_logged_in, is_available, has_paid — booleans drive almost every decision (if) in real programs.
Common Mistakes: Writing true/false in lowercase — Python requires True/False with a capital first letter.
Important Points:
Truebehaves like1andFalsebehaves like0in calculations.- Type check:
type(is_student)→<class 'bool'>.
11.6 None
What is it? A special value representing "nothing" or "no value assigned yet." It is Python's way of saying "empty" — different from 0, False, or an empty string "".
Syntax & Example:
pythonresult = None print(result)
Output:
NoneReal-World Example: A variable to hold a search result before the search has actually run, or a user's middle name field if they didn't provide one.
Common Mistakes: Confusing None with 0 or False — they are different types entirely (None means "no value," not "zero" or "false").
Important Points:
Noneis its own data type (NoneType).- Commonly used as a default/placeholder value.
- Check with
if result is None:(useis, not==, when comparing toNone— this is a Python best practice).
Comparison Table — Data Types at a Glance
| Type | Example | Use Case |
|---|---|---|
int | 25 | Counting, whole numbers |
float | 99.99 | Prices, measurements |
complex | 3+4j | Scientific/engineering math |
str | "Hello" | Text |
bool | True | Yes/no decisions |
NoneType | None | Absence of a value |
Practice
- Create one variable of each data type covered above and print each one along with its type using
type(). - What is the difference between
Noneand0? Write one sentence explaining it.
12. Type Conversion
What is it?
Type conversion (also called type casting) means converting a value from one data type to another — for example, turning the text "25" into the number 25.
Why do we use it?
Data often arrives in the "wrong" type for what you need. For instance, input from a user always arrives as a string, even if it looks like a number — you must convert it to int or float before doing math with it.
How does it work?
Python provides built-in functions for conversion: int(), float(), str(), bool().
Simple Example
pythonage_text = "25" # this is a string age_number = int(age_text) # convert to integer print(age_number + 5) print(type(age_number))
Output:
30
<class 'int'>Explanation of the Code
age_textholds the string"25"— you cannot do math directly on it.int(age_text)converts it into the actual number25.- Now
age_number + 5works correctly and gives30.
More Examples
pythonprint(float("3.14")) # "3.14" -> 3.14 print(str(100)) # 100 -> "100" print(int(9.8)) # 9.8 -> 9 (decimal part is dropped, not rounded!) print(bool(0)) # 0 -> False print(bool(5)) # 5 -> True
Common Mistakes
- Trying to convert non-numeric text to a number:
int("hello")→ValueError. - Assuming
int(9.8)rounds to10— it actually truncates (cuts off) the decimal, giving9. Useround(9.8)if you want proper rounding. - Forgetting to convert user input (from
input()) before doing math —input()always returns a string.
Important Points
int(),float(),str(),bool()are the main conversion functions.- Converting text that isn't a valid number causes a
ValueError. int()on a float truncates, it does not round.
Practice
- Convert the string
"45.6"into a float and then into an integer. What do you get at each step? - Take two numbers as text:
"10"and"20", convert both to integers, and print their sum.
13. Input and Output
What is it?
- Output means displaying information to the user — done using
print(). - Input means receiving information typed by the user — done using
input().
Why do we use it?
Real programs are interactive — they need to ask the user for information (like a name or a choice) and respond back. Input/output is what makes a program feel alive instead of just running the same fixed steps every time.
Syntax
pythonprint(value1, value2, ...) variable = input("Prompt message: ")
Simple Example
pythonname = input("What is your name? ") print("Hello,", name)
Sample Interaction:
What is your name? Sneha
Hello, SnehaExplanation of the Code
input("What is your name? ")displays the prompt text and waits for the user to type something and press Enter.- Whatever the user types is stored in the variable
name, always as a string. print("Hello,", name)displays two values separated automatically by a space.
Real-World Example
A login form asks for a username and password (input), then displays a welcome message or error (output).
Common Mistakes
- Forgetting that
input()always returns a string — even if the user types a number, you must convert it:age = int(input("Enter your age: ")). - Forgetting the space at the end of a prompt string, leading to output like
Enter name:John(no space before the user's typed text).
Important Points
input()always returns typestr.print()can take multiple values separated by commas — Python automatically adds a space between them.- Use
print(f"Hello, {name}")(f-strings) for cleaner formatting — covered in detail in the Strings file.
Practice
- Ask the user for their age using
input(), convert it to an integer, and print "You will turn 30 in X years" (calculate X). - Ask for two numbers separately and print their sum.
14. Operators
What is it?
Operators are special symbols that perform operations on values (called operands) — like addition, comparison, or logical checks.
14.1 Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division (always float) | 5 / 2 | 2.5 |
// | Floor Division (rounds down) | 5 // 2 | 2 |
% | Modulus (remainder) | 5 % 2 | 1 |
** | Exponent (power) | 5 ** 2 | 25 |
pythonprint(10 / 3) # 3.3333333333333335 print(10 // 3) # 3 print(10 % 3) # 1
14.2 Comparison Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
pythonprint(5 == 5) # True print(5 != 3) # True
14.3 Logical Operators
| Operator | Meaning |
|---|---|
and | True only if both conditions are True |
or | True if at least one condition is True |
not | Reverses the result (True → False) |
pythonage = 20 has_id = True print(age >= 18 and has_id) # True
14.4 Assignment Operators
| Operator | Example | Same As |
|---|---|---|
= | x = 5 | assigns 5 to x |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
14.5 Identity and Membership Operators
pythona = [1, 2, 3] b = [1, 2, 3] print(a == b) # True -> values are equal print(a is b) # False -> they are different objects in memory print(2 in a) # True print(5 not in a) # True
Important distinction: == checks if values are equal. is checks if two variables point to the exact same object in memory. This is a very common interview question.
Comparison Table — == vs is
== | is | |
|---|---|---|
| Checks | Value equality | Same object in memory |
| Common use | Comparing numbers, strings, lists | Comparing to None, checking identity |
Common Mistakes
- Using
=(assignment) when you meant==(comparison) — a very frequent beginner bug:if age = 18:is aSyntaxError; it should beif age == 18:. - Confusing
/(always gives float) with//(floor division, drops decimal). - Using
==to compare withNoneinstead ofis None(best practice isis None).
Important Points
/always returns a float, even if the result is a whole number (10 / 2→5.0).//performs floor division, rounding down to the nearest whole number.and,or,notare written as plain English words in Python (not&&,||like some other languages).
Practice
- Given
a = 15andb = 4, print the result of every arithmetic operator between them. - Write a program that checks if a number is both greater than 10 and even, using
and. - Explain in your own words the difference between
==andis.
15. Expressions
What is it?
An expression is any valid combination of values, variables, and operators that Python can evaluate to produce a single result.
Simple Example
pythonlength = 10 width = 5 area = length * width # "length * width" is an expression print(area)
Output:
50Explanation
length * widthis the expression — Python evaluates it and produces the value50.area = length * widthis a statement (a full instruction) that stores the expression's result in a variable.
Important Points
- Expressions always produce a value.
- Statements are complete instructions (which may contain expressions inside them).
- Complex expressions can combine multiple operators, following the normal order of operations (BODMAS/PEMDAS): parentheses first, then exponents, then multiplication/division, then addition/subtraction.
pythonresult = (2 + 3) * 4 - 5 ** 2 print(result) # (5 * 4) - 25 = 20 - 25 = -5
Practice
- Evaluate
10 + 2 * 3 - 4 / 2by hand, then verify with Python.
Common Beginner Mistakes — Summary for This Section
- Using
=instead of==for comparison. - Forgetting
input()returns a string, causing errors when doing math on it. - Mixing tabs and spaces for indentation.
- Assuming Python "rounds" when converting float to int (it truncates).
- Using lowercase
true/falseinstead ofTrue/False.
Cheat Sheet — Python Fundamentals
python# Variables name = "Aditi" age = 21 # Data types type(name) # str type(age) # int # Type conversion int("10") float("3.14") str(100) # Input / Output value = input("Enter something: ") print("Output:", value) # Operators + - * / // % ** # arithmetic == != > < >= <= # comparison and or not # logical = += -= *= /= # assignment is in # identity / membership
Mini Project: Simple Calculator
Objective: Build a calculator that takes two numbers and an operator from the user, then displays the result.
Requirements:
- Take two numbers as input.
- Take an operator (
+,-,*,/) as input. - Display the correct result.
Concepts Used: variables, input/output, type conversion, operators, conditionals (basic if/elif).
Complete Code:
python# Simple Calculator num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) operator = input("Enter operator (+, -, *, /): ") if operator == "+": result = num1 + num2 elif operator == "-": result = num1 - num2 elif operator == "*": result = num1 * num2 elif operator == "/": if num2 == 0: result = "Error: Division by zero" else: result = num1 / num2 else: result = "Invalid operator" print("Result:", result)
Sample Output:
Enter first number: 10
Enter second number: 5
Enter operator (+, -, *, /): +
Result: 15.0Possible Improvements:
- Loop the calculator so it keeps running until the user chooses to exit.
- Add support for more operators like
%and**.
Challenge Task: Modify the calculator to keep a running history of all calculations performed in the session.
Interview Questions
Q1. What type of language is Python — compiled or interpreted? Answer: Python is an interpreted language. Code is read and executed line by line by the Python interpreter, rather than being compiled into machine code beforehand.
Q2. Is Python statically typed or dynamically typed? Answer: Dynamically typed — you don't need to declare a variable's type; Python figures it out automatically based on the assigned value, and a variable's type can even change if reassigned.
Q3. What is the difference between `/` and `//`? Answer: / performs regular division and always returns a float. // performs floor division and returns the result rounded down to the nearest whole number.
Q4. What does `input()` return? Answer: input() always returns a string, even if the user types a number. It must be manually converted using int() or float() if numeric operations are needed.
Q5. What is the difference between `==` and `is`? Answer: == compares values for equality. is checks whether two variables refer to the exact same object in memory.
Q6. What is `None` in Python? Answer: None is a special value representing the absence of a value. It is its own data type (NoneType) and is different from 0, False, or an empty string.
Practice Questions
Beginner
- Write a program that stores your name and age in variables and prints them together.
- Convert the string
"100"to an integer and add 50 to it. - Take two numbers as input and print their product.
- Create a boolean variable and print its type.
- Print the result of
17 % 4and explain what it means.
Intermediate
- Write a program that takes a temperature in Celsius as input and converts it to Fahrenheit (
F = C * 9/5 + 32). - Write a program that swaps the values of two variables without using a third variable.
- Take a user's height in centimeters and convert it to feet and inches.
- Write a program that checks whether a number is even using the modulus operator.
- Ask the user for two numbers and print whether the first is greater, smaller, or equal to the second.
Challenge
- Write a program that takes the radius of a circle and calculates its area and circumference (use
PI = 3.14159as a constant). - Write a program that takes a person's birth year and current year as input and calculates their age, printing whether they are a minor or an adult.
- Modify the Mini Project calculator to also handle the
%and**operators.