Python basics

In this section, we will cover the basics of Python programming, including variables, data types, and basic arithmetic operations. Python is a high-level, interpreted, and general-purpose dynamic programming language that is known for its simplicity and readability. Let’s dive into the basics of Python programming.

Variables and data types

A variable is a named storage location in the computer’s memory that holds a value. In Python, you can create variables by assigning a value to them. Variables can store different data types, such as integers, floating-point numbers, strings, and boolean values.

Here is an example of creating variables in Python:

variables.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Creating integer variables
x = 10
y = 20

# Creating floating-point variables
pi = 3.14
radius = 5.0

# Creating string variables
name = "John Doe"
message = 'Hello, World!'

# Creating boolean variables
is_active = True
is_admin = False

Basic arithmetic operations

Python supports various arithmetic operations for performing calculations on numerical values. Here are some of the basic arithmetic operators in Python:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus: %
  • Exponentiation: **
  • Floor division: //

Here is an example of using arithmetic operators in Python:

arithmetic.py
# Addition
sum = 10 + 20
print("Sum:", sum)

# Subtraction
difference = 20 - 10
print("Difference:", difference)

# Multiplication
product = 5 * 4
print("Product:", product)

# Division
quotient = 20 / 5
print("Quotient:", quotient)

# Modulus
remainder = 20 % 3
print("Remainder:", remainder)

# Exponentiation
power = 2 ** 3
print("Power:", power)

# Floor division
result = 20 // 3
print("Result:", result)

Comments and code readability

Comments are essential for documenting your code and making it more readable. In Python, you can add comments using the # symbol. Comments are ignored by the Python interpreter and are used to explain the purpose of the code.

Here is an example of using comments in Python:

comments.py
1
2
3
4
5
6
7
8
# This is a single-line comment

# Creating variables
x = 10  #
y = 20  # Assigning values to variables

# Performing arithmetic operations
sum = x + y  # Adding x and y

Variables and data types

Variables are used to store data in a program. In Python, we can assign a value to a variable using the assignment operator =. Python is a dynamically typed language, which means we don’t have to declare the data type of a variable explicitly. The interpreter infers the data type based on the value assigned to the variable.

Here are some examples of variable assignments in Python:

variables.py
# Assigning an integer value to a variable
number = 10

# Assigning a floating-point value to a variable
pi = 3.14

# Assigning a string value to a variable
name = "Alice"

# Assigning a boolean value to a variable
is_student = True

In this example, we have assigned integer, floating-point, string, and boolean values to variables number, pi, name, and is_student, respectively.

Constants

In Python, we can define constants using variables. Constants are variables whose values remain constant throughout the program and cannot be changed once assigned. By convention, constant names are written in uppercase to distinguish them from regular variables.

Here is an example of defining constants in Python:

constants.py
# Defining constants
PI = 3.14159
GRAVITY = 9.81
SPEED_OF_LIGHT = 299792458

In this example, we have defined three constants PI, GRAVITY, and SPEED_OF_LIGHT with their respective values.

Naming conventions

When naming variables, constants, functions, and classes in Python, it is essential to follow certain naming conventions to make the code more readable and maintainable. Here are some common naming conventions in Python:

  • Use descriptive names that reflect the purpose of the variable or function.
  • Use lowercase letters for variable names and separate words using underscores (snake_case).
  • Use uppercase letters for constant names and separate words using underscores (UPPER_CASE).
  • Use camelCase for function names and class names.
  • Avoid using reserved keywords as variable names (if, for, while, etc.).

Here are some examples of following naming conventions in Python:

naming_conventions.py
# Variable names
first_name = "Alice"
last_name = "Smith"

# Constant names
MAX_VALUE = 100
MIN_VALUE = 0

# Function names
def greet_user():
    print("Hello, User!")

# Class names

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model

In this example, we have used descriptive names for variables, constants, functions, and classes, following the naming conventions in Python.

Data types

Python supports various data types to represent different types of values in a program. Here are some common data types in Python:

Data typeDescription
IntegerRepresents whole numbers without any decimal points.
Floating-pointRepresents real numbers with decimal points.
StringRepresents a sequence of characters enclosed in single or double quotes.
BooleanRepresents a binary value, either True or False.
ListRepresents an ordered collection of items.
TupleRepresents an ordered, immutable collection of items.
SetRepresents an unordered collection of unique items.
DictionaryRepresents a collection of key-value pairs.
NoneRepresents the absence of a value or a null value.
Custom data typesRepresents user-defined data types using classes.

Here is an example of using different data types in Python:

data_types.py
# Integer
age = 25

# Floating-point
pi = 3.14

# String
name = "Alice"

# Boolean
is_active = True

# List
numbers = [1, 2, 3, 4, 5]

# Tuple
coordinates = (10, 20)

# Set
colors = {"red", "green", "blue"}

# Dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}

# None
value = None

In this example, we have used different data types such as integer, floating-point, string, boolean, list, tuple, set, dictionary, and None in Python.

Type conversions

Type conversion is the process of converting one data type to another in Python. Python provides built-in functions to convert between different data types. Here are some common type conversion functions in Python:

FunctionDescription
int()Converts a value to an integer.
float()Converts a value to a floating-point number.
str()Converts a value to a string.
bool()Converts a value to a boolean.
list()Converts a value to a list.
tuple()Converts a value to a tuple.
set()Converts a value to a set.
dict()Converts a value to a dictionary.
type()Returns the data type of a value.

Here is an example of using type conversion functions in Python:

type_conversion.py
# Converting an integer to a float
radius = 10
radius_float = float(radius)
print(f"Radius: {radius_float}")

pi = 3.14159
circumference = 2 * pi * radius_float
circle_area = pi * radius_float ** 2
print(f"Circle with radius {radius_float} has circumference: {circumference} and area: {circle_area}")

In this example, we have converted an integer value radius to a floating-point number using the float() function and calculated the circumference and area of a circle using the converted value.

Conclusion

In this section, we covered the basics of Python programming, including variables, data types, and basic arithmetic operations. Understanding these fundamental concepts is essential for writing Python programs and working with different types of data. In the next section, we will explore strings and string operations in Python.