Python Fundamentals
Core Objectives: Learn the foundational elements of Python 3, including variables, data types, arithmetic operators, casting, and terminal input/output. By the end of this guide, you will build a functional, command-line Invoice & Expense Calculator.
Welcome to Python Fundamentals
This guide introduces the core building blocks of Python 3. Programming in Python allows you to write clear, logical instructions that solve real-world problems. Python's straightforward syntax makes it readable and highly expressive, which is why it is the language of choice for data science, software engineering, and scientific research.
1. Getting Started - Meet Python!
What is Python?
Definition: Python is a highly readable programming language. Computers only understand raw electricity (0s and 1s), so Python acts as a friendly translator. You write instructions in plain, English-like text, and Python automatically translates them into actions the computer can perform.
Python is standard infrastructure at modern engineering organizations:
- Google & YouTube: Power search indices, data analysis pipelines, and backend routing.
- NASA: Processes satellite imaging telemetry and calculates orbital logistics.
- Spotify: Analyzes listener metrics to curate custom recommenders.
Setup and Environment Verification
Step 1: The PyNex Studio Lab
Forget about complex terminal setups, PATH variables, or downloading installers. We have built a complete Python environment directly into your browser!
To write and execute your code, simply click the Studio Lab button on your screen. This sandboxed environment runs real Python instantly, meaning you can start building right now with zero setup.
Input and Output: Interacting with Python
Every computer system relies on taking inputs and presenting outputs. In Python, these standard operations are managed by the built-in functions print() and input().
1. Standard Output: print()
Definition: The
print()function outputs text or data to the terminal console. It takes whatever arguments you pass inside its parentheses and displays them.
main.pyRunnable## Outputting a standard string literal print("System ready for execution.")
Output:
System ready for execution.
2. Standard Input: input()
Definition: The
input()function pauses program execution and waits for the user to type text into the terminal and press Enter. It captures whatever was typed and feeds it back into your program as a text string.
main.pyRunnable## Pausing execution to capture the user's name input("Enter your username: ")
Code Annotations (Comments)
Definition: A Comment is an inline note written to explain the purpose of code. The Python compiler completely ignores these lines during execution. In Python, single-line comments begin with a
#symbol.
main.pyRunnable## Initialize output stream print("Script execution started.") # This prints a status update
Common Syntax Pitfalls
- Unmatched Quotes:main.pyRunnable
print("Hello, World!) # ❌ SyntaxError: EOL while scanning string literal print("Hello, World!") # Correct - Command Case Typo:main.pyRunnable
Print("Hello!") # ❌ NameError: name 'Print' is not defined print("Hello!") # Correct (Python is lowercase-strict) - Missing Parentheses:main.pyRunnable
print "Hello" # ❌ SyntaxError: Missing parentheses in call to 'print' print("Hello") # Correct
Self-Check Assessment
2. Data Containers - Storing Information
What is a Variable?
Definition: A Variable is a reserved memory location used to store data. In your program, it acts as a labeled container. Once declared, you can access, analyze, or overwrite the data held inside that container using its name.
Declaration and Assignment
In Python, a variable is created the moment you assign a value to it using the assignment operator (=).
main.pyRunnable## Assign data values to descriptive variables student_name = "Alex Johnson" active_credits = 15 print("Credits:", active_credits)
Output:
Name: Alex Johnson Credits: 15
Variable Re-assignment (State Tracking)
Variables can hold different values over the life of a script. When you assign a new value to an existing variable, the previous value in that memory location is overwritten.
main.pyRunnable## Initialize score state session_score = 0 print("Initial score:", session_score) ## Update score state session_score = 100 print("Level 1 score:", session_score) ## Final update session_score = 150 print("Session complete score:", session_score)
Basic Calculations with Variables
Variables can be combined mathematically to compute new values.
main.pyRunnable## Declaring prices base_cost = 45.00 processing_fee = 3.50 ## Compute final balance total_charge = base_cost + processing_fee print("Total Cost: $", total_charge)
Output:
Total Cost: $ 48.5
Variable Naming Rules
To keep your code clean and prevent compilation failures, your variable declarations must adhere to the following rules:
- ✅ Valid Formats:
user_id— Lowcase letters separated by an underscore (Standard Snake Case).metric_value_1— Numbers can be used at the end or middle._internal_flag— Leading underscores are valid for private identifiers.
- ❌ Invalid Formats (Will Cause Errors):
user id— Spaces are strictly prohibited.1st_metric— Cannot begin with a number.total-fee— Hyphens are treated as minus operators.while— Cannot use reserved keywords.
Self-Check Assessment
3. Types of Information
What is a Data Type?
Definition: A Data Type is a classification that tells the compiler how to interpret and manipulate a value. It determines what operations can be performed on the data.
The Four Fundamental Data Types
main.pyRunnable## 1. String (str) - Represents text characters (Enclosed in single or double quotes) active_course = "Python Foundations" ## 2. Integer (int) - Represents whole numbers (Positive or negative, no decimals) seat_capacity = 32 ## 3. Float (float) - Represents precise decimal values course_gpa = 3.75 ## 4. Boolean (bool) - Represents binary switches (Must be capital True or False) is_enrollment_open = True
Data Type Casting (Type Conversion)
Definition: Type Casting is the explicit conversion of a variable from one data type to another.
Since terminal inputs via input() are returned strictly as text strings, type conversion is required before performing calculations on user-provided values.
str()— Converts target value to text format.int()— Converts compatible target to a whole number.float()— Converts compatible target to a decimal.
main.pyRunnable## Convert integer to string for output formatting quiz_score = 92 print("Final Score: " + str(quiz_score) + "%") ## Convert a text string to an integer for calculation price_input = "25" item_price = int(price_input) discounted_price = item_price - 5 print("Adjusted Price:", discounted_price)
Output:
Final Score: 92% Adjusted Price: 20
Self-Check Assessment
4. Mathematical & Logical Operators
What are Operators?
Definition: Operators are mathematical symbols that instruct the program to perform specific computations or evaluations on values and variables.
1. Arithmetic Operators
Arithmetic operators execute standard mathematical computations:
| Symbol | Operation | Description | Example | Result |
|---|---|---|---|---|
+ | Addition | Sums two operands | 12 + 8 | 20 |
- | Subtraction | Finds the difference | 12 - 8 | 4 |
* | Multiplication | Multiplies two values | 12 * 2 | 24 |
/ | Division | Divides and returns a decimal | 12 / 8 | 1.5 |
// | Floor Division | Divides and drops the decimal part | 12 // 8 | 1 |
% | Modulus | Returns the mathematical division remainder | 12 % 8 | 4 |
** | Exponent | Raises the first value to the power of the second | 2 ** 3 | 8 |
main.pyRunnable## Calculating distributions and leftovers total_credits = 14 credits_per_term = 4 complete_terms = total_credits // credits_per_term remaining_credits = total_credits % credits_per_term print("Full terms planned:", complete_terms) print("Credits left over:", remaining_credits)
2. Comparison Operators
Comparison operators evaluate the relationship between two operands and return a Boolean value (True or False).
| Symbol | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 10 == 10 | True |
!= | Not equal to | 10 != 5 | True |
> | Greater than | 5 > 8 | False |
< | Less than | 5 < 8 | True |
>= | Greater than or equal to | 7 >= 7 | True |
<= | Less than or equal to | 12 <= 10 | False |
main.pyRunnable## Direct comparison state tracking active_grade = 82 passing_grade_boundary = 75 ## Evaluates directly to True or False is_passing_grade = active_grade >= passing_grade_boundary print("Grade boundary met:", is_passing_grade)
Output:
Grade boundary met: True
3. Logical Operators
Logical operators combine multiple boolean expressions together.
and— ReturnsTrueonly if both statements are True.or— ReturnsTrueif at least one statement is True.not— Reverses the boolean state of the target (negation).
main.pyRunnable## Combine conditions for scholarship eligibility gpa_met = True attendance_met = False ## Both must evaluate to True all_requirements_met = gpa_met and attendance_met ## At least one must evaluate to True some_requirements_met = gpa_met or attendance_met print("Approved (AND test):", all_requirements_met) print("Approved (OR test):", some_requirements_met)
Output:
Approved (AND test): False Approved (OR test): True
Self-Check Assessment
5. Capstone Project: Course Invoice & Expense Calculator
🌍 Real-World Scenario: You have been hired as a junior developer at Vidyalaya EdTech, a startup that runs online professional certification courses across India. The finance team is drowning in manual spreadsheets every semester — students email in their details, staff manually calculate totals, and billing errors cost the company money.
Your first task: build an automated terminal billing tool that collects student registration data, calculates all charges and credits, and prints a formatted invoice — replacing the manual process entirely.
This is exactly the kind of script that saves real businesses hours every week. We will combine variables, arithmetic, type casting, input(), and formatted print() — everything from this module — into a single procedural script. No if/for needed yet; pure top-to-bottom Python.
Save the following code block in a file named invoice_calculator.py and run it:
main.pyRunnable.md - Capstone Project ## Course Invoice & Expense Calculator - Procedural Arithmetic Script print("========================================") print(" COURSE EXPENSE CALCULATOR ") print("========================================") print("Enter your semester data details:") print("----------------------------------------") ## 1. Capture Registration Inputs student_name = input("Enter student name: ") base_tuition = float(input("Enter base course tuition: $")) student_fees = float(input("Enter mandatory student fees: $")) ## 2. Capture Material Inputs textbook_cost = float(input("Enter semester textbook cost: $")) equipment_cost = float(input("Enter lab/equipment cost: $")) ## 3. Capture Financial Credit Inputs scholarship_credit = float(input("Enter active scholarship credit: $")) early_payment_discount = float(input("Enter payment discount amount: $")) ## 4. Perform Financial Calculations total_gross_charge = base_tuition + student_fees + textbook_cost + equipment_cost total_credits = scholarship_credit + early_payment_discount net_tuition_due = total_gross_charge - total_credits ## Verify eligibility criteria directly as boolean output flags is_fully_funded = scholarship_credit >= total_gross_charge is_discount_applied = early_payment_discount > 0 ## 5. Display Invoicing Report print("\n========================================") print(" SEMESTER INVOICE REPORT ") print("========================================") print(f"Student Registered: {student_name}") print(f"Total Gross Charges: ${total_gross_charge:.2f}") print(f"Total Applied Credits: ${total_credits:.2f}") print(f"Net Amount Due: ${net_tuition_due:.2f}") print("----------------------------------------") print("Academic Financial Benchmarks:") print(f"• Student accounts fully funded? {is_fully_funded}") print(f"• Pre-payment discounts logged? {is_discount_applied}") print("========================================")
Congratulations!
You have completed Step 1: Python Fundamentals. You have established an active working environment and mastered variables, data types, type casting, mathematical operators, and terminal input/output.
You are now fully prepared to advance to the Data Collections guide to organize values into structured lists, tuples, sets, and dictionaries!
Finished this lesson?
Mark it complete to advance your curriculum progress.