TL;DR: This guide is a complete Python syntax reference: 100 core concepts, from variables to virtual environments, each with a plain-English definition and a working example. Built for beginners, career switchers, and working developers who need a fast, accurate lookup rather than a full tutorial.

This Python cheatsheet covers 100 core concepts with practical examples, making it easy to find the syntax you need without digging through lengthy documentation. It starts with Python basics, including variables, data types, and operators, then covers strings, lists, tuples, sets, dictionaries, conditionals, loops, and functions.

The guide also includes advanced and real-world Python patterns to help you write and understand Python code more effectively. Whether you're learning Python, preparing for a coding interview, or looking for a quick syntax refresher, use the sections below to find the concept you need, check the example, and get back to coding.

Python Cheatsheet Quick Reference

A quick summary of the most-searched Python syntax.

#SyntaxPurposeExampleRelated Python Concept
1print()Print output to the consoleprint("Hello, World!")Basics & Syntax
2x = 5Assign a value to a variablename = "Alex"Variables
3f"{x}"Format a string with embedded valuesf"Age: {age}."f-strings
4len()Get the length of a sequencelen("Python") → 6Strings, Lists
5list[start:end]Slice part of a sequencenums[1:3]List/String Slicing
6for x in y:Iterate over a sequencefor i in range(5): print(i)Loops
7while x:Repeat while a condition is truewhile n > 0: n -= 1Loops
8if / elif / elseBranch based on a conditionif x > 0: print("positive")Conditionals
9def f():Define a reusable functiondef greet(name): return f"Hi {name}"Functions
10lambdaDefine a small anonymous functionsquare = lambda x: x**2Functions
11[x for x in y]Build a list with a comprehension[n*2 for n in range(5)]List Comprehension
12{k: v for ...}Build a dict with a comprehension{n: n**2 for n in range(3)}Dict Comprehension
13try / exceptHandle errors gracefullytry: 1/0 except ZeroDivisionError: passException Handling
14class MyClass:Define a class (blueprint for objects)class Dog: passOOP
15import moduleBring in external functionalityimport mathModules
16*args, **kwargsAccept variable numbers of argumentsdef f(*args, **kwargs): passFunctions
17.append()Add an item to the end of a listnums.append(4)List Methods
18.split()Split a string into a list"a,b".split(",")String Methods
19.join()Join a list into a string",".join(["a","b"])String Methods
20dict.get()Safely fetch a dict valued.get("key", "default")Dictionaries
21yieldReturn a value lazily from a generatordef gen(): yield 1Generators
22@decoratorWrap a function to extend behaviour@staticmethodDecorators
23with open()Open and auto-close a filewith open("f.txt") as f: f.read()File Handling
24range()Generate a sequence of numbersrange(0, 10, 2)Loops
25enumerate()Loop with index + valuefor i, v in enumerate(lst):Loops, Lists

Python Basics & Syntax

How to print, store, and name things before you do anything else with them.

1. What is the print() function in Python?

The print() function displays output on the console.

print("Hello, World!")

2. How do you assign a variable in Python?

Variable assignment stores a value under a name using the = operator.

x = 5

3. How do you write comments in Python?

Comments begin with # and are ignored by the interpreter.

# calculates total price

4. How do you take user input in Python?

The input() function reads user input as a string.

name = input("Enter your name: ")

5. What does the type() function do?

It returns the data type of a value.

type(5)  # <class 'int'>

6. What are the core data types in Python?

The core types are int, float, str, and bool.

x = 5; y = 5.0; z = "hi"; b = True

7. What is type casting in Python?

Type casting converts a value from one type to another. Remember that input() always returns a string, so cast it before doing arithmetic.

int("5"); str(5); float("5.0")

8. How do you assign multiple variables?

Several variables can be assigned in one statement.

a, b, c = 1, 2, 3

9. Why is indentation important?

Indentation defines code blocks. Code inside an if statement must be indented, and mixing tabs and spaces causes an IndentationError.

10. What are reserved keywords?

Words Python reserves for syntax, such as and, or, not, if, else, def, and class.

Python Operators

Every symbol Python uses to do math, compare values, or combine conditions.

11. What are arithmetic operators?

They include + - * / % // **. Watch out for mixing up // and /.

7 // 2  # 3
7 % 2   # 1

12. What are comparison operators?

They compare two values and return a Boolean: == != > < >= <=.

5 == 5  # True

13. What are logical operators?

They combine Boolean expressions: and, or, not.

x > 0 and x < 10

14. What are assignment operators?

They assign or update values: = += -= *= /=.

x += 1

15. What are identity operators?

They check whether two variables reference the same object: is and is not.

a is b

16. What are membership operators?

They check whether a value exists in a collection: in and not in.

"a" in "cat"  # True

17. What are bitwise operators?

They work on binary representations: & | ^ ~ << >>.

5 & 3  # 1

18. What is the ternary operator?

A one-line conditional expression.

"even" if x % 2 == 0 else "odd"

19. What is operator precedence?

It determines evaluation order. Multiplication is evaluated before addition.

2 + 3 * 4  # 14

20. What is the walrus operator?

The := operator assigns a value within an expression (Python 3.8, PEP 572).

if (n := len(data)) > 10:
    print(n)

Python Strings

Cleaning, searching, splitting, and formatting text.

21. How do you find the length of a string?

len() returns the number of characters.

len("Python")  # 6

22. How do you convert to uppercase?

Use .upper().

"hi".upper()  # "HI"

23. How do you convert to lowercase?

Use .lower().

"HI".lower()  # "hi"

24. How do you remove leading and trailing whitespace?

Use .strip().

" hi ".strip()  # "hi"

25. How do you strip only the left or right side?

.lstrip() removes from the left, .rstrip() from the right.

" hi".lstrip()  # "hi"

26. How do you split a string into a list?

Use .split() with a separator.

"a,b,c".split(",")  # ['a', 'b', 'c']

27. How do you join a list into a string?

Call .join() on the separator string, not on the list.

"-".join(["a", "b"])  # "a-b"

28. How do you replace text in a string?

Use .replace().

"cat".replace("c", "b")  # "bat"

29. How do you find a substring?

.find() returns the index, or -1 if not found.

"hello".find("l")  # 2

30. What is the difference between find() and index()?

.find() returns -1 when the substring is missing; .index() raises an error.

31. How do you count occurrences of a substring?

Use .count().

"banana".count("a")  # 3

32. How do you check the start of a string?

Use .startswith().

"file.txt".startswith("file")  # True

33. How do you check the end of a string?

Use .endswith().

"file.txt".endswith(".txt")  # True

34. How do you format a string with format()?

The .format() method fills placeholders.

"{} is {}".format("x", 5)  # "x is 5"

35. What are f-strings?

F-strings embed variables and expressions directly in strings (Python 3.6, PEP 498).

f"{name} is {age}"

36. How do you capitalize the first letter?

Use .capitalize().

"python".capitalize()  # "Python"

37. How do you capitalize each word?

Use .title().

"hello world".title()  # "Hello World"

38. How do you check for digits or letters?

.isdigit() checks for digits and .isalpha() checks for letters.

"123".isdigit()  # True

39. How do you slice a string?

Use s[start:end:step].

"Python"[1:4]  # "yth"

40. How do you check whether a substring exists?

Use the in operator.

"th" in "Python"  # True

Python Lists

How to build, change, and read Python's most-used data structure.

41. How do you create a list?

Use square brackets.

nums = [1, 2, 3]

42. How do you add an item to the end?

Use .append().

nums.append(4)

43. How do you insert at a specific position?

Use .insert(index, value).

nums.insert(0, 10)

44. How do you remove an item by value?

.remove() deletes the first matching value.

nums.remove(2)

45. How do you remove and return an item?

.pop() removes the last item by default; an index can be given.

nums.pop()

46. How do you add multiple items?

Use .extend(). Calling .append() with a list nests it as a single item.

nums.extend([5, 6])

47. How do you sort a list in place?

Use .sort().

nums.sort()

48. How do you create a sorted copy?

sorted() returns a new list and leaves the original unchanged.

sorted(nums, reverse=True)

49. How do you reverse a list?

Use .reverse() (in place).

nums.reverse()

50. How do you find the number of items?

Use len().

len(nums)

51. How do you find the index of an item?

.index() returns the first match's position.

nums.index(3)

52. How do you count occurrences of an item?

Use .count().

nums.count(2)

53. How do you copy a list?

.copy() makes a shallow copy. Nested lists or dicts are still shared with the original.

new_list = nums.copy()

54. How do you remove all items?

Use .clear().

nums.clear()

55. How do you slice a list?

Use list[start:end]; the end index is excluded.

nums[1:3]

56. What is a list comprehension?

A concise way to build a new list from an iterable.

[x**2 for x in range(5)]

57. How do you loop with an index?

enumerate() gives both index and value.

for i, v in enumerate(nums):
    print(i, v)

58. How do you combine lists element by element?

zip() pairs elements from multiple iterables.

zip([1,2], ['a','b'])

59. How do you find the minimum and maximum?

min() returns the smallest value and max() the largest.

max(nums)

60. How do you sum the values?

sum() adds the values in an iterable.

sum(nums)

Tuples, Sets & Dictionaries

The other three core collections: an immutable tuple, a unique-items set, or a key-value dictionary.

61. How do you create a tuple?

Use parentheses.

point = (1, 2)

62. What is tuple unpacking?

It assigns individual tuple values to separate variables.

x, y = point

63. Why are tuples immutable?

Their elements cannot be changed after creation; trying raises a TypeError.

point[0] = 5  # TypeError

64. How do you convert an iterable into a tuple?

Use tuple().

tuple([1, 2, 3])  # (1, 2, 3)

65. How do you create a set?

Use curly braces or set(). Sets hold unique, unordered items.

s = {1, 2, 3}

66. How do you add an item to a set?

Use .add().

s.add(4)

67. What is the difference between remove() and discard()?

Both remove an item, but .discard() does not raise an error if the item is absent.

s.remove(1)
s.discard(99)  # no error

68. How do you combine two sets?

Use .union().

s1.union(s2)

69. How do you find common elements between two sets?

Use .intersection().

s1.intersection(s2)

70. How do you find elements unique to one set?

Use .difference().

s1.difference(s2)

71. How do you create a dictionary?

A dictionary stores key-value pairs in curly braces.

d = {"name": "Alex", "age": 30}

72. How do you access a dictionary value?

Use the key inside square brackets.

d["name"]  # "Alex"

73. How do you retrieve keys, values, and items?

Use .keys(), .values() and .items().

for k, v in d.items():
    print(k, v)

74. How do you add or update dictionary values?

.update() adds new pairs or updates existing ones.

d.update({"age": 31})

75. How do you safely retrieve a dictionary value?

.get() doesn't raise an error for a missing key and accepts a default.

d.get("email", "N/A")

76. What is dictionary comprehension?

A concise way to create dictionaries.

{x: x**2 for x in range(5)}

Conditional Statements

Running one block of code instead of another based on a condition.

77. What is an if statement?

It runs a block of code when a condition is true.

if x > 0:
    print("positive")

78. How does if/else work?

The if block runs when the condition is true; otherwise the else block runs.

if x > 0:
    print("positive")
else:
    print("not positive")

79. What is elif?

elif checks an additional condition when the previous if was false.

if x > 0:
    print("positive")
elif x == 0:
    print("zero")
else:
    print("negative")

80. What is a nested if statement?

One conditional placed inside another.

if x > 0:
    if x % 2 == 0:
        print("positive and even")

Loops

Repeating code with for and while, and controlling it with break and continue.

81. What is a for loop?

It iterates over the elements of a sequence or iterable.

for i in [1, 2, 3]:
    print(i)

82. What is a while loop?

It repeats code while a condition remains true.

while n > 0:
    n -= 1

83. What does break do?

break immediately exits a loop.

for i in range(10):
    if i == 5:
        break

84. What does continue do?

continue skips the rest of the current iteration and moves to the next.

for i in range(5):
    if i == 2:
        continue
    print(i)

85. What does range() do?

It generates a sequence of numbers, commonly used in loops.

range(0, 10, 2)  # 0, 2, 4, 6, 8

Functions

Packaging logic into reusable blocks, arguments, defaults, and the lambda shorthand.

86. How do you define a function?

Use the def keyword.

def greet(name):
    return f"Hi {name}"

87. What does return do?

It sends a value from a function back to the caller.

def add(a, b):
    return a + b

88. What are default arguments?

They provide fallback values for parameters. Defaults are evaluated once, when the function is defined, so a mutable default like items=[] is reused across calls.

def greet(name="friend"):
    return f"Hi {name}"

89. What are *args and **kwargs?

*args accepts any number of positional arguments; **kwargs accepts any number of keyword arguments.

def f(*args, **kwargs):
    pass

90. What is a lambda function?

A small anonymous function defined with the lambda keyword.

square = lambda x: x**2

Advanced Python

Where scripting turns into software engineering: decorators, generators, error handling, and classes.

91. What are advanced comprehensions?

They build lists, dictionaries, or sets while applying conditions.

[x for x in range(20) if x % 2 == 0]

92. What are decorators?

Decorators use the @ syntax to wrap a function and extend its behaviour.

class A:
    @staticmethod
    def hello():
        print("hi")

93. What are generators?

Generators produce values lazily, one at a time, using yield.

def gen():
    yield 1
    yield 2

94. How does try/except handle errors?

Code that may fail goes in try; the handler goes in except. Catch a specific exception type rather than a bare except:.

try:
    1/0
except ZeroDivisionError:
    pass

95. What are classes and objects?

Classes are blueprints for objects; each instance is an object created from the class.

class Dog:
    pass

rex = Dog()

Practical Python

The everyday tasks: reading and writing files, working with JSON, and setting up virtual environments.

96. How do you read a file?

Use open() with a context manager.

with open("f.txt") as f:
    data = f.read()

97. How do you write to a file?

Open the file in "w" mode. Specifying encoding="utf-8" avoids mismatches between Windows and Linux.

with open("f.txt", "w", encoding="utf-8") as f:
    f.write("hello")

98. How do you work with JSON?

Use the built-in json module.

import json
json.loads('{"a":1}')  # {'a': 1}

99. How do you import modules?

The import statement lets you reuse functionality from modules and libraries.

import math
math.sqrt(16)

100. What are virtual environments?

They isolate project dependencies so packages for one project don't interfere with another. Remember to activate the environment before installing packages.

python -m venv env
pip install requests

Conclusion: Your Go-To Python Reference

That's the complete picture, from print() statements to decorators and generators. This Python cheatsheet walks through every core building block you'll actually use day to day. The goal wasn't just to list syntax but to organise it the way your brain reaches for it: basics first, then operators and data types, then control flow, then the more advanced patterns that show up once you're comfortable with the fundamentals. And once you're ready to put these building blocks into practice, Simplilearn's free python courses are a good next stop for structured, hands-on learning.

Key Takeaways

A few ways to get the most out of this guide:

Bookmark this page. Python's standard library is huge, but the 100 items above cover the 20% of syntax you'll use 80% of the time.

Use the Quick Reference table when you just need a syntax reminder mid-project.

Practice the "Practical Python" section (#96–100). Reading/writing files, JSON handling, and virtual environments trip up even intermediate developers.

Revisit "Advanced Python" (#91–95) once the basics feel automatic; decorators, generators, and OOP are what separate scripting from software engineering in Python.

Python rewards consistency more than memorization. The syntax on this page starts feeling like muscle memory once you've written it out a few dozen times yourself, not just read it.

Footnotes

Last updated: September 21, 2026.

Python's current stable release is 3.14.7 (Source: Python.org, as of September 2026). Python version and release facts verified against python.org/downloads on the last updated date of this article.

Authored by: Kusum Saini, Director & Principal Architect at Simplilearn

Reviewed by: Jitendra Kumar, Chief Technology Officer at Simplilearn

Python® and the Python logo are trademarks of the Python Software Foundation. This is independent reference content, not officially affiliated with or endorsed by the PSF.

For guided, hands-on practice beyond this reference, see Simplilearn's Free Python course.

Our Software Development Program Duration and Fees

Software Development programs typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Full Stack Development Program with Generative AI20 weeks$4,000