Print Primes 1 to N
Print all prime numbers from 1 to n.
IntermediatePhase 6 - Category 3: Loop & Conditional MixExample 1 of 10
print-primes-1-to-n.py
1# Helper function2def is_prime(n):3 if n < 2:4 return False5 for i in range(2, int(n ** 0.5) + 1):6 if n % i == 0:7 return False8 return True910# Take n11n = int(input("Enter n: "))1213# Print primes14print(f"Primes from 1 to {n}:")15for num in range(1, n + 1):16 if is_prime(num):17 print(num, end=" ")18print()
Output
Enter n: 20 Primes from 1 to 20: 2 3 5 7 11 13 17 19
What's going on
Loop through range and check each number.
Key Concepts:
Use helper function
Loop from 1 to n
Check and print primes
🔗Related Content
- 📖
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- 📝
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- 💻
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum