Session 1: Introduction to Python

Instructor : Seyed Sadjad Abedi-Shahri

Introduction to Programming

Programming is the process of creating a set of instructions or logic that can be understood and executed by a computer to perform a specific task or solve a problem. It involves breaking down complex problems into smaller, more manageable steps that the computer can follow.

Programming languages are the tools used to communicate instructions to computers. They provide a structured way to express algorithms, which are sets of rules or procedures for solving problems. Different programming languages have their own syntax (rules for writing code) and semantics (meaning of the code).

Why Learn Programming?

  1. Problem-solving: Programming teaches logical thinking and problem-solving skills.
  2. Career opportunities: Programming skills are in high demand across various industries.
  3. Automation: Programming allows you to automate repetitive tasks, saving time and increasing productivity.
  4. Creation: Programming empowers you to create software applications, websites, games, and other digital products.
  5. Understanding technology: Having a basic understanding of programming helps you better comprehend the technologies you use daily.

What is Python?

Python is a popular, high-level, general-purpose programming language known for its simplicity, readability, and versatility. It was created by Guido van Rossum in the late 1980s and first released in 1991.

Key Features of Python

  1. Easy to learn: Python has a clean and straightforward syntax that emphasizes readability, making it easy for beginners to learn and understand.
  2. Interpreted: Python is an interpreted language, which means that its code is executed line by line without the need for a separate compilation step, allowing for faster development and testing cycles.
  3. Cross-platform: Python code can run on various operating systems, including Windows, macOS, and Linux, without requiring significant modifications.
  1. Dynamically-typed: Python is a dynamically-typed language, which means that variable types are determined during runtime, providing flexibility and reducing development time.
  2. Extensive libraries: Python has a vast collection of standard and third-party libraries and frameworks that cover a wide range of applications, from web development to data analysis, machine learning, and more.
  3. Open-source: Python is an open-source language, which means its source code is freely available for use, modification, and distribution, fostering a strong community of developers.

Python Applications

  • Web Development: Python is widely used for building web applications and frameworks like Django, Flask, and Pyramid.
  • Data Analysis and Scientific Computing: Libraries like NumPy, Pandas, Matplotlib, and SciPy make Python a powerful tool for data analysis, manipulation, and visualization.
  • Artificial Intelligence and Machine Learning: Popular libraries like TensorFlow, Keras, and scikit-learn enable Python for AI and machine learning applications.
  • Automation and Scripting: Python’s simplicity and cross-platform compatibility make it an excellent choice for automating tasks and writing scripts.
  • Game Development: With libraries like Pygame and Panda3D, Python can be used to create games.
  • Education and Prototyping: Python’s readability and ease of use make it a popular choice for teaching programming and building prototypes.

Setting up the Python Environment

To start programming in Python, you need to set up the Python environment on your computer. This involves installing the Python interpreter and an Integrated Development Environment (IDE) or a code editor. In this bootcamp, we will be using the Anaconda distribution and the Spyder IDE.

Anaconda Distribution

Anaconda is a popular open-source distribution of Python and other data science packages. It comes bundled with Python, the Conda package manager, and various pre-installed libraries and tools for data science, machine learning, and scientific computing.

To install Anaconda, follow these steps:

  1. Go to the official Anaconda website (https://www.anaconda.com/download) and download the latest version of Anaconda for your operating system (Windows, macOS, or Linux).
  2. Run the downloaded installer and follow the prompts to complete the installation process.

After the installation is complete, you will have access to the Anaconda Navigator, which is a graphical user interface (GUI) that allows you to launch applications and manage conda packages, environments, and channels.

Spyder IDE

Spyder (Scientific Python Development Environment) is a powerful IDE that comes bundled with Anaconda. It provides a user-friendly interface for writing, debugging, and executing Python code, as well as advanced features such as code completion, code exploration, and integration with popular scientific libraries like NumPy, SciPy, and Matplotlib.

To launch Spyder, you can either:

  1. Open the Anaconda Navigator and click on the “Launch” button next to the Spyder application.
  2. Open the Anaconda Prompt (on Windows) or the terminal (on macOS/Linux) and type spyder.

The Spyder IDE consists of three main panels:

  1. Editor: This is where you write and edit your Python code.
  2. IPython Console: This is an interactive Python shell where you can run code and see the output immediately.
  3. Variable Explorer: This panel displays the variables and their values in your current workspace.

Python Syntax

Python’s syntax is designed to be simple, readable, and easy to learn. Here’s a quick overview of some essential syntax elements:

Comments

1# This is a single-line comment
2
3"""
4This is a
5multi-line comment
6"""

Indentation

Python uses indentation to define code blocks instead of curly braces or keywords like begin and end. Proper indentation is crucial for Python code to run correctly.

1if condition:
2    # Indented block
3    statement1
4    statement2
5else:
6    # Indented block
7    statement3

Variables

Variables in Python don’t need to be explicitly declared. You can assign values to variables directly.

1x = 5         # Integer
2y = 3.14      # Float
3name = "Sadjad Abedi" # String
4is_true = True # Boolean

Data Types

Python supports several built-in data types, including:

Numbers

Python supports two main types of numbers: integers and floating-point numbers.

1x = 31        # Integer
2y = 3.14      # Float
3z = 1 + 3j    # Complex number

Strings

Strings in Python are sequences of characters enclosed in single quotes (’), double quotes ("), or triple quotes (’’’ or """).

1name = "Sadjad Abedi"
2message = 'Hello, World!'
3multiline = """This is
4a multiline
5string."""

Lists

Lists are ordered collections of items, which can be of different data types.

1fruits = ["apple", "banana", "cherry"]  # List of strings
2numbers = [1, 2, 3, 4, 5]               # List of integers
3mixed = [1, "apple", 3.14, True]        # Mixed data types

List Operations

1len(fruits)         # Get the length of the list
2fruits[0]           # Access the first element
3fruits[-1]          # Access the last element
4fruits[1:3]         # Get a slice (from index 1 to 3)
5fruits.append("orange")  # Add an element to the end
6fruits.insert(1, "kiwi")  # Insert an element at a specific index
7fruits.remove("banana")  # Remove the first occurrence of an element
8fruits.pop(2)       # Remove the element at a specific index

Basic Input/Output Operations

Python provides several built-in functions for handling input and output operations, allowing you to interact with users and work with files.

Input

The input() function is used to get user input from the console or terminal. It takes an optional prompt string as an argument and returns the user’s input as a string.

1name = input("Enter your name: ")
2print("Hello, " + name)

By default, input() returns a string.

If you need to work with other data types, such as integers or floats, you can use type conversion functions like int() or float().

1age = int(input("Enter your age: "))
2weight = float(input("Enter your weight (kg): "))

Output

The print() function is used to display output to the console or terminal.

1print("Hello, World!")

You can print multiple values by separating them with commas, and you can customize the separator and end characters using the sep and end parameters, respectively.

1print("Apple", "Banana", "Cherry", sep=", ")  # Output: Apple, Banana, Cherry
2print("Hello", end="")
3print("World")  # Output: HelloWorld

File Operations

Python provides several functions and methods for working with files, including reading from and writing to files.

Writing to a File

To write to a file, you first need to open it in write mode (“w”) or append mode (“a”). Then, you can use the write() method to write data to the file.

1file = open("data.txt", "w")  # Open a file for writing
2file.write("Hello, World!")
3file.close()  # Don't forget to close the file

Reading from a File

To read from a file, you need to open it in read mode (“r”). Then, you can use methods like read() or readline() to read the contents of the file.

1file = open("data.txt", "r")
2content = file.read()  # Read the entire file
3print(content)
4file.close()

Alternatively, you can use a for loop to read the file line by line.

1file = open("data.txt", "r")
2for line in file:
3    print(line.strip())  # Strip leading/trailing whitespace
4file.close()

Python also provides a convenient with statement to automatically handle opening and closing files.

1with open("data.txt", "r") as file:
2    content = file.read()
3    print(content)

Questions?

Email

Telegram