Python Program Templates With Examples
Python Program Templates With Examples
------------------------
Code:
result = num * 2
print("Double:", result)
2. If-Else Conditions
----------------------
Code:
if num % 2 == 0:
print("Even")
else:
print("Odd")
3. Elif Ladder
----------------
Code:
print("Grade A")
print("Grade B")
else:
print("Grade C")
4. For Loop
------------
Task: Print 1 to 5
Code:
print(i)
5. While Loop
--------------
Code:
i = 1
while i <= 5:
print(i)
i += 1
6. Star Pattern
----------------
Code:
print("* " * i)
7. List Operations
-------------------
Code:
numbers = [1, 2, 3]
numbers.append(4)
print("List:", numbers)
8. Dictionary Example
----------------------
Code:
9. Functions
-------------
Code:
return x + y
print(add(3, 4))
------------------
Code:
f.write("Hello")
print(f.read())
---------------------
Code:
class Student:
self.name = name
def display(self):
print("Name:", self.name)
s = Student("Alice")
s.display()
------------------------
Task: Check if number is prime
Code:
if num > 1:
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")
13. Factorial
--------------
Code:
fact = 1
fact *= i
print("Factorial:", fact)