GenAI Developer: Week 1 — Day 1
2 min read 1 day ago
Getting Started with python basics is essential for this course especially if you are a beginner. Install Jupyter Notebook and get started!
Python Basics — Data Types & Variables
# Variables, data types (int, float, string, list, dict, etc.)
name = "John" #String
age = 25 #Int
is_student = True #Boolean
grades = [85, 90, 88] #List
student_info = {"name": "John", "age": 25, "grades": grades} #Dict
Control Flow — Conditional Statements
# A simple if-else statement to check if the person is minor or major
if (age > 18):
print("Major")
else:
print("Minor")
Control Flow — Loops
# For Loop to print the grades from list
for grade in grades:
print(grade)
# While loop for checking the age of and print the statement
while age < 30:
print("Still in 20s!")
age += 1
Functions
# Simple function to calculate the average.
def calculate_avg_sum(numbers):
return sum(numbers)/len(numbers)
print(calculate_avg_sum([20,20,20]))
File Handling — Read and Write Files
Read more about python open function here.
#writing to a file
# open has 4 modes w - write, r - read, a - append, x - create
with open("new.txt", "w") as file:
file.write("Hello World!")
#reading a file
with open("new.txt", "r") as file:
print(file.read())
Practice Task — 1
# Task 1: Sum, Average, Max, Min
# Write a Python script that takes a list of numbers.
# Prints their sum, average, maximum, and minimum.
def analyze_numbers(numbers):
total = sum(numbers)
average = total / len(numbers)
maxNum = max(numbers)
minNum = min(numbers)
return total, average, maxNum, minNum
print(analyze_numbers([ 10, 20, 30 ]))
Practice Task — 2
# Task 2: Word Counter
# Write a script that reads a text file.
# Counts the number of words.
# Writes the word count to a new file.
def count_words(input_file, output_file):
with open(input_file, "r") as file:
content = file.read()
words = len(content.split())
with open(output_file, "w") as file:
file.write(f"Word count: {words}")
count_words("new.txt", "count.txt")
Feel free to connect on LinkedIn, if you have any queries!.