top of page
Writer's pictureAdisorn O.

PYTHON Cheat Sheet


Here is a basic cheat sheet for structured programming in Python:


**1. Variables and Data Types**

```python

# Strings

string_var = "Hello, World!"


# Numbers

int_var = 7

float_var = 7.0


# Lists

list_var = [1, 2, 3, "four", "five"]


# Dictionaries

dict_var = {"key1": "value1", "key2": "value2"}

```


**2. Control Structures**

```python

# If statement

if condition:

# do something

elif other_condition:

# do something else

else:

# do another thing


# For loop

for item in iterable:

# do something with item


# While loop

while condition:

# do something

```


**3. Functions**

```python

# Define a function

def function_name(parameter1, parameter2):

# do something

return result


# Call a function

output = function_name(argument1, argument2)

```


**4. Classes and Objects**

```python

# Define a class

class ClassName:

def __init__(self, parameter1):

self.attribute1 = parameter1

def method_name(self, parameter2):

# do something


# Create an object

object_name = ClassName(argument1)


# Call a method

output = object_name.method_name(argument2)

```


**5. Error Handling**

```python

try:

# code that might raise an error

except SomeSpecificError:

# what to do if SomeSpecificError happens

finally:

# code that runs whether an error happened or not

```


**6. Modules**

```python

# Import a module

import module_name


# Use a function from a module

output = module_name.function_name(argument1, argument2)


# Import a function directly

from module_name import function_name

```


This is a very basic cheat sheet. Python can do much more, but these are some of the fundamental elements of structured programming in Python. Always remember to follow Python's syntax rules when using these structures.

3 views
bottom of page