Beginner Python Study Guide: From Basics to Problem-Solving
1. Data Types
Fundamental Data Types
Python uses dynamic typing, meaning you don’t declare types explicitly. Common types include int, float, bool, str, and None.
1# Python dynamics types
2age = 25 # int
3salary = 50000.50 # float
4is_active = True # bool
5grade = 'A' # str
6large_number = 1000000000 # int
7empty_string = "" # str
8optional_var = None # NoneType Conversion
Python uses built-in functions for conversion, making it more intuitive than Java.
1# Python type conversion
2d = 10.5
3i = int(d) # result is 10
4x = 5
5y = float(x) # result is 5.0
6s = str(x) # result is '5'2. Control Structures
Conditional Statements
Python uses if, elif, else with indentation-based syntax. An if can be used as a ternary operator.
1# Python conditionals
2score = 85
3if score >= 90:
4 print("A")
5elif score >= 80:
6 print("B")
7else:
8 print("C")
9
10# Ternary operator
11grade = "A" if score >= 90 else "B"Loops
Python uses for and while loops with the range() function for iteration.
1# Python loops
2for i in range(5):
3 print(i)
4
5# Iterating directly over elements
6numbers = [1, 2, 3, 4, 5]
7for num in numbers:
8 print(num)
9
10j = 0
11while j < 5:
12 print(j)
13 j += 13. Arrays and Lists
Declaration and Initialization
Python lists are dynamic and can contain mixed types.
1# Python lists
2numbers = [1, 2, 3, 4, 5]
3names = ["Alice", "Bob", "Charlie"]
4mixed = [1, "hello", 3.14, True]
5
6# Common list operations
7numbers.append(6) # add element
8numbers.extend([7, 8]) # add multiple elements
9numbers.insert(0, 0) # insert at position
10numbers.remove(0) # remove first occurrence
11popped = numbers.pop() # remove and return last element
12length = len(numbers) # get lengthAccessing Elements
Python uses index notation with additional features like negative indexing and slicing.
1arr = [10, 20, 30]
2first = arr[0] # 10
3last = arr[-1] # 30 (last element)
4arr[1] = 25 # modify element
5
6# Slicing
7slice = arr[0:2] # [10, 25]
8slice = arr[1:] # [25, 30]
9reverse = arr[::-1] # [30, 25, 10]4. String Manipulation
String Creation and Basics
Python strings are immutable, but flexible. Concatenation is very simple.
1# Python strings
2s1 = "Hello"
3s2 = "World"
4combined = s1 + " " + s2 # "Hello World"
5
6# String formatting options
7formatted = f"{s1} {s2}" # f-string (modern)
8formatted = "{} {}".format(s1, s2) # .format()
9formatted = "%s %s" % (s1, s2) # % operatorCommon String Methods
1text = "Hello World"
2length = len(text) # 11
3char = text[0] # 'H'
4upper = text.upper() # "HELLO WORLD"
5lower = text.lower() # "hello world"
6contains = "World" in text # True
7index = text.find("World") # 6
8substring = text[0:5] # "Hello"
9parts = text.split(" ") # ["Hello", "World"]
10trimmed = text.strip() # remove leading/trailing whitespace
11equals = text == "Hello World" # True
12starts_with = text.startswith("Hello") # True
13ends_with = text.endswith("World") # True
14replaced = text.replace("World", "Python") # "Hello Python"Useful Techniques
Character checking and conversion:
1# Python
2c = 'a'
3is_letter = c.isalpha() # True
4is_digit = c.isdigit() # False
5is_upper = c.isupper() # False
6upper = c.upper() # 'A'5. Integer Arrays and Utilities
Array Operations
Python provides array-handling functionality through built-in functions and list methods.
1numbers = [5, 2, 8, 1, 9]
2
3# Sorting
4numbers.sort() # [1, 2, 5, 8, 9]
5sorted_numbers = sorted(numbers) # returns new sorted list
6
7# Finding index
8index = numbers.index(5) # 2
9contains = 5 in numbers # True
10
11# Slicing/copying
12copy = numbers[:] # shallow copy
13sublist = numbers[1:3] # [2, 8]
14
15# Reversing
16numbers.reverse() # reverse in-place
17reversed_list = numbers[::-1] # returns reversed list
18
19# Creating filled list
20zeros = [0] * 5 # [0, 0, 0, 0, 0]
21
22# Converting to string
23str_rep = str(numbers) # "[1, 2, 5, 8, 9]"6. Working with Arrays of Objects, Counting Occurrences and Commonalities
Counting Occurrences
1# Counting occurrences in list
2numbers = [1, 2, 2, 3, 2, 4, 1]
3count = numbers.count(2) # 3
4
5# Using dictionary for frequency count
6frequency = {}
7for num in numbers:
8 frequency[num] = frequency.get(num, 0) + 1
9# frequency: {1: 2, 2: 3, 3: 1, 4: 1}
10
11# Using Counter (most Pythonic)
12from collections import Counter
13frequency = Counter(numbers)
14# Counter({2: 3, 1: 2, 3: 1, 4: 1})
15
16# Counting strings
17words = ["apple", "banana", "apple", "cherry"]
18word_count = Counter(words)
19most_common = word_count.most_common(2) # [('apple', 2), ('banana', 1)]Finding Common Elements
1# Finding common elements
2arr1 = [1, 2, 3, 4, 5]
3arr2 = [3, 4, 5, 6, 7]
4
5# Using set intersection
6common = list(set(arr1) & set(arr2)) # [3, 4, 5]
7
8# Preserving order from first array
9common = [x for x in arr1 if x in arr2] # [3, 4, 5]
10
11# Using set operations
12set1 = set(arr1)
13set2 = set(arr2)
14intersection = set1 & set2
15union = set1 | set2
16difference = set1 - set2Working with Arrays of Objects
1# Using a class
2class Student:
3 def __init__(self, name, score):
4 self.name = name
5 self.score = score
6
7# List of objects
8students = [
9 Student("Alice", 95),
10 Student("Bob", 87),
11 Student("Charlie", 92)
12]
13
14# Accessing object attributes
15first_name = students[0].name
16first_score = students[0].score
17
18# Filtering and processing
19high_scores = [s for s in students if s.score >= 90]
20
21# Using filter() function
22high_scores = list(filter(lambda s: s.score >= 90, students))
23
24# Using dictionaries (simpler alternative to classes)
25students = [
26 {"name": "Alice", "score": 95},
27 {"name": "Bob", "score": 87},
28 {"name": "Charlie", "score": 92}
29]
30
31high_scores = [s for s in students if s["score"] >= 90]7. Tips for Solving HackerRank Coding Questions
Read the Problem Carefully
Before writing any code, spend time understanding what the problem is asking. Pay attention to constraints, input formats, and expected output. Reread the problem statement if you’re unsure about edge cases.
Start with a Clear Plan
Outline your approach in pseudocode or comments before implementing. Ask yourself: What data structures do I need? What’s the algorithm? Are there any edge cases?
1# Pseudocode example
2# Read array size
3# Read array elements
4# Find max element
5# Print max elementHandle Edge Cases
Consider boundary conditions: empty arrays, single elements, all identical elements, negative numbers, zeros, and maximum constraints.
1# Handle empty list
2def find_max(nums):
3 if not nums:
4 return None
5 return max(nums)Test with Sample Input/Output
After writing code, trace through the given examples manually to ensure correctness before submitting.
1# If example shows input "1 2 3" should output "6"
2# Test your code step by step with this inputUse Appropriate Data Structures
Different problems benefit from different data structures. Choose wisely to avoid unnecessary complexity.
- Lists/Arrays: Sequential data, indexed access needed
- HashMap/Dictionary: Frequency counting, lookups, grouping by key
- Set: Checking membership, finding unique elements
- Stack: LIFO problems, nested structures
- Queue: FIFO problems, level-by-level processing
- PriorityQueue: K-largest/smallest, sorting requirements
1# Same logic in Python
2from collections import Counter
3text = "hello"
4freq = Counter(text) # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})Optimize Time Complexity
Start with a working solution, then optimize if needed. Be aware of nested loops and unnecessary operations.
1# O(n²) - brute force
2def find_pair(arr, target):
3 for i in range(len(arr)):
4 for j in range(i + 1, len(arr)):
5 if arr[i] + arr[j] == target:
6 return True
7 return False
8
9# O(n) - optimized
10def find_pair(arr, target):
11 seen = set()
12 for num in arr:
13 if target - num in seen:
14 return True
15 seen.add(num)
16 return FalseCommon Patterns and Techniques
Pattern 1: Two-pointer technique - useful for sorted arrays or string manipulation.
1def find_pair(arr, target):
2 left, right = 0, len(arr) - 1
3 while left < right:
4 total = arr[left] + arr[right]
5 if total == target:
6 return True
7 elif total < target:
8 left += 1
9 else:
10 right -= 1
11 return FalsePattern 2: Sliding window - for contiguous subarray problems.
1def max_sum(arr, k):
2 current_sum = sum(arr[:k])
3 max_sum = current_sum
4
5 for i in range(k, len(arr)):
6 current_sum = current_sum - arr[i - k] + arr[i]
7 max_sum = max(max_sum, current_sum)
8
9 return max_sumPattern 3: Prefix sum - for range queries.
1# Calculate prefix sums
2arr = [1, 2, 3, 4, 5]
3prefix = []
4total = 0
5for num in arr:
6 total += num
7 prefix.append(total)
8# prefix: [1, 3, 6, 10, 15]
9
10# Query sum from index i to j
11def range_sum(i, j):
12 return prefix[j] - (prefix[i - 1] if i > 0 else 0)Input/Output Handling
Pay attention to how input is formatted and how output should be presented.
1n = int(input()) # read single integer
2line = input() # read entire line
3arr = list(map(int, input().split())) # read array
4arr = [int(x) for x in input().split()] # alternativeDebugging Tips
Use print statements or a debugger to trace variable values. Check intermediate results, not just the final answer.
1# Add debug output
2print(f"DEBUG: arr = {arr}")
3print(f"DEBUG: result = {result}")Practice Progressions
Start with Easy problems to master fundamentals, then progress to Medium and Hard. Focus on:
- String manipulation: Reverse strings, check palindromes, count characters
- Array operations: Sorting, searching, finding max/min, counting occurrences
- Frequency problems: Count duplicates, find mode, identify unique elements
- Math problems: GCD, prime numbers, number properties
- Two-pointer problems: Merge arrays, find pairs, remove duplicates
- Dynamic programming: Build understanding gradually with simple problems first
Submit Early and Often
Don’t overthink edge cases before submitting. Get your solution working, submit it, and then optimize if it fails test cases. HackerRank’s feedback can guide you to missing edge cases.
Learn from Solutions
After solving or if stuck, read accepted solutions to see different approaches. Understanding multiple solutions deepens your problem-solving skills and introduces you to new techniques.
Quick Reference: Java vs Python Comparison
| Task | Python | Java |
|---|---|---|
print(x) | System.out.println(x); | |
| Array | arr = [1, 2, 3] | int[] arr = {1,2,3}; |
| List | list = [] | ArrayList<Integer> list = new ArrayList<>(); |
| HashMap | dict = {} or from collections import defaultdict | HashMap<K,V> map = new HashMap<>(); |
| Loop | for i in range(n): | for(int i=0; i<n; i++) |
| String iterate | for c in s: | for(char c : s.toCharArray()) |
| Convert to int | int(s) | Integer.parseInt(s) |
| Max | max(a, b) | Math.max(a, b) |
| Sort | arr.sort() or sorted(arr) | Arrays.sort(arr); |
Final Reminders
Practice consistently. Each problem you solve builds pattern recognition. Focus on understanding the solution, not just getting it right. Pseudocode and comments help clarify your thinking. When stuck, break the problem into smaller pieces. Most importantly, learn from every attempt—both successes and failures improve your problem-solving skills.