The Comprehensive Guide to Python Basics
Table of Contents:
Introduction to Python
Why Python?
Getting Started
3.1 How to Install Python3.2 Checking if Python is Already Installed
3.3 Hello World Program
Variables and Data Types
4.1 Keywords and Identifiers
Operators in Python
Conclusion
References
1. Introduction to Python
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. Due to its simplicity and readability, it has become a widely-used language. Python support multiple programming paradigms, including procedural, object-oriented, and functional programming. It is versatile and used in various fields such as web development, data science, automation, and artificial intelligence.
2. Why Python ?
Readability and Simplicity: Python's syntax is clear and easy to understand, making it an excellent choice for beginners and enabling developers to write clean and maintainable code.
Versatility: Python can be used for various applications, including web development, data analysis, artificial intelligence, machine learning, automation, and more.
Strong Community and Libraries: Python boasts a large, supportive community and a vast ecosystem of libraries and frameworks, such as Django for web development, Pandas for data analysis, and TensorFlow for machine learning.
Cross-Platform Compatibility: Python is compatible with major operating systems like Windows, macOS, and Linux, allowing developers to create cross-platform applications.
3. Getting Started
In this section, we'll cover how to install Python and set up your development environment.
3.1 How to Install Python
To get started with Python, you need to install it on your computer.
Windows
Go to the Python Downloads page.
Download the latest version of Python for Windows.
Run the installer and make sure to check the box that says "Add Python to PATH".
Follow the prompts to complete the installation.
MacOS
Go to the Python Downloads page.
Download the latest version of Python for macOS.
Open the downloaded package and follow the prompts to complete the installation.
Linux
Most Linux distributions come with Python pre-installed. However, you can install the latest version using the package manager. For example, on Ubuntu, you can use the following commands:
sudo apt update
sudo apt install python3
3.2 Checking if Python is Already Installed
Before installing Python, you might want to check if it's already installed on your computer.
Windows
Open Command Prompt and type:
python --version
MacOS and Linux
Open Terminal and type:
python3 --version
3.3 Hello World Program
Open your editor and write the following code:
print("Hello World")
Save your file with a .py extension, for example, hello_world.py. Then, open the command line and navigate to the directory where you saved your file. Run the following command:
python hello_world.py
You should see the output:
Hello World
4. Variables and Data Types
Variables are used to store data values in Python. Each variable has a name and a data type. Python supports various data types, including:
Numeric Types: Integers (
int
), floating-point numbers (float
), and complex numbers (complex
).Sequence Types: Lists (
list
), tuples (tuple
), and strings (str
).Mapping Type: Dictionaries (
dict
).Set Types: Sets (
set
) and frozen sets (frozenset
).Boolean Type: Boolean (
bool
), representingTrue
orFalse
.
# Variables and Data Types
x = 10 # Integer
y = 3.14 # Float
name = "John" # String
is_valid = True # Boolean
my_list = [1, 2, 3]# List
my_dict = {'a': 1, 'b': 2} # Dictionary
4.1 Keywords and Identifiers
Keywords are reserved words in Python that have special meanings and purposes, such as if, else, for, while, etc. Identifiers are names given to variables, functions, classes, etc., and must follow certain rules and conventions.
Valid Characters: Letters (a-z, A-Z), digits (0-9), and underscores (_).
Start with Letter or Underscore: Must begin with a letter (a-z, A-Z) or an underscore (_), not a digit.
Case Sensitivity: Python is case-sensitive.
Reserved Words: Cannot be a reserved word or keyword.
Meaningful Names: Use descriptive and meaningful names.
Conventions:
Use lowercase letters for variables (e.g., my_variable).
Use uppercase letters for constants (e.g., MAX_VALUE).
Separate words with underscores (snake_case).
Use CamelCase for class names (e.g., MyClass).
Avoid single-character names except for loop variables.
if True:
print("This is an example of a keyword (if)")
my_variable = 10 # Identifier
def my_function():
5.1 Operators in Python
Operators in python are symbols that perform operations on operands. They are classified into different categories, such as arithmetic operators, comparison operators, logical operators, etc. Here are some commonly used operators in python:
Arithmetic Operators: Perform mathematical operations like addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floor division (//).
Comparison Operators: Compare the values of two operands and return True or False based on the comparison. These include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
Logical Operators: Perform logical operations like AND (and), OR (or), and NOT (not) on Boolean values.
Assignment Operators: Assign values to variables using =, +=, -=, \=, /=, %=, *=, //=, etc.
Bitwise Operators: Perform bitwise operations on binary numbers, including AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>).
Membership Operators: Check for membership in sequences (lists, tuples, etc.) using in and not in.
Identity Operators: Check if two operands are identical (refer to the same object) using is and is not.
# Arithmetic Operators
x = 10
y = 5
print(x + y) # Addition
print(x - y) # Subtraction
print(x * y) # Multiplication
print(x / y) # Division
# Comparison Operators
print(x > y) # Greater than
print(x == y) # Equal to
print(x != y) # Not equal to
# Logical Operators
a = True
b = False
print(a and b) # Logical AND
print(a or b) # Logical OR
print(not a) # Logical NOT
# Assignment operator
a= 3
a+=10
print(a)
a-=4
print(a)
a*=5
print(a)
a/=2
print(a)
a//=2
print(a)
# Bitwise Operators
x= 2
y= 4
print(x|y) # Sets each bit to 1 if both bits are 1
print(x&y) # Sets each bit to 1 if one of two bits is 1
print(~x) # Inverts all the bits
print(x^y) # Sets each bit to 1 if only one of two bits is 1
print(8 >> 1) # Right shift operator move the last significant bit to left 1000 => 0000100 => 4
print(5 << 1) # Left shift operator move the most significant bit to right
# Identity operator
a= ['apple', 'banana']
b= ['apple', 'banana']
print(a is b)
Output:
False
a='Hello'
b='Hello'
print(a is b)
Output:
True
# Membership Operator
a='Ahmad Ali'
print('Ahmad' in a)
Output:
True
6. Conclusion
By exploring Python programming basics, we have established the foundation for becoming proficient in this adaptable language. Now, we have a firm grasp of variables, data types, operators, keywords, and identifiers, and may use Python for programming a variety of tasks. Python is an indispensable tool for developers and data scientists alike, because to its ease of use, versatility, and extensive library ecosystem. These qualities apply to constructing web apps, analyzing data, and implementing machine learning algorithms. As we progress with Python, don't forget to practice frequently, investigate novel ideas, and make use of online communities, documentation, and tutorials as tools to improve your knowledge and broaden your horizons in the field of programming.