To install Python on Amazon Linux, you can use the following commands based on the version of Amazon Linux you are using.
For Amazon Linux 2:
- Update the Package List:
sudo yum update -y
2. Install Python 3:
sudo yum install python3 -y
- Verify the Installation:
python3 --version
Task 1: Basics of Python
The day started with a session focused on the basics of Python, where I explored essential concepts such as variables, data types, and basic operations. Here’s a breakdown of what I learned and practiced.
1. Understanding Variables in Python
Variables in Python are containers that hold data. The data stored can be of various types, including strings, integers, floats, and more. Creating a variable in Python is straightforward—just assign a value to a name using the = sign.
For example:
# String variable
name = "Muzammil"
# Integer variable
score = 90
# Float variable
distance = 0.7
# Using f-string for formatting
print(f"{name} scored {score} and traveled {distance} km.")
2. Working with Data Types
Python offers a variety of data types to work with. I explored the most common ones, including strings, integers, lists, and dictionaries.
- Strings: Text data, enclosed in quotes.
greeting = "Hello, World!"
- Integers and Floats: Numerical data for whole numbers and decimals.
num = 10 # Integer
pi = 3.14 # Float
- Lists: Ordered collections of items.
fruits = ["apple", "banana", "cherry"]
- Dictionaries: Key-value pairs for storing data.
person = {"name": "Muzammil", "score": 90, "location": "Karachi"}
# Print each variable on a new line:
print(f"{greeting}\n{fruits}\n{person}")
3. Performing Basic Operations
With a firm grasp on variables and data types, I moved on to performing basic operations. Python makes it simple to manipulate data.
- Arithmetic Operations:
a = 5
b = 3
sum = a + b # Addition
difference = a - b # Subtraction
product = a * b # Multiplication
quotient = a / b # Division
- String Operations:
first_name = "Muzammil"
last_name = "Jan"
full_name = first_name + " " + last_name # Concatenation
- List Operations:
# Adding an item
fruits.append("orange")
Task 2: File Handling and Automation
The second task of the day involved diving deeper into Python's capabilities, particularly in file handling and automation. Here’s how I tackled this challenge:
1. Reading a Text File and Counting Word Occurrences
The first script I implemented focused on reading data from a text file and counting the occurrences of specific words. This task demonstrated Python’s ability to work with files, and it gave me a glimpse of how automation can simplify repetitive tasks.
Here’s a simplified version of the script:
# Open the file in read mode
with open('example.txt', 'r') as file:
content = file.read()
# Split the content into words
words = content.split()
# Count the occurrences of a specific word
word_to_count = "Python"
count = words.count(word_to_count)
# Print the result
print(f"The word '{word_to_count}' occurs {count} times in the file.")
This script reads the content of example.txt, splits it into individual words, and counts how often the word "Python" appears.
2. Writing Data to a New File Based on User Input
The second part of this task was to create a script that writes user input into a new file. This was an excellent exercise in handling user data and writing it into a structured format.
Here’s how the script works:
# Get user input
user_name = input("Enter your name: ")
user_age = input("Enter your age: ")
# Create or open a file in write mode
with open('user_data.txt', 'w') as file:
# Write the data to the file
file.write(f"Name: {user_name}\n")
file.write(f"Age: {user_age}\n")
print("Data written to 'user_data.txt' successfully!")
This script prompts the user for their name and age, then writes that information into a new file called user_data.txt.
Task 3: Practice Git Integration
The third task of the day was particularly exciting as it involved integrating Python with Git. This practice helped me understand how Python scripts can be utilized for version control and automating tasks related to repositories.
1. Cloning a Git Repository Using Python
A task that demonstrated how automation can streamline the setup process for development environments.
- Install the gitpython Library (if not already installed): You need to install the gitpython package using pip. Run the following command in your terminal:
sudo yum install python3-pip
- Install gitpython Using pip3: Once pip3 is installed and verified, install gitpython with:
pip3 install gitpython
it's important to import the git module and ensure the gitpython library is installed because it enables your Python script to interact with Git repositories programmatically. Without this library, you wouldn't be able to automate tasks like cloning repositories, committing changes, or pushing updates directly from your Python code.
Here's how the script looks:
import git
# URL of the repository to be cloned
repo_url = "https://github.com/example/repo.git"
# Directory where the repository will be cloned
clone_dir = "cloned_repo"
# Clone the repository
git.Repo.clone_from(repo_url, clone_dir)
print(f"Repository cloned into '{clone_dir}' successfully!")
This script utilizes the gitpython library to clone a remote repository into a specified directory. This kind of automation can save time, especially when setting up multiple repositories.
2. Automating Committing and Pushing Changes to a Remote Repository
The next step was automating the process of committing changes and pushing them to a remote repository using Python. This task highlighted the potential of scripting in automating repetitive Git tasks.
import git
# Path to the local repository
repo_dir = "cloned_repo"
# Open the repository
repo = git.Repo(repo_dir)
# Stage all changes
repo.git.add('--all')
# Commit changes
commit_message = "Automated commit message"
repo.index.commit(commit_message)
# Push changes to the remote repository
origin = repo.remote(name='origin')
origin.push()
print("Changes committed and pushed successfully!")
This script stages all changes, commits them with a message, and pushes them to the remote repository, all in one go. Automating such tasks can enhance productivity and reduce the chances of errors during manual operations.