How to Learn Python: Installation and Basics
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Introduction
Python is one of the most popular programming languages today. It is easy to use and understand, with simple enough syntax that even a complete beginner can write a working Python program with a bit of help. It is free, open-source, and has a large community and ecosystem with extensive support on various platforms. Python has also been used extensively for advanced computer science applications such as data science, artificial intelligence, and machine learning.
In this tutorial, we will look at some of the most useful fundamental features in Python.
Whether you're a beginner programmer or an expert looking to try out a new programming language, this tutorial will cover all the basics you need for starting with Python.
Installing Python
Installing Python
To use the language on your machine, you need to install Python. It supports installation on common operating systems such as Windows, Mac OS X, Linux, as well as on several other operating systems.
To get Python on your machine, you can download the Python setup files from the official website here. The download is free, and you can choose the setup files according to your operating system.
Python Trivia
Python is a paid programming language that is only limited to corporations.
Working in Python
Working in Python
Python programming is easy to understand. The syntax is simple, and the programs appear like they are written in the English language itself.
Before moving forward, let's review some basic programming syntax in this language.
Multiple Choice 1
Which of the following is NOT a data type?
Creating Functions
Great! Now that we have reviewed some basics, let's talk about some useful aspects of the programming language.
Creating Functions
You may already be aware of built-in functions. Built-in functions are specified by the programming language directly via reserved keywords-- terms taken by the language itself. Such functions are available for the user to freely use in their programs. An example of one such very common built-in function in Python is print().
But what if you wanted to create a custom function to perform a task of your choice? You can create a user-defined function in that case, and Python fully supports this.
Let's now see how user-defined functions in Python work. A function definition starts with a def keyword, followed by the function name, parenthesis, and a colon. You can also provide function parameters within the parenthesis. However, they are entirely optional, and functions exist without parameters as well.
To use this custom function in a program, it needs to be called, or invoked, within your code. This is shown in the code block below, where the function is now utilized. As output, "Hello World!" is printed on the console.
Functions help modularize code, as the program gets divided into different blocks (or "subroutines") which can be reused. Suppose you have a program that performs file writing when triggered by a certain condition. Instead of writing the same lines of code repeatedly, a function can be made which performs this specific task. This function is then called whenever this task is required.
```py
def my_function():
print("Hello World!")
my_function()
```
```java
public void myFunction() {
System.out.println("Hello World!");
}
myFunction();
```
```javascript
function myFunction() {
console.log("Hello World!");
}
myFunction();
```
```cpp
#include <iostream>
void myFunction() {
std::cout << "Hello World!\n";
}
int main() {
myFunction();
return 0;
}
```
```csharp
void MyFunction() {
Console.WriteLine("Hello World!");
}
MyFunction();
```
```go
func myFunction() {
fmt.Println("Hello World!")
}
func main() {
myFunction()
}
```
Function Anatomy Snapshot
Before moving on, lock in the shape of a Python function.
Notice the two separate moments: definition creates the reusable block, while the call actually runs it. Parameters are optional, but the indentation under def is what makes the body belong to the function.

Python Basics Map
Before moving deeper, zoom out: Python starts with a working interpreter, then small pieces of syntax, then reusable functions.
In the visual, notice the difference between defining a function and calling it. A definition stores the instructions; a call actually runs them.

Function Flow Map
Before moving on, lock in the mental model for functions: defining a function stores a reusable block of work, but nothing happens until the function is called.
In the visual, notice the two separate steps: definition with def, then invocation with my_function().

True or False
Is the following function definition valid?
def func()
print("This is my first function!")
public void func() {
System.out.println("This is my first function!");
}
function func() {
console.log("This is my first function!");
}
void func() {
std::cout << "This is my first function!" << std::endl;
}
void Func() {
Console.WriteLine("This is my first function!");
}
func func() {
fmt.Println("This is my first function!")
}
Lists
Lists
So far, you've seen variables in Python. The problem with variables is that they can only store one value of a single data type.
Lists solve this problem for us. They can store a collection of data-- that is, multiple values of the same or different data types in a single variable.
Lists in Python are defined with square brackets. Let's look at some examples of lists.
What if we want to access any of its elements? This is done using indexing. In indexing, each value in a list is given a number (starting from 0, not 1!). To access a certain element, this number is specified inside the square bracket with the list name. For example, "w" from the list below can be accessed using lst[5].

Lists are very powerful, and many useful operations are defined with them. These list methods make it easier to manipulate and perform operations on lists. Some of these common methods are in the table below.
len()
Get the length of list
append()
Add more elements to an existing list
count()
Gives the number of times a specified element appears in a list
pop()
Remove the element at last index in the list
sort()
Sort all the elements in the list according to specified order
copy()
Copy all elements from one list to another, and returns the copy
```py
#list with items of single type
fruits = ["orange", "apple", "banana", "strawberry"]
#list with items of multiple types
lst = ["a", 1, "c", ["x", "y"], 5, 7, (1,2)]
```
```java
// ArrayList with items of single type
List<String> fruits = new ArrayList<String>();
Collections.addAll(fruits, "orange", "apple", "banana", "strawberry");
// ArrayList with items of multiple types
List<Object> lst = new ArrayList<Object>();
Collections.addAll(lst, "a", 1, "c", Arrays.asList("x", "y"), 5, 7, new int[]{1, 2});
```
```javascript
// Array with items of single type
let fruits = ["orange", "apple", "banana", "strawberry"];
// Array with items of multiple types
let lst = ["a", 1, "c", ["x", "y"], 5, 7, [1,2]];
```
```cpp
// Vector with items of single type
std::vector<std::string> fruits = {"orange", "apple", "banana", "strawberry"};
// Vector with items of different types cannot be realized in C++
```
```csharp
// List with items of single type
List<string> fruits = new List<string> {"orange", "apple", "banana", "strawberry"};
// List with items of multiple types
List<object> lst = new List<object> {"a", 1, "c", new List<string> {"x", "y"}, 5, 7, new Tuple<int, int>(1, 2)};
```
```go
// Slice with items of single type
fruits := []string{"orange", "apple", "banana", "strawberry"}
// Slices with items of multiple types can't be created in Go
```
Dictionaries
Dictionaries
A collection of data can also be stored in the form of dictionaries in Python. Unlike lists, dictionaries store data values in what's known as key: value pairs. These key: value pairs are also called items. This means that in a dictionary, values are assigned to keys, and the values of these items can be obtained using key names.
In Python, dictionaries are declared using curly braces {}, separated by a comma. A key is specified within the curly braces, which is followed by a colon and its corresponding value.
Let's look at an example dictionary.

But in what cases can dictionaries be helpful?
Suppose you want to store distances of all cities from a chosen starting point. In such a case, it would be helpful if you could store distance values for each city from the starting city. Using a list would be a tedious task as you would have difficulty representing which city has what distance. Dictionaries make it easier to represent such problems. In this example, using a dictionary, cities can be represented as keys and their distances as values.
```py
distances = {"A": 421, "B": 234, "C": 127, "D": 184}
```
```java
Map<String, Integer> distances = new HashMap<String, Integer>();
distances.put("A", 421);
distances.put("B", 234);
distances.put("C", 127);
distances.put("D", 184);
```
```javascript
let distances = {"A": 421, "B": 234, "C": 127, "D": 184};
```
```cpp
std::map<std::string, int> distances;
distances["A"] = 421;
distances["B"] = 234;
distances["C"] = 127;
distances["D"] = 184;
```
```csharp
Dictionary<string, int> distances = new Dictionary<string, int>(){
{"A", 421},
{"B", 234},
{"C", 127},
{"D", 184}
};
```
```go
distances := map[string]int{
"A": 421,
"B": 234,
"C": 127,
"D": 184,
}
```
Dictionary Methods
Like lists, dictionaries also have a set of methods that make it easier for them to be able to be manipulated in a program.
Methods Usagekeys
Get all the keys from dictionary
values()
Get all values from dictionary
items()
Get all key value pairs from dictionary
get()
Gets the value of specified key
Working with Files
Working with Files
Analyzing or working with data from a local file in a program is called file handling. Suppose you have student academic records in a file and want to calculate percentages of each student. Calculating it one by one in a file is a tiring task. This work would be easier if the file could be loaded to a program, and you could directly apply the operation on all the data in the file.
To work with files in Python, you need to open the file (within the program), perform an operation on it (read or write), and then close the file. Simple, right? Let's see how it looks in code.
```py
f = open("filename.txt")
f.read()
f.close()
```
```java
try {
File f = new File("filename.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
} catch(IOException e) {
e.printStackTrace();
}
```
```javascript
var fs = require('fs');
fs.readFile('filename.txt', 'utf8', function(err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
```
```cpp
#include<fstream>
#include<iostream>
#include<string>
int main() {
std::string line;
std::ifstream file("filename.txt");
if (file.is_open()) {
while (getline (file, line)) {
std::cout << line << '\n';
}
file.close();
}
else std::cout << "Unable to open file";
return 0;
}
```
```csharp
using System;
using System.IO;
class Program {
static void Main() {
try {
StreamReader sr = new StreamReader("filename.txt");
string line;
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
sr.Close();
}
catch(Exception e){
Console.WriteLine("Exception: " + e.Message);
}
finally {
Console.WriteLine("Executing finally block.");
}
}
}
```
```go
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("filename.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
```
File Handling Mental Model
File handling is easier when you picture where the data lives.
A file starts outside your program on disk. Python uses open() to create a connection, your code reads or writes through that connection, and close() releases it when the work is done.

File Handling Lifecycle
File handling is easiest to remember as a small lifecycle: open the file, do the operation, then close the file.
The key mental model: your program does not magically own the file. It creates a connection to it, uses that connection, then releases it.

From Data to Files
Dictionaries and files solve related but different problems. A dictionary is data already in your program's memory; a file is data stored outside the program.
The key file-handling pattern is a small lifecycle: open → read or write → close.

Writing to Files
Python provides an in-built function open() which opens the file inside the program. You need to specify the name of the file which needs to be opened in a string within the parenthesis. By default, the file opens in reading mode. You can specify different modes according to how you want to use the file in your program.
If you want to write to a file, you'd do something like this.
```py
f = open("filename.txt", "w")
f.write("Writing in file")
f.close()
```
```java
FileWriter fileWriter = new FileWriter("filename.txt");
fileWriter.write("Writing in file");
fileWriter.close();
```
```javascript
var fs = require('fs');
fs.writeFile("filename.txt", "Writing in file", function(err) {
if (err) {
return console.log(err);
}
});
```
```cpp
#include <fstream>
std::ofstream file("filename.txt");
if (file.is_open()) {
file << "Writing in file";
file.close();
}
```
```csharp
using (StreamWriter sw = new StreamWriter("filename.txt")) {
sw.WriteLine("Writing in file");
}
```
```go
f, err := os.Create("filename.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
_, err2 := f.WriteString("Writing in file")
if err2 != nil {
log.Fatal(err2)
}
```
Appending to Files
However, this would overwrite the file if there was any previous information in it. To avoid that, we can append to a file using a different mode like this.
```py
f = open("filename.txt", "a")
f.write("Appending to existing file")
f.close()
```
```java
FileWriter fileWriter = new FileWriter("filename.txt", true);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println("Appending to existing file");
printWriter.close();
```
```javascript
const fs = require('fs');
fs.appendFile('filename.txt', 'Appending to existing file', function (err) {
if (err) throw err;
});
```
```cpp
#include <fstream>
std::ofstream outfile;
outfile.open("filename.txt", std::ios_base::app);
outfile << "Appending to existing file";
```
```csharp
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"filename.txt", true))
{
file.WriteLine("Appending to existing file");
}
```
```go
f, err := os.OpenFile("filename.txt", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer f.Close()
if _, err = f.WriteString("Appending to existing file"); err != nil {
panic(err)
}
```
Note
Important! Make sure you specify the file path correctly while opening files! And that the files are in the proper directory!
Let's test your knowledge regarding the different Python features discussed in this lesson!
Choose the Right Mode
When opening a file, the mode is the important decision.
Use write mode when replacing the file contents is intended. Use append mode when the existing contents should stay and new text should be added at the end. In both cases, the file path still has to point to the right location.

Write vs Append
The safest way to remember file modes is to picture what happens to the existing contents.
"w" starts fresh and can overwrite what was there. "a" keeps the existing file and adds new content at the end.

File Mode Checklist
When opening files, the mode changes the outcome. The most important distinction here is that "w" replaces file contents, while "a" adds to the end.
Also check the path before blaming the code: Python can only open the file if it is looking in the right directory.

Multiple Choice
What is the correct way to check if a value 42 exists in the dictionary below?
employees = {"a": 10, "b": 53, "c": 42, "d": 88}
HashMap<String, Integer> employees = new HashMap<String, Integer>();
employees.put("a", 10);
employees.put("b", 53);
employees.put("c", 42);
employees.put("d", 88);
var employees = {"a": 10, "b": 53, "c": 42, "d": 88};
std::unordered_map<std::string, int> employees;
employees["a"] = 10;
employees["b"] = 53;
employees["c"] = 42;
employees["d"] = 88;
Dictionary<string, int> employees = new Dictionary<string, int>()
{
{"a", 10},
{"b", 53},
{"c", 42},
{"d", 88}
};
employees := map[string]int{"a": 10, "b": 53, "c": 42, "d": 88}
True or False
Is the given function correct, and is this a valid method to read first n characters of a file?
def read_file(filename, n):
f = open(filename, "r")
data = f.read(n)
print(data)
read_file("filename.txt", 10)
import java.nio.file.*;
public class Main {
public static void main(String[] args) {
try {
String content = new String(Files.readAllBytes(Paths.get("filename.txt")));
if (content.length() > 10) {
System.out.println(content.substring(0, 10));
} else {
System.out.println(content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
const fs = require('fs');
fs.readFile('filename.txt', (err, data) => {
if (err) throw err;
console.log(data.toString('utf8').substring(0,10));
});
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream file("filename.txt");
if (file.is_open())
{
std::string data;
std::getline(file, data, '\0');
std::cout << data.substr(0, 10);
file.close();
}
return 0;
}
using System;
using System.IO;
class Program
{
static void Main()
{
string contents = File.ReadAllText("filename.txt");
Console.WriteLine(contents.Substring(0, 10));
}
}
package main
import (
"io/ioutil"
"fmt"
)
func main() {
data, err := ioutil.ReadFile("filename.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data[:10]))
}
One Pager Cheat Sheet
One Pager Cheat Sheet
- This tutorial provides an introduction to
installingandworkingwith Python, with a focus on the key points of installation and setup, and an overview of some of its basic features. - To download and install Python
free of chargeon youroperating system, you can visit the official website here. - Python is a
free and open-sourceprogramming language that is accessible and popular for a variety of purposes. -
Pythonprogramming is easy to understand due to its simple syntax resembling the English language. - Number objects of the
int,float,complex, andbooldata types can all be considerednumbersin Python. - By
creating functionsand reusing them, we canmodularizeour code to make program execution more efficient. - - A Python function is defined once with
def, then executed whenever it is called. - - A Python function is defined once with
def, then reused by calling its name. - - A Python function is defined once with
def, then executed whenever it is called. - The definition is invalid because it does not include the
keyword def, the function name within parenthesis with the parameters, a colon and an indented code blockfor the function body. - Lists in Python are powerful data structures, allowing us to store multiple values of different data types in a single variable and perform operations on them using
indexingandlist methods. - Dictionaries in Python are an efficient way to store
key: valuepairs of data, particularly for representing data wherekeysneed to be associated with particularvalues. - Dictionaries have methods, such as
keys(),values(),items(), andget(), to help them be manipulated in a program. - By opening, reading and closing a file in Python, you can easily manipulate data from the file within your program.
- - File handling follows a simple path: file on disk → open connection → read/write data → close connection.
- - File handling follows the pattern: open → read/write → close.
- - File handling moves data between disk and your program using the open/read-or-write/close lifecycle.
- The
open()function in Python can be used to open a file, with the name specified in astringwithin the parenthesis, in eitherreadingorwritingmode. - We can
appendto a file to avoid overwriting any previous information. - Be sure to
specifythe file path correctly while opening files and ensure they are in the correct directory. - - Use
wto replace file contents,ato add to the end, and always verify the file path. - - Use
"w"to overwrite a file and"a"to append without deleting existing contents. - - Use
"w"to overwrite,"a"to append, and always verify the file path. - The
in operatorand thevalues()method can be used to check if the value42exists in theemployeesdictionary. - Yes, the given
open()andread(n)function is correct and should successfully read the firstncharacters of the filefilename.txt.