Print to Console
print("Hello")Prints a value to standard output.
Python syntax quick reference for common tasks, from the official Python documentation. Every item below is clearly marked as a shortcut, command, or syntax reference.
print("Hello")Prints a value to standard output.
def greet(name):
return f"Hi {name}"Defines a reusable function.
if x > 0:
...
elif x == 0:
...
else:
...Runs code depending on a condition.
for item in items:
print(item)Loops over each item in a sequence.
nums = [1, 2, 3]Creates an ordered, changeable list.
nums.append(4)Adds an item to the end of a list.
len(items)Returns the number of items.
d = {"a": 1, "b": 2}Creates key-value pairs.
Prints a value to standard output.
print("Hello")Defines a reusable function.
def greet(name):
return f"Hi {name}"Runs code depending on a condition.
if x > 0:
...
elif x == 0:
...
else:
...Loops over each item in a sequence.
for item in items:
print(item)Creates an ordered, changeable list.
nums = [1, 2, 3]Adds an item to the end of a list.
nums.append(4)Returns the number of items.
len(items)Creates key-value pairs.
d = {"a": 1, "b": 2}Inserts values into a string.
f"Total: {total:.2f}"Handles an error without crashing.
try:
...
except ValueError as e:
...Imports a module or a name from it.
from math import sqrtReads a line of text typed by the user.
name = input("Name: ")Adds a comment that Python ignores.
# commentLoops a fixed number of times.
for i in range(10):Repeats while a condition is true.
while x < 10:
x += 1Builds a new list from an expression.
[x * 2 for x in nums if x > 0]Defines a class with an initializer.
class Dog:
def __init__(self, name):
self.name = nameReads a file and closes it automatically.
with open("file.txt") as f:
text = f.read()Converts between numbers and strings.
int("5"), float("2.5"), str(10)Gets index and value while looping.
for i, item in enumerate(items):Gets part of a list or string.
items[1:4]Returns a value or a default if the key is missing.
d.get("key", default)Loops over keys and values.
for k, v in d.items():Splits a string into a list.
"a,b".split(",")Joins a list of strings with a separator.
", ".join(words)Writes text to a file.
with open("out.txt", "w") as f:
f.write(text)Runs code only when the file is run directly.
if __name__ == "__main__":Returns a new sorted list.
sorted(items, key=len, reverse=True)Creates a small anonymous function.
square = lambda x: x * xCreates a collection of unique items.
s = {1, 2, 3}Raises an error on purpose.
raise ValueError("bad value")Creates an immutable sequence.
point = (1, 2)It covers 32 common Python patterns and examples, including Print to Console, Define a Function, If / Elif / Else, For Loop, Create a List.
Yes. Each reference page includes a copyable code example.
Check the linked documentation for language or runtime version requirements. Libraries, file paths, terminal quoting and environment settings can differ across systems; no blanket platform compatibility is implied.