Learn Python Programming’s Fundamentals with Our In-Depth Guide
Welcome to your first step into the world of Python programming. Whether you’re a complete beginner or looking to refresh your knowledge, this tutorial will guide you through the basics and get you started with Python. So, let’s get started.
Introduction of Python
Python is a popular programming language known for being easy to read and use. It was created by Guido van Rossum and first released in 1991. It is designed to be simple and straightforward, making it a great choice for beginners. Python can be used for many things, like building websites, analyzing data, artificial intelligence, and even controlling robots!
Key Features of Python
- Easy to Read: Python’s syntax (the rules for writing code) is clear and easy to understand.
- No Need to Declare Variables: In Python, you don’t need to specify the type of data (like numbers or text) your variable will hold.
- Interpreted Language: Python runs your code line by line, which makes it easy to test and debug.
- Lots of Libraries: Python has many pre-written code libraries that you can use to add features to your programs.
- Works on Different Operating Systems: Python runs on Windows, macOS, and Linux.
Setting up Python
To start using Python, you need to install it on your computer. Follow these steps:
Download Python
Go to the official Python website: python.org.
Click on “Downloads” and choose the version that matches your operating system (Windows, macOS, or Linux).
Run the Installer
Windows: Open the downloaded file and follow the instructions. Make sure to check the box that says “Add Python to PATH” before clicking “Install Now.”
macOS: Open the downloaded file and follow the instructions.
Linux: Open a terminal and type:
sudo apt update sudo apt install python3
Verify installation
After installing Python, you should verify that it’s installed correctly.
Open Command Prompt or Terminal:
On Windows, open Command Prompt.
On macOS/Linux, open Terminal.
Check Python Version:
Type python --version
or python3 --version
and press Enter.
You should see something like Python 3.11.6
. This shows that Python is installed correctly.
Running Python code
You can run Python code in two main ways: using the interactive shell or by running Python scripts.
Interactive Shell
The interactive shell lets you type and run Python code one line at a time.
Open the Shell:
Open Command Prompt or Terminal.
Type python
or python3
and press Enter.
Enter Python Commands:
You will see the Python prompt >>>
. This means Python is ready to accept your commands.
Type:
print("Hello, World!")
Press Enter, and you should see: Hello, World!
.
Running Python Scripts
For longer programs, you write your code in a file (script) and run the whole file at once.
Create a Python Script:
Open a text editor (like Notepad or any code editor).
Write your Python code and save the file with a .py
extension. For example, create a file named hello.py
with this content:
# Your first Python program print("Hey, world, let's be friends!")
Run the Script:
Open Command Prompt or Terminal.
Navigate to the directory where your script is saved using the cd
command.
Run the script by typing:
python hello.py
When you run this Python program:
- Python ignores the comment line because it is not meant to be executed.
- The
print()
function is executed, which tells Python to display the string inside the parentheses to the screen.
Output:
Hey, world, let's be friends!
What is a Variable?
A variable is like a storage box in your computer’s memory where you can keep data. You can put information into this box and later retrieve or change it. Variables make it easier to write and manage your code by allowing you to label data with descriptive names.
Example:
# Creating variables name = "John" age = 25
In the example, the variable name
stores the string value "John"
, while the variable age
stores the integer value 25
.
Variable Naming Rules
When you create a variable, you need to give it a name. There are some rules for naming variables:
- Start with a letter or an underscore (_):
- Correct:
myVariable
,_myVariable
- Incorrect:
1myVariable
,-myVariable
- Correct:
- Use letters, numbers, and underscores:
- Correct:
variable1
,var_1
,var1_
- Incorrect:
var-1
,var.1
,var 1
- Correct:
- Case-sensitive: This means
myVariable
andmyvariable
are different variables. - Cannot use reserved keywords: Python has certain reserved words that you cannot use as variable names, such as
class
,for
,if
,else
, etc.
Data Types
Data types define the kind of data a variable can hold. Python supports several data types, but the most common ones are numeric, text, and boolean.
Numeric Data Types
Numeric data types include integers and floating-point numbers.
int | Whole numbers without a decimal point. They can be positive or negative like 5, -3, or 0. |
float | Numbers that have a decimal point, like 3.14, -0.5, or 2.0. |
Example:
# Numeric data types age = 25 pi = 3.14
In the example above, the variable age
is assigned the value 25, which is an integer. The variable pi
is assigned the value 3.14, which is a floating-point number.
Text Data Type
Text data is represented by strings in Python.
str | A sequence of characters enclosed in single quotes ('...' ) or double quotes ("..." ). |
Example:
# Text data type name = "John Doe" message = 'Hello, World!'
In the example above, the variable name
is assigned the string value "John Doe"
, while the variable message
is assigned the string value "Hello, World!"
.
Boolean Data Type
Boolean data types (bool
) represent truth values, which can be either True
or False
.
Example:
# Boolean data type is_student = True is_adult = False
In the example above, the variable is_student
is assigned the boolean value True
, indicating that the person is a student. The variable is_adult
is assigned the boolean value False
, indicating that the person is not an adult.
Type Conversion
Type conversion, also known as type casting, is the process of changing the data type of a value. For example, you might want to convert a number to a string or a string to a number. Python provides ways to do this both automatically (implicit type conversion) and manually (explicit type conversion).
Implicit Type Conversion
Implicit type conversion happens automatically in Python. This means Python converts one data type to another without you needing to do anything. It usually happens when you perform operations involving different data types.
Example:
# Implicit type conversion x = 10 y = 3.5 result = x + y # Implicit conversion of x to float: 10.0 + 3.5 = 13.5
In the example above, we have a variable x
of type integer and a variable y
of type float. When adding x
and y
, Python performs implicit type conversion and converts x
to a float before performing the addition.
Explicit Type Conversion
Explicit type conversion is when you manually change the data type using Python’s built-in functions.
int() | Converts a value to an integer data type. |
float() | Converts a value to a floating-point data type. |
str() | Converts a value to a string data type. |
bool() | Converts a value to a Boolean data type. |
Example:
# Explicit type conversion x = 10.5 y = "25" x_as_int = int(x) # Explicit conversion of x to int: 10 y_as_int = int(y) # Explicit conversion of y to int: 25 y_as_float = float(y) # Explicit conversion of y to float: 25.0 x_as_str = str(x) # Explicit conversion of x to str: "10.5" y_as_str = str(y) # Explicit conversion of y to str: "25" z = 0 # Zero is considered False in Python z_as_bool = bool(z) # Explicit conversion of z to bool: False
In the example above, we use the built-in functions int()
, float()
, and str()
to explicitly convert values between different data types. We also demonstrate how to convert a value to a Boolean data type using the bool()
function.
Handling Type Conversion Errors
Sometimes, type conversion can fail and cause errors. Handling these errors is important to make sure your program runs smoothly.
Common Errors:
ValueError | Happens when you try to convert a value that is not appropriate for the target data type. |
TypeError | Happens when an operation or function is applied to an object of inappropriate type. |
You can use try
and except
blocks to handle type conversion errors gracefully.
Example:
# Handling type conversion errors user_input = input("Enter a number: ") try: user_input_as_int = int(user_input) print("Conversion successful!") except ValueError: print("Invalid input. Please enter a valid number.")
In the example, we use the int()
function to convert user input into an integer. However, if the user provides a value that cannot be converted to an integer, a ValueError
will occur. To handle this, we use a try-except
block to catch the ValueError
and print an error message gracefully.
Output:
Enter a number: hey
Invalid input. Please enter a valid number.
Operators and Expressions
Operators and expressions are fundamental components in programming. They allow you to perform operations on data and create meaningful instructions.
An operator is a symbol that tells the computer to perform a specific mathematical, logical, or relational operation on one or more values (known as operands). For example, the +
operator adds two numbers.
Python has several types of operators. We’ll cover the most commonly used ones: arithmetic, comparison, logical, and assignment operators.
Arithmetic Operators
Arithmetic operators perform mathematical operations.
Addition (+) | Adds two numbers. |
Subtraction (-) | Subtracts one number from another. |
Multiplication (*) | Multiplies two numbers. |
Division (/) | Divides one number by another. The result is a floating-point number (a number with a decimal point). |
Integer Division (//) | Divides one number by another and rounds down to the nearest whole number. |
Modulo (%) | Returns the remainder when one number is divided by another. |
Exponentiation (\*\*) | Raises one number to the power of another. |
Example:
# Arithmetic operators x = 10 y = 3 addition = x + y # 10 + 3 = 13 subtraction = x - y # 10 - 3 = 7 multiplication = x * y # 10 * 3 = 30 division = x / y # 10 / 3 = 3.3333333333333335 integer_division = x // y # 10 // 3 = 3 modulo = x % y # 10 % 3 = 1 exponentiation = x ** y # 10 ** 3 = 1000
Comparison Operators
Comparison operators compare two values and return either True
or False
.
Equal to (==) | Checks if two values are the same. |
Not equal to (!=) | Checks if two values are different. |
Greater than (>) | Checks if the first value is greater than the second. |
Less than (<) | Checks if the first value is less than the second. |
Greater than or equal to (>=) | Checks if the first value is greater than or equal to the second. |
Less than or equal to (<=) | Checks if the first value is less than or equal to the second. |
Example:
x = 10 y = 3 equal_to = x == y # False not_equal_to = x != y # True greater_than = x > y # True less_than = x < y # False greater_than_or_equal_to = x >= y # True less_than_or_equal_to = x <= y # False
Logical Operators
Logical operators are used to combine multiple conditions. They return True
or False
.
Logical AND (and) | Returns True if both conditions are true. |
Logical OR (or) | Returns True if at least one condition is true. |
Logical NOT (not) | Reverses the result of a condition. |
Example:
# Logical operators x = True y = False logical_and = x and y # False logical_or = x or y # True logical_not = not x # False
Assignment Operators
Assignment operators are used to assign values to variables and can also be used to update the value of a variable.
Assignment (=) | Assigns the value on the right to the variable on the left. |
Addition assignment (+=) | Adds the right operand to the left operand and assigns the result to the left operand. |
Subtraction assignment (-=) | Subtracts the right operand from the left operand and assigns the result to the left operand. |
Multiplication assignment (\*=) | Multiplies the left operand by the right operand and assigns the result to the left operand. |
Division assignment (/=) | Divides the left operand by the right operand and assigns the result to the left operand. |
Modulo assignment (%=) | Takes modulus using the two operands and assigns the result to the left operand. |
Example:
# Assignment operators x = 10 x += 5 # Equivalent to x = x + 5 x -= 3 # Equivalent to x = x - 3 x *= 2 # Equivalent to x = x * 2 x /= 4 # Equivalent to x = x / 4 x %= 3 # Equivalent to x = x % 3
Expressions
An expression is a combination of values, variables, and operators that produces a result. For instance, 2 + 3
is an expression that evaluates to 5
.
You can combine different operators to create complex expressions. Python follows a specific order of operations (also known as PEMDAS/BODMAS rules):
- Parentheses:
()
- Exponents:
**
- Multiplication and Division:
*
,/
,//
,%
(from left to right) - Addition and Subtraction:
+
,-
(from left to right)
Example:
result = (5 + 3) * 2 ** 2 / 4 - 1 # Output: 7.0
In this example:
- Parentheses are evaluated first:
(5 + 3)
becomes8
. - Exponents are evaluated next:
2 ** 2
becomes4
. - Multiplication and Division are evaluated from left to right:
8 * 4 / 4
becomes8
. - Subtraction is evaluated last:
8 - 1
becomes7.0
.
Next Chapter’s
- Python Built-in Functions
- Python Functions: Syntax, Parameters, Return Values, Lambda, Scope and more
- Lists And Tuples in Python
- Sets in Python
- Dictionaries: Mapping Key-Value Pairs
- Decision-Making Statements in Python
- Advanced Looping Techniques in Python
- Formatting Strings: The Power of f-strings
- Error Handling in Python
- Learn All About Python Modules
- File Handling in Python