0% found this document useful (0 votes)
5 views5 pages

Tutorial Part1 Python

This document is a comprehensive tutorial on Python, part of a series covering multiple programming languages. It introduces Python installation, basic syntax, data types, control flow, functions, classes, file I/O, error handling, and highlights the standard library. The tutorial aims to provide a solid foundation for both beginners and experienced developers, preparing them for subsequent parts focusing on C, C++, and Go.

Uploaded by

Oulfa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Tutorial Part1 Python

This document is a comprehensive tutorial on Python, part of a series covering multiple programming languages. It introduces Python installation, basic syntax, data types, control flow, functions, classes, file I/O, error handling, and highlights the standard library. The tutorial aims to provide a solid foundation for both beginners and experienced developers, preparing them for subsequent parts focusing on C, C++, and Go.

Uploaded by

Oulfa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Part 1: Introduction & Python

Welcome to this comprehensive programming tutorial covering four of the most influential programming languages
in modern software development: Python, C, C++, and Go (Golang). This five-part series is designed to take you
from the fundamentals of each language through intermediate and advanced concepts, giving you a solid
foundation in each. Whether you are a complete beginner or an experienced developer looking to add new
languages to your toolkit, this tutorial will guide you step by step.

1.1 Why Learn Multiple Programming Languages?


Each programming language was created to solve particular classes of problems. C gives you control over
hardware and memory. C++ adds object-oriented programming and generic programming on top of C while
maintaining performance. Python prioritizes readability and rapid development. Go was designed for concurrency
and simplicity at scale. By learning multiple languages, you gain a deeper understanding of programming concepts
that transfer across all of them, such as variables, control flow, functions, data structures, and memory
management.

1.2 How to Use This Tutorial


Each part focuses on a different language. Part 1 covers Python. Part 2 dives into C. Part 3 explores C++. Part 4
introduces Go. Part 5 compares all four languages and covers advanced cross-cutting topics. We recommend
typing out every code example yourself rather than copying and pasting, because muscle memory plays an
important role in learning syntax.

1.3 Setting Up Python


Python is one of the easiest languages to install. On macOS, you can use Homebrew. On Windows, download the
installer from [Link]. On Linux, use your package manager. After installation, verify it works by running
python3 --version in your terminal. You should see a version number like 3.12 or newer.
$ python3 --version
Python 3.12.0

# Optional: create a virtual environment


$ python3 -m venv myenv
$ source myenv/bin/activate # macOS/Linux
$ myenv\Scripts\activate # Windows

1.4 Your First Python Program


Let us start with the classic hello world program. In Python, a single line is all it takes. Create a file called [Link]
with the following content and run it with python3 [Link].
print("Hello, World!")

1.5 Variables and Data Types


Python is dynamically typed, which means you do not need to declare the type of a variable. Python infers it
automatically. The built-in data types include integers, floats, strings, booleans, lists, tuples, dictionaries, and sets.
Let us look at examples of each.
# Numbers

Page 1
Part 1: Introduction & Python

age = 30 # int
price = 19.99 # float

# Strings
name = "Alice"
greeting = f"Hello, {name}!"

# Booleans
is_active = True

# List (ordered, mutable)


fruits = ["apple", "banana", "cherry"]
[Link]("date")

# Tuple (ordered, immutable)


coordinates = (10, 20)

# Dictionary (key-value pairs)


person = {"name": "Bob", "age": 25}

# Set (unordered, unique elements)


unique_numbers = {1, 2, 3, 3} # {1, 2, 3}

1.6 Control Flow


Python uses indentation to define code blocks instead of braces. This makes the code visually clean but requires
consistent spacing. The main control flow constructs are if-elif-else, for loops, and while loops.
# Conditional statements
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Your grade is {grade}")

# For loop over a range


for i in range(5):
print(f"Iteration {i}")

# While loop
count = 0
while count < 3:
print(f"Count is {count}")
count += 1

# Looping over a list

Page 2
Part 1: Introduction & Python

for fruit in fruits:


print([Link]())

1.7 Functions
Functions in Python are defined with the def keyword. They can take default arguments, keyword arguments, and
variable-length arguments. Python also supports lambda functions for short anonymous functions.
def greet(name, greeting="Hello"):
"""Return a greeting message."""
return f"{greeting}, {name}!"

print(greet("Alice")) # Hello, Alice!


print(greet("Bob", "Hi")) # Hi, Bob!

# Lambda function
square = lambda x: x * x
print(square(5)) # 25

# Variable-length arguments
def sum_all(*args):
return sum(args)

print(sum_all(1, 2, 3, 4, 5)) # 15

1.8 Classes and Object-Oriented Programming


Python supports object-oriented programming with classes, inheritance, and polymorphism. The __init__ method
is the constructor. Every instance method receives self as the first parameter, which refers to the current instance.
class Animal:
def __init__(self, name, sound):
[Link] = name
[Link] = sound

def speak(self):
return f"{[Link]} says {[Link]}"

class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof")

def fetch(self):
return f"{[Link]} fetches the ball"

dog = Dog("Rex")
print([Link]()) # Rex says Woof
print([Link]()) # Rex fetches the ball

1.9 Working with Files


File I/O in Python is straightforward with the open function and context managers (the with statement), which

Page 3
Part 1: Introduction & Python

ensure files are properly closed even if an error occurs.


# Writing to a file
with open("[Link]", "w") as f:
[Link]("Line 1\n")
[Link]("Line 2\n")

# Reading from a file


with open("[Link]", "r") as f:
for line in f:
print([Link]())

# Appending to a file
with open("[Link]", "a") as f:
[Link]("Line 3\n")

1.10 Error Handling


Python uses try-except blocks to handle exceptions. You can catch specific exception types or use a generic
except clause. The finally block always runs, whether or not an exception occurred.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("That is not a valid number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
except Exception as e:
print(f"An error occurred: {e}")
finally:
print("This always executes.")

1.11 Python Standard Library Highlights


One of Python's greatest strengths is its extensive standard library. Here are a few commonly used modules you
should know about. The os module provides operating system interfaces. The sys module gives access to
interpreter variables. The json module handles JSON encoding and decoding. The datetime module works with
dates and times. The collections module offers specialized data structures like Counter, defaultdict, and
namedtuple.
import os
import json
from datetime import datetime
from collections import Counter

# OS operations
print([Link]())
print([Link]("."))

Page 4
Part 1: Introduction & Python

# JSON
data = {"name": "Alice", "age": 30}
json_str = [Link](data)
loaded = [Link](json_str)

# Datetime
now = [Link]()
print([Link]("%Y-%m-%d %H:%M:%S"))

# Counter
words = "the cat sat on the mat the cat".split()
word_counts = Counter(words)
print(word_counts.most_common(2))

1.12 Summary of Part 1


In this part, we covered Python installation, basic syntax, variables, control flow, functions, classes, file I/O, error
handling, and the standard library. Python's readable syntax and powerful standard library make it ideal for
scripting, data analysis, web development, and automation. In the next part, we will move to C, where you will
learn about memory management, pointers, and low-level system programming.

Page 5

You might also like