What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability and ease of use, making it accessible to both beginners and experienced developers. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
- What can Python do?
Web development (using frameworks like Django, Flask)
Data analysis and machine learning (libraries like pandas, NumPy, TensorFlow)
Automation and scripting
Game development
Desktop GUI applications
Network programming
- Why Python?
Easy to learn and use with a clean, readable syntax
Extensive library support for diverse tasks
Large community and plenty of documentation
Versatile, suitable for multiple fields from web to data science
Cross-platform compatibility
PYTHON SYNTAX
Python syntax refers to the set of rules that defines how a Python program is written and interpreted. It emphasizes readability and simplicity, making it distinct from other programming languages.
NOTE: Python uses indentation to indicate a block of code. Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important.
# A function that checks if a number is positive, negative, or zero
def check_number(num):
if num > 0:
print("The number is positive.")
elif num == 0:
print("The number is zero.")
else:
print("The number is negative.")
# Calling the function
check_number(10)
check_number(0)
check_number(-5)
def check_number(num):
if num > 0: # Missing indentation
print("The number is positive.") # Missing indentation
elif num == 0: # Missing indentation
print("The number is zero.") # Missing indentation
else: # Missing indentation
print("The number is negative.") # Missing indentation
PYTHON COMMENTS
A comment in Python is a line of text in the code that is not executed by the interpreter. It is used to provide explanations, improve readability, or temporarily disable code for testing purposes. Comments are preceded by the #
symbol for single-line comments or enclosed in triple quotes '''
or """
for multi-line comments.
# Function to add two numbers
def add_numbers(a, b):
# Add the two numbers and store the result in 'result'
result = a + b
return result # Return the result
# Call the function with values 5 and 3
sum_result = add_numbers(5, 3)
# Print the result to the console
print(f"The sum is: {sum_result}")
# The following line of code is disabled (commented out) to prevent execution during testing
# print(add_numbers(10, 20)) # This won't be executed
Python Variables
Variables are containers for storing data values. A variable is created the moment you first assign a value to it.
x = 5
y = "John"
print(x)
print(y)
Casting
This is the process where you specify the datatype of a given variable
NOTE: To get the datatype of your variable you will use the type() function
Also python is case sensitive.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Rules For Python - Variable Names
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
Python Variable Scope
In Python, the scope of a variable refers to the context in which it is defined and accessible. The primary types of variable scope are:
Local Scope
Variables defined inside a function are local to that function and can only be accessed within it. For example:def my_function(): local_var = "I'm local" print(local_var) my_function() # Prints: I'm local # print(local_var) # This will raise an error because local_var is not accessible outside the function
Global Scope
Variables defined outside any function are global and can be accessed from any part of the code, including inside functions. For example:global_var = "I'm global" def my_function(): print(global_var) # Accessing the global variable my_function() # Prints: I'm global
Enclosing Scope
When dealing with nested functions, a variable in an outer (enclosing) function can be accessed by an inner function. For example:def outer_function(): enclosing_var = "I'm in the enclosing scope" def inner_function(): print(enclosing_var) # Accessing the enclosing variable inner_function() outer_function() # Prints: I'm in the enclosing scope
Built-in Scope
Python also has built-in variables and functions, which are always available. These are part of Python's standard library and can be accessed from any scope.print(len("Hello")) # len() is a built-in function
Understanding variable scope is crucial for managing data and ensuring that variables are used in the correct context within your code.
Python Data Types
In programming, data types define the kind of data that can be stored and manipulated within a program. They specify the format and type of values, such as integers, floats, strings, or more complex structures, and determine what operations can be performed on those values.
Integer (
int
)
Represents whole numbers.num = 10
Float (
float
)
Represents floating-point numbers (decimals).pi = 3.14
String (
str
)
Represents text data, enclosed in quotes.message = "Hello, world!"
Boolean (
bool
)
Represents truth values:True
orFalse
.is_active = True
List (
list
)
An ordered collection of items, which can be of different types.fruits = ["apple", "banana", "cherry"]
Tuple (
tuple
)
An ordered, immutable collection of items.point = (10, 20)
Set (
set
)
An unordered collection of unique items.unique_numbers = {1, 2, 3, 4}
Dictionary (
dict
)
A collection of key-value pairs.person = {"name": "Alice", "age": 30}
Setting Data Types
In Python, you typically set data types by assigning values to variables. Python automatically infers the type based on the value:
num = 10 # int
pi = 3.14 # float
message = "Hello" # str
is_active = True # bool
fruits = ["apple", "banana"] # list
point = (10, 20) # tuple
unique_numbers = {1, 2, 3} # set
person = {"name": "Alice", "age": 30} # dict
To explicitly convert a value to a specific data type, use type conversion functions:
num_str = "123"
num_int = int(num_str) # Convert string to int
pi_str = str(pi) # Convert float to string
Understanding these data types and how to set them helps in managing and manipulating data effectively in Python.
Python Strings
In Python, a string is a sequence of characters enclosed in either single quotes ('
) or double quotes ("
). Strings are immutable, meaning once created, they cannot be changed. However, Python provides many powerful methods and attributes for working with strings effectively.
String Slicing
String slicing allows you to access a subset (or slice) of characters from a string. Slicing is done using square brackets []
with the syntax string[start:end]
, where start
is the index of the first character and end
is the index of the last character you want to slice (non-inclusive).
text = "Hello, World!"
# Slicing from index 0 to 4 (exclusive)
print(text[0:5]) # Output: Hello
# Slicing with only the start index (till the end of the string)
print(text[7:]) # Output: World!
# Slicing with a negative index (from the end of the string)
print(text[-6:]) # Output: World!
Concatenating Strings
String concatenation is the process of joining two or more strings together using the +
operator.
str1 = "Python"
str2 = "Programming"
# Concatenating strings
result = str1 + " " + str2
print(result) # Output: Python Programming
Formatting Strings
Python provides multiple ways to format strings, allowing you to insert variables or expressions inside a string.
- Using
f-strings
(Python 3.6+):
This is the most modern and preferred way to format strings.
name = "Alice"
age = 30
greeting = f"My name is {name} and I am {age} years old."
print(greeting) # Output: My name is Alice and I am 30 years old.
Using .format()
method:
greeting = "My name is {} and I am {} years old.".format(name, age)
print(greeting) # Output: My name is Alice and I am 30 years old.
Using %
formatting (older method):
greeting = "My name is %s and I am %d years old." % (name, age)
print(greeting) # Output: My name is Alice and I am 30 years old.
Escape Characters
Escape characters allow you to include special characters in a string that are otherwise hard to represent. Escape sequences start with a backslash \
.
\n
: Newline\t
: Tab\'
: Single quote\"
: Double quote\\
: Backslash
# Using escape characters
text = "She said, \"Hello!\"\nLet's meet at 5\tPM."
print(text)
String Methods
Python provides various built-in methods to manipulate strings. Some of the most common ones include:
upper()
: Converts the string to uppercase.
print("python".upper()) # Output: PYTHON
lower()
: Converts the string to lowercase.
print("PYTHON".lower()) # Output: python
replace()
: Replaces occurrences of a substring with another substring.
print("Hello World".replace("World", "Python")) # Output: Hello Python
strip()
: Removes leading and trailing whitespace.
print(" python ".strip()) # Output: python
len()
: Returns the length of the string.
print(len("Hello")) # Output: 5