0% found this document useful (0 votes)
11 views14 pages

Python Fundamentals: Variables & Operators

This guide provides an overview of Python fundamentals, including variables, operators, blocks, and data types. It explains how to declare and use variables, perform operations with various types of operators, and understand the significance of indentation in code blocks. Additionally, it covers numeric types and their operations, forming a foundation for more advanced Python programming.

Uploaded by

tidireh473
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views14 pages

Python Fundamentals: Variables & Operators

This guide provides an overview of Python fundamentals, including variables, operators, blocks, and data types. It explains how to declare and use variables, perform operations with various types of operators, and understand the significance of indentation in code blocks. Additionally, it covers numeric types and their operations, forming a foundation for more advanced Python programming.

Uploaded by

tidireh473
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Comprehensive Guide to Python Fundamentals

Python Variables

What Are Variables?

Variables are containers that store data values in memory. Think of them as labeled boxes where you can put
information and retrieve it later. Unlike some programming languages, Python doesn't require you to declare a
variable's type explicitly—it infers the type automatically.

Variable Assignment

In Python, you create a variable by simply assigning a value to it using the equals sign ( = ):

python

name = "Alice"
age = 25
height = 5.7
is_student = True

Variable Naming Rules

Python has specific rules and conventions for naming variables:

Rules (mandatory):

Must start with a letter (a-z, A-Z) or underscore ( _ )

Can contain letters, numbers, and underscores

Cannot start with a number

Cannot contain spaces or special characters (except underscore)

Cannot be a Python keyword (like if , for , class , etc.)

Case-sensitive ( age and Age are different variables)

Conventions (recommended):

Use lowercase with underscores for variable names (snake_case): user_name , total_price

Use descriptive names: student_count is better than sc

Avoid single letters except for counters (like i , j ) or mathematical variables

python
# Valid variable names
user_name = "Bob"
user1 = "Alice"
_private_var = 42
totalAmount = 100 # Valid but not Pythonic

# Invalid variable names


# 1user = "Bob" # Cannot start with number
# user-name = "Bob" # Cannot use hyphens
# user name = "Bob" # Cannot contain spaces

Variable Reassignment

Variables can be reassigned to new values, even of different types:

python

x = 10 # x is an integer
x = "hello" # now x is a string
x = [1, 2, 3] # now x is a list

Multiple Assignment

Python allows you to assign values to multiple variables in one line:

python

# Assign same value to multiple variables


a = b = c = 100

# Assign different values to multiple variables


x, y, z = 10, 20, 30

# Swap variables
a, b = 5, 10
a, b = b, a # Now a=10, b=5

Python Basic Operators


Operators are symbols that perform operations on variables and values. Python has several categories of
operators.

Arithmetic Operators

These perform mathematical calculations:


python

a = 10
b=3

# Addition
result = a + b # 13

# Subtraction
result = a - b # 7

# Multiplication
result = a * b # 30

# Division (always returns float)


result = a / b # 3.3333...

# Floor Division (returns integer, rounds down)


result = a // b # 3

# Modulus (remainder)
result = a % b # 1

# Exponentiation (power)
result = a ** b # 1000 (10 to the power of 3)

Comparison Operators

These compare values and return True or False :

python

x=5
y = 10

x == y # Equal to: False


x != y # Not equal to: True
x > y # Greater than: False
x < y # Less than: True
x >= y # Greater than or equal to: False
x <= y # Less than or equal to: True

Assignment Operators

These assign values to variables, often combining with arithmetic:


python

x = 10

x += 5 # Same as: x = x + 5 (x becomes 15)


x -= 3 # Same as: x = x - 3 (x becomes 12)
x *= 2 # Same as: x = x * 2 (x becomes 24)
x /= 4 # Same as: x = x / 4 (x becomes 6.0)
x //= 2 # Same as: x = x // 2 (x becomes 3.0)
x %= 2 # Same as: x = x % 2 (x becomes 1.0)
x **= 3 # Same as: x = x ** 3 (x becomes 1.0)

Logical Operators

These combine conditional statements:

python

a = True
b = False

# AND: True if both are True


result = a and b # False

# OR: True if at least one is True


result = a or b # True

# NOT: Reverses the boolean value


result = not a # False
result = not b # True

# Practical example
age = 25
has_license = True
can_drive = age >= 18 and has_license # True

Identity Operators

These check if two variables refer to the same object in memory:

python
a = [1, 2, 3]
b = [1, 2, 3]
c=a

a is b # False (different objects, even with same content)


a is c # True (c points to the same object as a)
a is not b # True

Membership Operators

These test if a value exists in a sequence:

python

fruits = ["apple", "banana", "cherry"]

"apple" in fruits # True


"grape" in fruits # False
"grape" not in fruits # True

# Also works with strings


"ell" in "hello" # True

Understanding Python Blocks

What Are Blocks?

In Python, a block is a group of statements that are executed together as a unit. Blocks are defined by
indentation (whitespace at the beginning of lines), which is unique to Python and mandatory for the code to
work.

Indentation Rules

Python uses indentation to define code blocks (most languages use braces {} )

Standard practice is 4 spaces per indentation level

All statements in a block must be indented by the same amount

Mixing tabs and spaces is an error

python
# Correct indentation
if True:
print("This is inside the if block")
print("Still inside the if block")
print("Outside the if block")

# Incorrect indentation (will cause an error)


# if True:
# print("Error: not indented")
# print("Error: inconsistent indentation")

Common Block Structures

Conditional blocks:

python

age = 20

if age >= 18:


print("You are an adult")
print("You can vote")
else:
print("You are a minor")
print("You cannot vote yet")

Loop blocks:

python

# For loop block


for i in range(3):
print(f"Iteration {i}")
print("Still in the loop")

# While loop block


count = 0
while count < 3:
print(f"Count: {count}")
count += 1

Function blocks:

python
def greet(name):
message = f"Hello, {name}!"
print(message)
return message

Nested blocks:

python

for i in range(3):
print(f"Outer loop: {i}")

for j in range(2):
print(f" Inner loop: {j}")

if j == 1:
print(" Nested condition met")

Why Indentation Matters

Indentation in Python is not just for readability—it's part of the syntax. The level of indentation determines
which block a statement belongs to:

python

x = 10

if x > 5:
print("x is greater than 5")
if x > 8:
print("x is also greater than 8") # Nested block
print("Back to first if block")
print("Outside all blocks")

Python Data Types


Python has several built-in data types that categorize different kinds of values.

Overview of Main Data Types

Numeric Types:

int : Integer numbers (whole numbers)

float : Floating-point numbers (decimals)


complex : Complex numbers

Sequence Types:

str : String (text)

list : Ordered, mutable collection

tuple : Ordered, immutable collection

Mapping Type:

dict : Key-value pairs (dictionary)

Set Types:

set : Unordered collection of unique items

frozenset : Immutable set

Boolean Type:

bool : True or False

None Type:

NoneType : Represents absence of value

Checking Data Types

You can check the type of any variable using the type() function:

python

x = 42
print(type(x)) # <class 'int'>

y = 3.14
print(type(y)) # <class 'float'>

z = "hello"
print(type(z)) # <class 'str'>

Type Conversion (Casting)

You can convert between types explicitly:

python
# String to integer
x = int("10") # 10

# Integer to string
y = str(42) # "42"

# String to float
z = float("3.14") # 3.14

# Float to integer (truncates decimal)


a = int(3.99) # 3

# Integer to boolean
b = bool(0) # False
c = bool(5) # True

Declaring and Using Numeric Data Types

Integer ( int )

Integers are whole numbers without decimal points. They can be positive, negative, or zero.

Declaration:

python

# Positive integer
age = 25

# Negative integer
temperature = -15

# Zero
count = 0

# Large integers (no size limit in Python 3)


big_number = 123456789012345678901234567890

Integer Operations:

python
a = 10
b=3

# All arithmetic operators work


sum_result = a + b # 13
diff = a - b #7
product = a * b # 30
quotient = a // b # 3 (floor division)
remainder = a % b #1
power = a ** b # 1000

Different Number Systems:

Python supports integers in different bases:

python

# Decimal (base 10)


decimal = 42

# Binary (base 2) - prefix with 0b


binary = 0b101010 # 42 in binary

# Octal (base 8) - prefix with 0o


octal = 0o52 # 42 in octal

# Hexadecimal (base 16) - prefix with 0x


hexadecimal = 0x2A # 42 in hex

# Convert to different bases


print(bin(42)) # '0b101010'
print(oct(42)) # '0o52'
print(hex(42)) # '0x2a'

Float ( float )

Floats represent decimal numbers (numbers with fractional parts).

Declaration:

python
# Simple float
price = 19.99

# Negative float
temperature = -3.5

# Float with no decimal part (still a float)


whole = 10.0

# Scientific notation
large = 1.5e6 # 1,500,000 (1.5 × 10^6)
small = 2.5e-3 # 0.0025 (2.5 × 10^-3)

Float Operations:

python

a = 10.5
b = 2.5

sum_result = a + b # 13.0
diff = a - b # 8.0
product = a * b # 26.25
quotient = a / b # 4.2

Important Float Considerations:

Floats have precision limitations due to how computers store decimal numbers:

python
# Precision issues
result = 0.1 + 0.2
print(result) # 0.30000000000000004 (not exactly 0.3)

# Rounding for display


print(round(result, 2)) # 0.3

# Comparing floats
# Bad practice
x = 0.1 + 0.2
if x == 0.3: # May be False due to precision
print("Equal")

# Good practice
if abs(x - 0.3) < 0.0001: # Check if close enough
print("Equal")

Complex Numbers ( complex )

Complex numbers have a real and imaginary part. The imaginary part is denoted with j :

python

# Creating complex numbers


z1 = 3 + 4j
z2 = complex(3, 4) # Same as above

# Accessing parts
print([Link]) # 3.0
print([Link]) # 4.0

# Operations
z3 = z1 + z2 # (6+8j)
z4 = z1 * z2 # (-7+24j)

Practical Examples with Numeric Types

Calculator program:

python
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")

if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
if num2 != 0:
result = num1 / num2
else:
result = "Error: Division by zero"
else:
result = "Invalid operation"

print(f"Result: {result}")

Working with percentages:

python

original_price = 100.0
discount_percent = 20

discount_amount = original_price * (discount_percent / 100)


final_price = original_price - discount_amount

print(f"Original: ${original_price}")
print(f"Discount: ${discount_amount}")
print(f"Final price: ${final_price}")

Rounding and formatting:

python
pi = 3.14159265359

# Round to 2 decimal places


rounded = round(pi, 2) # 3.14

# Format for display


formatted = f"{pi:.2f}" # "3.14"

# Ceiling and floor (need math module)


import math
print([Link](3.2)) # 4
print([Link](3.8)) # 3

Summary
This guide covers the fundamental concepts of Python programming:

Variables: Containers for storing data with flexible typing

Operators: Tools for performing calculations, comparisons, and logical operations

Blocks: Code organization using indentation to define scope

Data Types: Built-in types for representing different kinds of data

Numeric Types: Integers, floats, and complex numbers with their operations and use cases

These concepts form the foundation for all Python programming and are essential for building more complex
applications.

You might also like