1. Home
  2. Explore
  3. Computer Science
  4. Python Programming Tutorial

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Python Programming Tutorial

Python Foundations: Concepts, Setup, and Core Syntax

Python at a glance

Python is a general-purpose, high-level programming language that is commonly described as interpreted and dynamically typed. It was created by Guido van Rossum and is used across many areas of software development and computing.

Python is used in:

  • Web development

  • Data analysis and data science

  • Machine learning

  • Automation and scripting

  • Game development

These applications make Python useful both for building software and for working with data.

What the main terms mean

  • General-purpose: Python is not restricted to one application domain. It can be used to build many kinds of programs.

  • High-level: Its syntax is designed to be relatively readable and expressive. Python also handles many lower-level tasks, such as memory management, for the programmer.

  • Interpreted: Python programs are commonly run through a Python interpreter rather than being distributed as machine-specific executables. In standard implementations such as CPython, source code is generally compiled to bytecode before the interpreter executes it; the process is not simply direct execution of the original text.

  • Dynamically typed: A variable name does not need a declared type. Python determines the type of the object assigned to the name at runtime. A name can later be assigned an object of a different type.

For example, assigning a string to a name and then assigning an integer to it is valid:

value = "first"
value = 10

The second assignment makes value refer to the integer object. This does not produce a type error merely because the earlier value was a string.


Why Python is widely used

Readability and ease of learning

Python emphasizes readable syntax, which can make programs easier to understand and maintain. A simple output statement, for example, can be written on one line:

print("Hello, world!")

Python is often recommended to beginners because they can focus on programming ideas without first writing extensive setup code.

Free and open source

Python is free and open source. Its source code can be inspected, used, modified, and redistributed under its license. A large community contributes to the language and its ecosystem.

Broad libraries and community support

Python has a large collection of libraries for tasks such as data analysis, web development, scientific computing, and machine learning. A broad user community also makes it easier to find learning materials and help when problems arise.

Career flexibility

Because Python is used in multiple domains, learning it can support work in areas such as software development, data science, machine learning, and automation. Career opportunities and compensation vary by location, experience, employer, and specialization; language knowledge alone does not guarantee a particular role or salary.

The source quoted average annual salaries of 127,826 for data scientists, 143,650 for machine-learning developers, and 123,473 for Python developers. These should be treated as context-dependent estimates, not current or universal salary guarantees.


Important features of Python

  • Object-oriented programming: Python supports classes and objects, allowing related data and behavior to be organized together. It also supports procedural and functional programming styles.

  • Cross-platform use: Python programs can often run on Windows, macOS, and Linux with little or no change, provided the required Python version, libraries, and system dependencies are available.

  • Large library ecosystem: Standard-library modules and third-party packages provide reusable tools for many common tasks.

  • Integration with other languages: Python can work with code written in languages such as C and C++, and tools exist for interoperability with other languages.

  • Indentation-based block structure: Indentation is part of Python’s syntax. It indicates which statements belong to a block, such as the body of a function, loop, or conditional.


Common applications

Web applications

Python can be used to build web applications, from small sites to complex services. Frameworks and libraries provide tools for handling requests, routing, databases, and other web tasks.

Data analysis and data science

Python is widely used to collect, clean, analyze, and visualize data. Libraries such as NumPy and pandas support numerical computing and tabular-data analysis.

Machine learning

Python is frequently used to build machine-learning workflows, including predictive models. Libraries named in the source include scikit-learn and TensorFlow.

Game development

Python can be used for game development, particularly through libraries and frameworks designed to support game loops, graphics, and input. The source mentions Pygame as an example.

Automation

Python scripts can automate repetitive activities, such as sending emails, opening websites, or posting updates. Automation is useful when a task follows repeatable steps, though interactions with online services may also require permission, authentication, and compliance with their rules.


Installing Python and choosing a development environment

Python versions

The source describes a historical choice between Python 2 and Python 3. Python 3 is the version to learn and use for new projects. Python 2 reached the end of its official support in 2020 and should not be chosen for new development unless a legacy system specifically requires it.

The particular version numbers discussed in the source, such as Python 3.7 and Python 2.7, are historical. Current installations should use a supported Python 3 release appropriate for the operating system and project.

Ways to write and run Python

Python code can be written and executed using several kinds of tools:

  • Command-line interpreter (CLI): Runs Python interactively or executes a script from a terminal.

  • Text editor: A basic editor can be used to write a Python file, although it may provide few programming-specific features.

  • Integrated development environment (IDE): An IDE can offer editing, execution, and debugging tools.

  • Jupyter Notebook: A browser-based environment that runs code in cells and displays results alongside the code. It is especially useful for interactive work, data exploration, and teaching.

  • Anaconda: A Python distribution that bundles Python and commonly used data-science tools. It includes Anaconda Navigator, from which applications such as Jupyter Notebook can be launched.

An environment setup can be summarized as:

  1. Download a supported Python distribution or installer for the operating system.

  2. Run the installer and follow its setup instructions.

  3. Choose a code editor, IDE, or notebook environment.

  4. Create and run a Python program in that environment.

When using Jupyter Notebook, code can be entered into a notebook cell and executed to show its output immediately.


Variables and assignment

A variable is a name that refers to a value or object. Python does not require a type declaration when a name is assigned.

age = 10
name = "John"
salary = 2023.23

Python infers the type of each assigned object:

  • age refers to an integer.

  • name refers to a string.

  • salary refers to a floating-point number.

The type of an object can be checked with type():

print(type(age))
print(type(name))
print(type(salary))

The exact printed type names may appear as <class 'int'>, <class 'str'>, and <class 'float'>.

Assigning one value to multiple names

A single value can be assigned to several names:

a = b = c = 10

All three names refer to the same assigned object. For immutable values such as integers, this commonly behaves as expected when the names are used independently.

Assigning different values to multiple names

Several names can be assigned corresponding values in one statement:

x, y, z = 20, 30, 40

This is called multiple assignment or unpacking assignment. The names receive values in order: x receives 20, y receives 30, and z receives 40.

A later assignment changes the value referred to by a name:

a = 20

Python does not require a variable’s type to remain constant across assignments.


Python tokens

A token is a basic meaningful component of source code. Common token categories include:

  • Keywords: Reserved words with defined roles in the language.

  • Identifiers: Names chosen for variables, functions, classes, and other objects.

  • Literals: Values written directly in code, such as numbers, strings, and None.

  • Operators: Symbols or words that perform operations.

  • Delimiters: Punctuation that structures code, such as parentheses, commas, and colons.

Understanding these categories helps when reading Python syntax and interpreting errors.

Keywords

Keywords are reserved words with special meaning in Python. Examples include if, for, while, break, continue, del, True, and False.

Keywords cannot be used as ordinary identifier names. For instance, if = 10 is invalid because if is reserved for conditional syntax.

Identifiers

An identifier is a name given to a variable, function, class, or other program element. Python identifier rules include:

  • An identifier may contain letters, digits, and underscores.

  • It cannot begin with a digit.

  • It cannot contain punctuation such as @ or ..

  • It cannot be a reserved keyword.

  • Python is case-sensitive, so value, Value, and VALUE are distinct names.

Examples:

valid_name = 10
_private_name = 20
name2 = 30

Examples such as 2name, a.b, and name@one are invalid identifiers.


Literals

A literal is a value written directly in source code. Common literal categories include strings, numeric values, Boolean values, and the special value None.

String literals

A string is text enclosed in matching quotation marks. Single and double quotes are both valid:

first_name = "John"
second_name = 'James'

Triple quotes can enclose a string that spans multiple lines:

message = """Line one
Line two
Line three"""

The line breaks are part of the resulting string.

Numeric literals

Common numeric types include:

  • Integer (int): Whole-number values, such as 10, 0, or -7.

  • Floating-point (float): Values with a decimal point, such as 2.5 or -0.25.

  • Complex (complex): Values with real and imaginary parts, such as 2 + 3j.

Python integers can grow beyond fixed-size integer limits, constrained by available memory. Python 3 does not have a separate long integer type; the historical long type was incorporated into int. A numeric literal generally has one decimal point at most.

Boolean literals

Python has two Boolean values: True and False. They are keywords, not ordinary names, and are commonly used as the results of comparisons and logical conditions.

The special literal None

None represents the absence of a value or a value that has not been set. It is often used to indicate “no result” or “no value.” It is not interchangeable with the string "None", the number 0, or False.


Operators

An operator performs an operation on one or more values, called operands. Python has several operator groups.

Arithmetic operators

Arithmetic operators perform numerical calculations. Common examples include:

  • + for addition

  • - for subtraction

  • * for multiplication

  • / for division

  • % for remainder (modulo)

For example:

total = 1 + 2
remainder = 7 % 3

Assignment operators

The basic assignment operator = assigns a value to a name:

count = 10

Augmented assignment operators combine an operation with assignment:

count += 10
count -= 3
count *= 2

For a numeric variable, count += 10 has the effect of adding 101010 to the current value and assigning the result back to count. Augmented assignment is a shorter form of an update operation.

Comparison operators

Comparison operators compare values and produce a Boolean result. Examples include:

  • < and > for less than and greater than

  • <= and >= for less than or equal to and greater than or equal to

  • == for equality

  • != for inequality

For example:

10 > 20

evaluates to False.

Logical operators

The logical operators are and, or, and not. They are used to combine or reverse conditions.

result = (10 < 10) and (2 > -1)

The first comparison is False and the second is True; therefore, the combined and expression is False. In Boolean reasoning, and is true only when both operands are true.

Bitwise operators

Bitwise operators operate on the binary representation of integers. The source discusses:

  • & for bitwise AND

  • | for bitwise OR

  • ~ for bitwise NOT

  • << for left shift

  • >> for right shift

For example, the binary representations of 777 and 555 are 1112111_21112​ and 1012101_21012​. A bitwise OR sets a bit to 111 if either corresponding bit is 111, so 7∣57 \mathbin{|} 57∣5 evaluates to 777. A bitwise AND sets a bit to 111 only if both corresponding bits are 111, so 7&57 \mathbin{\&} 57&5 evaluates to 555.

For nonnegative integers, shifting left by one place corresponds to multiplying by 222, while shifting right by one place corresponds to integer division by 222 with the fractional part discarded. Thus, 10 >> 2 evaluates to 2, and 10 << 2 evaluates to 40.

Python’s bitwise NOT follows the integer relationship ∼n=−(n+1)\sim n = -(n + 1)∼n=−(n+1). Therefore, ~7 evaluates to -8.

Identity operators

The identity operators are is and is not. They test whether two references point to the same object, not merely whether their values are equal.

Use == to compare values for equality. Use is especially for identity checks such as testing whether a value is None:

result is None

Membership operators

The membership operators in and not in test whether a value occurs within a collection or sequence, such as a string, list, or tuple.

"wolf" in ["dog", "cat", "wolf"]

This expression evaluates to True; checking whether "lion" is in the same list evaluates to False.


Data types and mutability

Python objects can be described as immutable or mutable according to whether their contents can be changed after creation.

Immutable types

An immutable object cannot be changed in place after it is created. The source identifies numbers, strings, and tuples as immutable types.

If an operation appears to change an immutable value, it creates or returns a different value rather than altering the original object.

Mutable types

A mutable object can be changed after it is created. The source identifies lists, dictionaries, and sets as mutable types.

This distinction matters when objects are shared through multiple variable names: changing a mutable object through one name can be visible through another name that refers to the same object.


Numbers and type inspection

Python determines a value’s type automatically when it is assigned. The type() function can be used to inspect it:

a = 10
name = "Jill"
salary = 2000.23

print(type(a))
print(type(name))
print(type(salary))

These values have types int, str, and float, respectively.

Python also provides conversion functions such as int(), float(), and complex() to convert compatible values explicitly. Conversion depends on the input; not every value can be converted successfully.


Strings: indexing, slicing, and common methods

Strings are sequences of characters. Their positions are indexed, starting at 000 for the first character. Negative indices count from the end, with -1 referring to the last character.

text = "Hello world"
  • text[0] gives the first character, "H".

  • text[-1] gives the last character, "d".

Slicing a string

A slice extracts part of a sequence. A slice uses a start index and a stop index; the stop position is excluded.

text[0:5]

This produces "Hello" because it includes positions 000 through 444, but not position 555. The stop index is therefore often one greater than the index of the final character desired.

Finding a substring

The string method .find() returns the index of the first occurrence of a substring:

text.find("world")

If the substring is not found, .find() returns -1.

Replacing text

The string method .replace(old, new) returns a string with occurrences of old replaced by new:

text.replace("world", "Python")

Strings are immutable, so .replace() returns a new string; it does not modify the original string in place.

Multiline strings

Triple-quoted strings can preserve line breaks and are useful for multiline text:

lines = """First line
Second line
Third line"""

The resulting string contains the three lines, including their line breaks.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent