📌 Basics of Coding – A Beginner’s Guide
Welcome to the basics of coding! In this document, we will cover fundamental programming
concepts with simple Python examples and explanations.
---
1. Printing Output
print("Hello, World!") # This prints "Hello, World!" to the screen
2. Variables and Data Types
name = "Alice" # A string variable
age = 25 # An integer variable
height = 5.6 # A float variable
is_student = True # A boolean variable
print(name, age, height, is_student) # Printing multiple variables
3. User Input
user_name = input("Enter your name: ") # Takes user input as a string
print("Hello, " + user_name + "!") # Concatenates and prints user input
4. Conditional Statements
num = int(input("Enter a number: ")) # Converts input to an integer
if num > 0:
print("Positive number") # Executes if num is greater than 0
elif num == 0:
print("Zero") # Executes if num is 0
else:
print("Negative number") # Executes if num is less than 0
5. Loops
# Using a for loop to print numbers from 1 to 5
for i in range(1, 6):
print(i)
# Using a while loop to count down from 5
count = 5
while count > 0:
print(count)
count -= 1 # Decreases count by 1 each iteration
6. Functions
def greet(name):
"""This function greets the user."""
print("Hello, " + name + "!")
greet("Alice") # Calls the function with "Alice" as an argument
7. Lists
fruits = ["apple", "banana", "cherry"] # Creating a list
print(fruits[0]) # Accessing the first element
fruits.append("orange") # Adding a new element
print(fruits) # Printing the updated list
8. Dictionaries
person = {"name": "Alice", "age": 25, "city": "New York"} # Creating a dictionary
print(person["name"]) # Accessing value using a key
person["job"] = "Engineer" # Adding a new key-value pair
print(person)
9. Exception Handling
try:
num = int(input("Enter a number: ")) # Try to convert input to an integer
print(10 / num) # Attempt division
except ZeroDivisionError:
print("Cannot divide by zero!") # Handles division by zero
except ValueError:
print("Invalid input! Please enter a number.") # Handles non-numeric input
10. File Handling
# Writing to a file
with open("sample.txt", "w") as file:
file.write("Hello, this is a test file.") # Writing to the file
# Reading from a file
with open("sample.txt", "r") as file:
content = file.read() # Reading file contents
print(content) # Printing the content
🌟 Conclusion
These are the fundamental building blocks of coding. Keep practicing these concepts to
build a strong foundation. Happy coding! 🚀