Learn Python

The extraordinarily incomplete source for learning Python basics by Allex Veldman

Check Installation

  • Open the command line
  • [Windows] Win + R > cmd
  • [Mac] Cmd + Space > Terminal.app

							[Allex Veldman ~]$ python --version
							Python 3.10.7
						

Hello World

python hello-world.py
							
								print("Hello World")
							
						

Hello World (Interactive)


							>>> print("Hello World")
							Hello World
						

Variables

						
							a_int = 1  # Integer
							a_float = 3.2  # Floating-point number
							a_string = "This is a string"
							# List of values
							a_list = [1, 2, 3, a_float]
							# key-value pairs
							a_dict = {"key1": a_int, "key2": "some text"}
						
					

Functions

						
							def add(left, right):
							    """Add two numbers together"
							    return left + right
							
							result = add(1, 2)
						
					

Input

						
							>>> name = input("What's your name?: ")
							What's your name?: Allex

							>>> print("Your name is", name)
							Your name is Allex
						
					

Solution

							
								filename = input("[filename]: ")

								data = input("What would you like to write?: ")
								with open(filename, mode="w") as file:
									file.write(data)
							
						

Solution 2

							
								from pathlib import Path

								filename = input("[filename]: ")
								out_file = Path(filename)
								data = input("[content]: ")
								out_file.write_text(data)
							
						

Solution

							
								workbook = Workbook()
								worksheet = workbook.create_sheet("Cities", 0)

								data = [
									["Name", "City"],
									["Jarle", "Amsterdam"],
									["Lisa", "Eindhoven"],
									["Allex", "Eindhoven"],
								]

								for row in data:
									worksheet.append(row)
								
								workbook.save("assignment.xlsx")
							
						

Mutability

objects like lists and dicts are mutable, so they can be changed.
							
								def increment_list_element(index, input_list):
								    """increment and return the element `index` in `input_list`"""
								    input_list[index] += 1
								    return input_list[index]
								
								x = list(range(5))
								print(x)
								value = increment_list_element(2, x)
								print(value)
								print(x)

								[0, 1, 2, 3, 4]
								3
								[0, 1, 3, 3, 4]