Python Sample Source Sode
Here are some Python sample source codes, covering various concepts and accompanied by images for better understanding:
1. Printing "Hello, World!":
print("Hello, World!") |
2. Basic Arithmetic Operations:
a = 10 b = 5 # Addition sum = a + b print("Sum:", sum) # Subtraction difference = a - b print("Difference:", difference) # Multiplication product = a * b print("Product:", product) # Division quotient = a / b print("Quotient:", quotient) |
3. Taking User Input:
name = input("Enter your name: ") age = int(input("Enter your age: ")) print("Hello,", name, "! You are", age, "years old.") |
4. Conditional Statements (if/else):
number = int(input("Enter a number: ")) if number > 0: print("The number is positive.") elif number == 0: print("The number is zero.") else: print("The number is negative.") |
5. Loops (for/while):
# for loop for i in range(5): print(i) # while loop count = 0 while count < 5: print(count) count += 1 |
6. Defining Functions:
def greet(name): print("Hello,", name, "!") greet("Alice") |
7. Working with Lists:
fruits = ["apple", "banana", "orange"] # Accessing elements print(fruits[0]) # Output: apple # Adding elements fruits.append("mango") # Removing elements fruits.remove("banana") # Printing the list print(fruits) # Output: ['apple', 'orange', 'mango'] |
8. Handling Exceptions:
try: result = 10 / 0 except ZeroDivisionError: print("Error: Cannot divide by zero.") |
9. Reading and Writing Files:
# Reading from a file with open("my_file.txt", "r") as file: contents = file.read() print(contents) # Writing to a file with open("my_file.txt", "w") as file: file.write("Hello, world!") |
10. Working with Classes and Objects:
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print("Hello, my name is", self.name) person1 = Person("Bob", 30) person1.greet() # Output: Hello, my name is Bob |
Related Post