Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6
Here are the 20 simple Python code examples without using functions:
1. Print "Hello, World!"
print("Hello, World!")
2. Find the sum of two numbers
a=5 b=3 print(a + b)
3. Check if a number is even or odd
num = 10 if num % 2 == 0: print("Even") else: print("Odd")
4. Find the largest of two numbers
a=5 b = 10 if a > b: print(a) else: print(b) 5. Count the number of vowels in a string s = "hello" vowels = "aeiou" count = 0 for char in s: if char in vowels: count += 1 print(count)
6. Find the factorial of a number
num = 5 fact = 1 for i in range(1, num+1): fact *= i print(fact)
7. Check if a number is prime
num = 11 is_prime = True for i in range(2, num): if num % i == 0: is_prime = False break print(is_prime) 8. Reverse a string s = "hello" reversed_s = "" for i in range(len(s)-1, -1, -1): reversed_s += s[i] print(reversed_s)
9. Find the Fibonacci sequence up to n terms
n=5 a, b = 0, 1 for _ in range(n): print(a, end=" ") a, b = b, a + b
10.Check if a string is a palindrome
s = "madam" if s == s[::-1]: print("Palindrome") else: print("Not Palindrome") 11.Find the length of a list lst = [1, 2, 3, 4, 5] count = 0 for item in lst: count += 1 print(count) 12.Sort a list of numbers lst = [5, 2, 9, 1] for i in range(len(lst)): for j in range(i + 1, len(lst)): if lst[i] > lst[j]: lst[i], lst[j] = lst[j], lst[i] print(lst)
lst = [5, 2, 9, 1] min_val = lst[0] max_val = lst[0] for item in lst: if item < min_val: min_val = item if item > max_val: max_val = item print(min_val, max_val) 15.Find the average of numbers in a list lst = [1, 2, 3, 4, 5] sum_lst = 0 for num in lst: sum_lst += num average = sum_lst / len(lst) print(average)
16.Remove duplicates from a list
lst = [1, 2, 2, 3, 4, 4] unique_lst = [] for item in lst: if item not in unique_lst: unique_lst.append(item) print(unique_lst)
my_dict = {"name": "Alice", "age": 25} if "name" in my_dict: print(True) else: print(False) 19.Find the intersection of two sets set1 = {1, 2, 3} set2 = {2, 3, 4} intersection = set() for item in set1: if item in set2: intersection.add(item) print(intersection)
20.Calculate the power of a number
base = 2 exp = 3 result = 1 for _ in range(exp): result *= base print(result)