AB
Master the basics of Python programming with this comprehensive guide covering variables, operators, control structures, and essential concepts for beginners.
Python is a high-level, interpreted programming language renowned for its simplicity and readability. It has become one of the most popular programming languages in the world, used in web development, data analysis, artificial intelligence, scientific computing, and more.
Functions are reusable blocks of code designed to perform specific tasks. They help organize code, improve readability, and reduce redundancy.
print()
, len()
, range()
)def
keywordlambda
keywordmap()
, filter()
, reduce()
)# User-defined function
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
# Lambda function
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
# Higher-order function
def apply(func, value):
return func(value)
result = apply(lambda x: x * 2, 5)
print(result) # Output: 10
print()
FunctionThe print()
function outputs data to the console. It’s one of the most commonly used functions in Python, especially for beginners.
print("Hello, World!") # Output: Hello, World!
Special characters can modify how text is displayed. For example, \n
creates a new line:
print("Hello\nWorld")
# Output:
# Hello
# World
When you pass multiple arguments to print()
, they’re separated by spaces by default:
print("Hello", "World", "!") # Output: Hello World !
The sep
and end
parameters control how arguments are separated and what appears at the end:
# Custom separator
print("Hello", "World", sep="*") # Output: Hello*World
# Custom ending
print("Hello", end="*")
print("World") # Output: Hello*World
Literals are fixed values assigned to variables or used directly in code.
"Hello, World!"
, 'Python is fun'
, '''Multi-line string'''
10
(integer), 3.14
(float), 42j
(complex)True
, False
None
(represents absence of value)[1, 2, 3]
(list), (1, 2, 3)
(tuple), {'a': 1, 'b': 2}
(dictionary), {1, 2, 3}
(set)Operators perform operations on variables and values.
Used for mathematical operations:
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.3333333333333335
print(a % b) # Modulus (remainder): 1
print(a ** b) # Exponentiation: 1000
print(a // b) # Floor Division: 3
Compare values and return a boolean result:
a = 10
b = 3
print(a == b) # Equal to: False
print(a != b) # Not equal to: True
print(a > b) # Greater than: True
print(a < b) # Less than: False
print(a >= b) # Greater than or equal to: True
print(a <= b) # Less than or equal to: False
Perform logical operations on boolean values:
a = True
b = False
print(a and b) # Logical AND: False
print(a or b) # Logical OR: True
print(not a) # Logical NOT: False
Operate on binary representations of numbers:
a = 10 # 1010 in binary
b = 3 # 0011 in binary
print(a & b) # Bitwise AND: 2 (0010 in binary)
print(a | b) # Bitwise OR: 11 (1011 in binary)
print(a ^ b) # Bitwise XOR: 9 (1001 in binary)
print(~a) # Bitwise NOT: -11 (inverts all bits)
print(a << 1) # Left shift: 20 (10100 in binary)
print(a >> 1) # Right shift: 5 (0101 in binary)
Operators follow a precedence order that determines how expressions are evaluated:
/
vs. //
Python has two division operators, each with distinct behaviors:
/
(Division)The regular division operator always returns a floating-point result:
result = 10 / 3
print(result) # Output: 3.3333333333333335
Use cases: Scientific calculations, financial applications, or whenever precision is necessary.
//
(Floor Division)The floor division operator discards the fractional part, returning:
result = 10 // 3
print(result) # Output: 3
result = 13.0 // 3
print(result) # Output: 4.0
Use cases: When you need a truncated integer result, such as for array indices or counting iterations.
Variables are names that store data values. Python is dynamically typed, meaning variable types are determined at runtime.
myVar
and myvar
are different)if
, else
, for
, etc.# Assigning values
name = "Alice"
age = 25
is_student = True
# Multiple assignments
x, y, z = 1, 2, 3
# Swapping variables
a, b = 5, 10
a, b = b, a
print(a, b) # Output: 10 5
Python provides shorthand operators for updating variables:
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 /= 6 # Same as x = x / 6, x becomes 4.0
Comments make code more readable and help document your code. Python ignores comments during execution.
Use the #
symbol for single-line comments:
# This is a single-line comment
print("Hello, World!") # This is also a comment
Python doesn’t have a specific syntax for multi-line comments, but you can use triple quotes:
"""
This is a multi-line comment.
It spans multiple lines.
Python treats this as a string literal that isn't assigned to a variable.
"""
The input()
function reads user input from the keyboard:
# Basic input
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Converting input to a different type
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
Remember that input()
always returns a string, so you need to convert it to the desired type for non-string operations.
Python provides many built-in methods for string manipulation:
# Converting case
print("hello".upper()) # Output: HELLO
print("HELLO".lower()) # Output: hello
# Removing whitespace
print(" text ".strip()) # Output: text
# Replacing substrings
print("Hello, World!".replace("World", "Universe")) # Output: Hello, Universe!
# Splitting strings
print("a,b,c".split(",")) # Output: ['a', 'b', 'c']
# Finding substrings
print("Hello, World!".find("World")) # Output: 7
# Joining strings
words = ["Hello", "World", "!"]
print(" ".join(words)) # Output: Hello World !
# Chaining methods
sentence = " Hello, World! "
print(sentence.strip().upper()) # Output: HELLO, WORLD!
Python compares strings based on their ASCII/Unicode values, which means lowercase letters have higher values than uppercase:
result = 'python' > 'Python'
print(result) # Output: True
This is True
because ‘p’ (ASCII 112) is greater than ‘P’ (ASCII 80).
Conditional statements let you execute different code blocks based on conditions.
age = 18
if age >= 18:
print("You are an adult.")
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
In Python, any non-empty tuple is considered True
in a boolean context:
if (5, 10):
print("hello") # This will execute
While loops repeatedly execute a block of code as long as a condition is True
:
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
break
: Exits the loop completelycontinue
: Skips the current iteration and moves to the next one# Using break
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
# Using continue
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
i = 1
while True:
if i % 0o7 == 0: # 0o7 is octal for 7
break
print(i)
i += 1
Output:
1
2
3
4
5
6
The loop stops when i
reaches 7 (which is divisible by 7).
For loops iterate over a sequence (like lists, tuples, or strings):
# Iterating through a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# Using range()
for i in range(5):
print("Iteration:", i)
# Iterating through a dictionary
student_scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
for student, score in student_scores.items():
print(f"{student} scored {score} points.")
Logical operators combine conditions and return boolean results:
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
The bin()
function converts integers to binary strings:
num = 10
binary_representation = bin(num)
print(binary_representation) # Output: 0b1010
Bitwise operators work on the binary representations of numbers:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print(a & b) # Bitwise AND: 1 (Binary: 0001)
print(a | b) # Bitwise OR: 7 (Binary: 0111)
print(a ^ b) # Bitwise XOR: 6 (Binary: 0110)
print(~a) # Bitwise NOT: -6
a = 5 # Binary: 0101
print(a << 2) # Left shift: 20 (Binary: 010100)
a = 20 # Binary: 010100
print(a >> 2) # Right shift: 5 (Binary: 0101)
This guide has covered the fundamental concepts of Python programming, from basic syntax to control structures and operators. Python’s simplicity and readability make it an excellent language for beginners, while its powerful features and extensive library support make it suitable for advanced applications.
As you continue your Python journey, practice writing code regularly and explore the vast ecosystem of libraries and frameworks that make Python one of the most versatile programming languages available today.