Python Basics: Operations, Manipulations and Type Conversions

Arithmetic Operations in Python

Python supports various arithmetic operations, including addition, subtraction, multiplication, and division. The language uses familiar symbols to represent these operations, making it easy for beginners to understand.

Basic Arithmetic Operations

  • Addition (+): adds two numbers together.
  • Subtraction (-): subtracts the second number from the first number.
  • Multiplication (*): multiplies two numbers.
  • Division (/): divides the first number by the second number.
a = 10
b = 5

sum = a + b
difference = a - b
product = a * b
quotient = a / b

print(sum, difference, product, quotient)

Other Arithmetic Operations

  • Modulus (%): returns the remainder when the first number is divided by the second number.
  • Exponentiation (**): raises the first number to the power of the second number.
  • Floor Division (//): divides the first number by the second number and rounds down to the nearest integer.
a = 10
b = 5

remainder = a % b
exponentiation = a ** b
floor_division = a // b

print(remainder, exponentiation, floor_division)

String Manipulation

Strings in Python are sequences of characters. You can create a string by enclosing characters in single (' ') or double (" ") quotes. Python provides several methods for manipulating strings, including concatenation, slicing, and formatting.

String Concatenation

You can concatenate strings using the '+' operator.

string1 = "Hello"
string2 = "World"

combined_string = string1 + " " + string2

String Slicing

You can extract a substring from a string using slicing. Specify the start and end indices, separated by a colon.

text = "Python programming"

substring = text[0:6]

String Formatting

Python provides various ways to format strings, including the f-string, which allows you to embed expressions within string literals.

name = "John"
age = 30

formatted_string = f"My name is {name}, and I am {age} years old."

Boolean Logic in Python

Boolean logic deals with true and false values, represented in Python as 'True' and 'False'. You can use logical operators such as 'and', 'or', and 'not' to combine or negate boolean values.

a = True
b = False

print(a and b)
print(a or b)
print(not a)

Type Conversions in Python

Python allows you to convert data types using built-in functions such as 'int()', 'float()', and 'str()'.

integer = 42
floating_point = 3.14
string = "123"

converted_float = float(integer)
converted_int = int(floating_point)
converted_str = str(integer)

print(converted_float, converted_int, converted_str)