1. What is Python?
Python is a high-level scripting language. It is interpreted and object-oriented. The code is easy to read.
Full lesson: Python3 intro
44 questions about Python with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
Python is a high-level scripting language. It is interpreted and object-oriented. The code is easy to read.
Full lesson: Python3 intro
Download Python from the official site and run the installer. Check the install with the version command.
python3 --version
Full lesson: Python3 install
The first character must be a letter or an underscore. The other parts can be letters, digits, or underscores. Identifiers are case-sensitive.
count = 1
Count = 2
Full lesson: Python3 basic syntax
Use the if keyword and a condition. Add a colon and an indented block. Use else for the other case.
x = 5
if x > 0:
print("positive")
else:
print("not positive")
Full lesson: Python if else
Use a for loop. The loop visits each item in the list.
for item in [1, 2, 3]:
print(item)
Full lesson: Python for loop2
Use the def keyword and a function name. Add a colon and an indented body. Use return to send a value back.
def add(a, b):
return a + b
print(add(2, 3))
Full lesson: Python3 function
Use the join() method. Call it on the delimiter string. Pass the list as the argument.
my_list = ['Hello', 'World', 'Python']
result = ' '.join(my_list)
print(result)
Full lesson: Python join list
Use the + operator. It makes a new list with the items of both lists.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)
Full lesson: Python merge lists
Use the index() method. It returns the start position of the substring. It raises an exception if the substring is not there.
text = "runoob"
print(text.index("noo"))
Full lesson: Python3 string index
Use the rindex() method. It returns the position of the last match. It raises an exception if there is no match.
text = "runoob"
print(text.rindex("o"))
Full lesson: Python3 string rindex
Use the sum() function. It adds all numbers in the list and returns the total.
numbers = [1, 2, 3, 4]
print(sum(numbers))
Full lesson: Python list sum
Put the parent class name in parentheses after the subclass name. The subclass gets the attributes and methods of the parent. The subclass can override a method.
class Animal:
def speak(self):
return "sound"
class Dog(Animal):
def speak(self):
return "bark"
Full lesson: Python subclass inheritance
Use the import statement. Then use the module name and a dot to call its items.
import math
print(math.sqrt(16))
Full lesson: Python3 module
Use the Differ class from the difflib module. Call compare() on the two split strings. The result shows the changed lines.
import difflib
differ = difflib.Differ()
diff = differ.compare(["a"], ["b"])
print('\n'.join(diff))
Full lesson: Python string difference
The join() method needs strings. A list of numbers causes a TypeError. Convert each number to a string first.
nums = [1, 2, 3]
print(' '.join(str(n) for n in nums))
Full lesson: Python3 string join
A list is a sequence of values. You write the values between square brackets and separate them with commas.
colors = ["red", "green", "blue"]
Full lesson: Python3 list
Use square brackets after the list name. The first index is 0.
colors = ["red", "green", "blue"]
print(colors[1])
Full lesson: Python3 list
Use square brackets with a start index and an end index. The slice includes the start index and stops before the end index.
text = "Hello World!"
print(text[0:5])
Full lesson: Python3 string
Use a slice with no indexes to make a shallow copy. The new list has the same items as the old list.
li1 = [4, 8, 2]
li2 = li1[:]
print(li2)
Full lesson: Python copy list
Use the not operator on the list. An empty list is false in a condition.
items = []
if not items:
print("The list is empty")
Full lesson: Python empty list
Call the clear method on the list. The list stays but it has no items.
items = [1, 2, 3]
items.clear()
print(items)
Full lesson: Python clear list
Call the sort method on the list. The method changes the list in place.
nums = [3, 1, 2]
nums.sort()
print(nums)
Full lesson: Python sort list
Use the open function with a mode string. The with keyword closes the file for you.
with open("test.txt", "wt") as f:
f.write("Hello")
with open("test.txt", "rt") as f:
print(f.read())
Full lesson: Python3 file io
Import StringIO from the io module. You can read and write the buffer like a file.
from io import StringIO
buf = StringIO()
buf.write("Hello")
print(buf.getvalue())
Full lesson: Python stringio
Convert each list to a set. Then use the union operator on the two sets.
a = [1, 2, 3]
b = [3, 4, 5]
print(set(a) | set(b))
Full lesson: Python list union
Python raises an IndexError. The index must be less than the length of the list.
items = [1, 2]
print(items[5]) # IndexError
Full lesson: Python3 list
The = operator binds a second name to the same list object. A change through one name appears through the other name.
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
Full lesson: Python copy list
The loop uses an internal index. When you remove an item, the later items move left and the loop skips some of them.
items = [1, 2, 3]
for x in items:
items.remove(x)
print(items) # [2]
Full lesson: Python3 loop
The condition stays true, so the loop never stops. You must change the variable inside the loop body.
x = 0
while x < 3:
print(x)
x += 1
Full lesson: Python3 loop
Python looks for a file with the module name and the .py suffix. A wrong name causes a ModuleNotFoundError.
import mymodule # ModuleNotFoundError if mymodule.py is missing
Full lesson: Python3 module
Type python and the file name. The interpreter reads the file and runs the code.
python test.py
Full lesson: Python3 tutorial
Use the class keyword and a class name. Put the class body under the class line.
class Dog:
def bark(self):
print("Woof")
Full lesson: Python3 class
Call the class name like a function. The result is a new object of that class.
d = Dog()
d.bark()
Full lesson: Python3 class
Use one loop for the rows and one loop for the columns. Print each product on the same row.
for i in range(1, 10):
for j in range(1, i + 1):
print('{}x{}={}'.format(j, i, i * j), end=' ')
print()
Full lesson: Python3 99 table
Call the sorted() function on the list. The function returns a new sorted list and keeps the old list as it is.
numbers = [3, 1, 2]
new_list = sorted(numbers)
print(numbers)
print(new_list)
Full lesson: Python sort list
Run the uv pip install command and give the package name. The tool adds the package to your environment.
uv pip install requests
Full lesson: Uv tutorial
Shell sort compares items that are far apart. It then reduces the gap until the gap is zero.
def shellSort(arr):
n = len(arr)
gap = int(n / 2)
while gap > 0:
for i in range(gap, n):
temp = arr[i]
gap = int(gap / 2)
Full lesson: Python shellsort
Use the with keyword and the open() function. Python closes the file for you at the end of the block.
with open("test.txt", "rt") as in_file:
text = in_file.read()
print(text)
Full lesson: Python3 file io
Use the not operator on the list. An empty list gives False, so not gives True.
my_list = []
if not my_list:
print("The list is empty")
Full lesson: Python empty list
The = sign does not copy a list. It gives a second name to the same list object.
a = [1, 2]
b = a
b.append(3)
print(a)
Full lesson: Python copy list
The sort() method changes the list in place. It returns None, so you must not assign its result to a variable.
numbers = [3, 1, 2]
numbers.sort()
print(numbers)
Full lesson: Python sort list
A method needs self as its first parameter. Without self, Python cannot find the object.
class Dog:
def bark(self):
print("Woof")
Full lesson: Python3 class
Mode "wt" removes the old file content. Use mode "rt" to read a file that already has text.
with open("test.txt", "rt") as in_file:
print(in_file.read())
Full lesson: Python3 file io
A set holds each item only one time. The union of two sets drops all repeated values.
list1 = [1, 2, 3]
list2 = [3, 4]
print(list(set(list1).union(set(list2))))
Full lesson: Python list union