0% found this document useful (0 votes)
8 views2 pages

Python Code Snippets for Beginners

The document contains beginner-friendly Python code snippets that demonstrate basic programming concepts without using functions. It includes examples for generating even numbers, checking prime numbers, reversing a number, counting vowels, calculating factorials, generating Fibonacci sequences, finding the largest number in a list, checking for palindromes, counting character frequency, and swapping two variables. Each snippet is straightforward and serves as a practical introduction to Python programming.

Uploaded by

VIDUSHI VERMA
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)
8 views2 pages

Python Code Snippets for Beginners

The document contains beginner-friendly Python code snippets that demonstrate basic programming concepts without using functions. It includes examples for generating even numbers, checking prime numbers, reversing a number, counting vowels, calculating factorials, generating Fibonacci sequences, finding the largest number in a list, checking for palindromes, counting character frequency, and swapping two variables. Each snippet is straightforward and serves as a practical introduction to Python programming.

Uploaded by

VIDUSHI VERMA
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

Beginner-Friendly Python Code Snippets (No Functions)

1. Even Numbers from 1 to 20


for i in range(1, 21):
if i % 2 == 0:
print(i)

2. Prime Number Check


n = 13
is_prime = True

if n <= 1:
is_prime = False
else:
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
is_prime = False
break

print("Prime" if is_prime else "Not Prime")

3. Reverse a Number
num = 1234
rev = 0

while num > 0:


digit = num % 10
rev = rev * 10 + digit
num //= 10

print("Reversed number:", rev)

4. Count Vowels
text = "Hello World"
vowels = "aeiouAEIOU"
count = 0

for char in text:


if char in vowels:
count += 1

print("Vowel count:", count)

5. Factorial Using Loop


n = 5
fact = 1

for i in range(2, n + 1):


fact *= i
print("Factorial:", fact)

6. Fibonacci Sequence
n = 10
a, b = 0, 1

print(a, b, end=' ')


for _ in range(n - 2):
a, b = b, a + b
print(b, end=' ')

7. Find Largest Number in List


numbers = [4, 9, 1, 7, 3]
max_num = numbers[0]

for num in numbers:


if num > max_num:
max_num = num

print("Largest number:", max_num)

8. Palindrome Check
s = "madam"
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

9. Character Frequency
text = "banana"
freq = {}

for char in text:


if char in freq:
freq[char] += 1
else:
freq[char] = 1

print(freq)

10. Swap Two Variables


a = 5
b = 10
a, b = b, a
print("a:", a, "b:", b)

You might also like