Python, the versatile and beginner-friendly programming language, is not just about solving complex problems or developing sophisticated software. It’s also a playground for coders, where short and playful snippets can unleash creativity and showcase the language’s simplicity and elegance. Let’s dive into some fun and short Python codes that demonstrate its charm.
1.Printing a Heart Shape:
python for row in range(6): for col in range(7): if (row == 0 and col % 3 != 0) or (row == 1 and col % 3 == 0) or (row - col == 2) or (row + col == 8): print("*", end=" ") else: print(end=" ") print()
This snippet uses nested loops and conditional statements to create a heart shape, showcasing Python’s ability to handle basic logic with ease.
2.One-liner to Check if a Number is Prime:
python n = int(input("Enter a number: ")) print("Prime" if all(n % i != 0 for i in range(2, int(n**0.5) + 1)) else "Not Prime")
This compact line of code efficiently checks if a number is prime, demonstrating Python’s powerful one-liners and its efficient handling of mathematical operations.
3.Printing the Fibonacci Series:
python def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() fib(100)
This simple function prints the Fibonacci series up to a specified number, highlighting Python’s clean syntax and ease of defining functions.
4.Quicksort Algorithm in One Line:
python qsort = lambda arr: arr if len(arr) <= 1 else qsort([x for x in arr[1:] if x < arr]) + [arr] + qsort([x for x in arr[1:] if x >= arr]) print(qsort([3,6,8,10,1,2,1]))
This is a concise implementation of the Quicksort algorithm, showcasing Python’s support for lambda functions and list comprehensions, making it possible to write complex algorithms in a single line.
5.Word Frequency Counter:
python from collections import Counter text = "Python is an amazing language. It is great for beginners." print(Counter(text.split()))
Using the collections.Counter
class, this snippet counts the frequency of each word in a given text, demonstrating Python’s rich standard library and its ease of handling text data.
These examples are just a tip of the iceberg when it comes to the fun and playful aspects of Python. The language’s simplicity, combined with its powerful features, makes it an excellent choice for both serious projects and recreational coding. So, next time you’re looking for a quick coding break, try experimenting with some fun Python snippets!
[tags]
Python, Programming, Fun Code, Short Code, Beginner-friendly, Coding Snippets