0% found this document useful (0 votes)
27 views6 pages

Python Programming Rules Handbook

Stuff

Uploaded by

kedemig
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views6 pages

Python Programming Rules Handbook

Stuff

Uploaded by

kedemig
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Rules of Programming in Python

Student handbook.

1. Case Sensitivity

Python is case-sensitive, meaning it treats uppercase and lowercase letters as different. So


'name', 'Name', and 'NAME' are three separate identifiers.

Correct Example:

student_name = "Alice"
print(student_name)

Incorrect Example:

student_name = "Alice"
print(Student_name) # NameError

Rule: Always use consistent letter case when naming your variables and functions.

2. Indentation
Python uses indentation (spaces) to define which code belongs to a block. If your indentation is
wrong, the program will not run.

Correct Example:

if True:
print("This is indented correctly")
print("So this belongs to the if block")

Incorrect Example:
if True:
print("This is wrong!") # IndentationError

Rule: Always use 4 spaces per indentation level. Never mix tabs and spaces.

3. Comments
Comments are notes in code that Python ignores. They help explain what the code is doing.

Correct Example:

# This program greets the user


name = input("Enter your name: ")
print("Hello,", name)

"""
This section:
1. Asks for user name
2. Prints a greeting
"""

Rule: Leave a space after # and write clear comments.

4. Naming Variables (Identifiers)


Variable naming rules:
1. Must start with a letter or underscore
2. Can contain letters, numbers, or underscores
3. Cannot start with a number
4. Cannot use Python keywords

Correct Example:

age = 25
student_name = "Alice"
_total = 100

Incorrect Example:

2nd_place = "Bob" # starts with a number


if = 10 # 'if' is a reserved keyword
student-name = "Ali" # '-' is not allowed

Rule: Use snake_case for variables/functions, PascalCase for classes, and ALL_CAPS for
constants.

Note

1. snake_case: This format uses lowercase letters with words separated by underscores. It’s
typically used for variables and functions in languages like Python. For example: `my_variable`,
`calculate_total()`.

2. PascalCase: In this style, each word starts with a capital letter and there are no spaces or
underscores. It's often used for naming classes in many programming languages. For example:
`MyClass`, `VehicleType`.

3. ALL_CAPS: This convention is used for constants, where all letters are uppercase and words
are usually separated by underscores. It helps distinguish constants from variables. For example:
`MAX_VALUE`, `DEFAULT_TIMEOUT`.

These conventions help in making code more readable and maintainable by providing a
consistent way to name different types of entities.

5. Print and Input


Correct Example:

name = input("Enter your name: ")


print("Hello", name)

Incorrect Example:

print "Hello" # Missing parentheses (Python 2 syntax)

Rule: Always use parentheses in print() and input().


6. Conditions and Loops
Correct Example:

x = 10
if x > 5:
print("Greater than 5")
else:
print("5 or less")

Incorrect Example:

if x > 5
print("Greater than 5") # Missing colon and indentation

Rule: Always end condition statements with a colon (:) and indent the next line.

7. Functions
Correct Example:

def greet(name):
print("Hello,", name)

greet("Solomon")

Incorrect Example:

def greet(name)
print("Hello,", name) # Missing colon and indentation

Rule: Always put ':' at the end of 'def' and indent the body of the function.

8. Importing Modules
Correct Example:

import math
print([Link](16))

Incorrect Example:

print(sqrt(16)) # 'sqrt' not defined because math wasn’t imported

Rule: Use 'import module_name' or 'from module_name import function_name'.

9. Errors and Exceptions


Correct Example:

try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("That’s not a number!")

Rule: Always use try...except when user input or risky operations might fail.

10. Code Style (PEP 8)


PEP 8 is Python’s official style guide — it helps make your code readable and professional.
Key rules include:
1. Use 4 spaces per indent
2. Leave 2 blank lines between functions/classes
3. Add spaces around operators
4. Keep lines under 79 characters
5. Use meaningful names

Correct Example:

def calculate_total(price, tax):


"""Return total amount after tax."""
total = price + tax
return total

Incorrect Example:
def cal(p,t):return p+t # unreadable and violates PEP 8

Rule: Write clear, readable code — not just short code.

Summary Table
Rule Correct Use Avoid

Case sensitivity Use consistent lowercase Mixing 'Name' and 'name'


Indentation 4 spaces No indentation/mixing tabs
Comments # use space after hash Overusing or unclear
comments
Variable names snake_case Starting with numbers or
symbols
Printing print('Hello') print 'Hello'
Conditions if x > 0: Missing colon or indentation
Functions def name(): Forgetting a colon or
parentheses
Imports import math Using a function before
import
Exceptions try...except Ignoring possible errors
Style Follow PEP 8 Messy, unclear code

Common questions

Powered by AI

Error messages related to indentation and naming in Python serve as immediate feedback mechanisms that help maintain code quality. Indentation errors, such as IndentationError, highlight discrepancies in the code structure crucial for correct block definitions. Similarly, naming errors like NameError indicate misuse or misreference of identifiers. Developers should address these by reviewing the scope of blocks defined by whitespace and ensuring naming consistency with Python's case sensitivity and syntax rules. This attention to detail prevents logical errors and aids in developing maintainable and bug-free code .

Inconsistent adherence to Python's styling rules, like those outlined in PEP 8, can complicate team collaboration and slow down the development cycle. When team members follow varied styles, it can lead to misunderstanding or misinterpretation of the code, decreased readability, and increased cognitive load when switching between codebases. This inconsistency can result in more time spent on reviewing and merging code and increased potential for bugs. Maintaining a consistent style ensures smoother communication, easier debugging, and a streamlined development process .

Python's case sensitivity means that variable names like 'name', 'Name', and 'NAME' are all distinct identifiers, each potentially referencing different variables. This can prevent common errors in code readability and logic, compared to case-insensitive languages where such distinctions aren't made, potentially leading to overwriting or confusing variable assignments. Consistent use of case in Python helps to delineate variable functions and identities clearly, aligning with the convention of using snake_case for variables and functions, PascalCase for classes, and ALL_CAPS for constants, further reinforcing readability .

Using 'try...except' blocks in Python is crucial for handling potential exceptions that may arise from unpredictable user inputs or operations that might fail, such as division by zero or invalid inputs for conversion. By implementing exception handling, programs can gracefully manage errors without crashing, providing user-friendly error messages and potentially allowing recovery or alternative actions. This practice not only prevents application breakdowns but also enhances user experience and program robustness by anticipating and addressing edge cases effectively .

Correctly importing modules in Python is crucial because it allows access to functions and classes that are not built into Python by default. Failing to import a module correctly will result in NameError when trying to use a function or class from that module, as they are not available in the global namespace. Proper imports ensure that external functionalities are explicitly linked to the code, maintaining clear dependencies and enabling the effective use of Python's extensive libraries to enhance a program's capabilities .

Python's variable naming conventions significantly improve clarity and organization by providing a visual distinction between different types of entities. Snake_case (like student_name or calculate_total) is used for variables and functions, enhancing readability by clearly identifying purpose and use without spaces. PascalCase (such as MyClass or VehicleType) is for classes, easily distinguishing them from functions and variables. ALL_CAPS (like MAX_VALUE or DEFAULT_TIMEOUT) is reserved for constants, signaling values that should not be altered. These conventions create a uniform and navigable codebase, allowing developers to quickly discern the role and scope of each element .

PEP 8 is Python's official style guide that provides comprehensive rules to improve code readability and maintainability. Key differences include the emphasis on using 4 spaces per indentation level, leaving 2 blank lines between functions and classes, and maintaining lines under 79 characters. It also recommends meaningful naming conventions and adding spaces around operators. In contrast, general programming practices may not adhere strictly to these standards, leading to varied styles of indentation, inconsistent spacing, and mixed naming conventions. By following PEP 8, developers create more consistent and readable code, making it easier to maintain and collaborate across projects .

Indentation in Python is critical for defining the scope and nesting of loops and conditionals. Unlike languages that use braces, where the scope is defined within curly brackets, Python uses indentation to determine the block of code that belongs to each loop or conditional statement. This means that the correct level of indentation is necessary to ensure that the related code blocks execute as intended under the control structure. Incorrect indentation results in errors and logic misalignments, as Python will not execute the misplaced code correctly .

Incorrect indentation in Python can lead to errors such as IndentationError, causing the program to fail execution entirely because Python relies on indentation to define code blocks. This is unlike many other languages that use braces or keywords to define blocks. The rule in Python is to consistently use 4 spaces per indentation level, and mixing spaces and tabs is discouraged. Incorrect indentation disrupts the logical structure of code, making it difficult for interpreters and developers to understand the intended relationships between operations .

Using incorrect variable naming conventions in Python can lead to confusion about variable roles and contribute to bugs. If a developer uses inconsistent casing, like 'Name' instead of 'name', it might inadvertently create new variables or lead to logic errors. Similarly, using symbols or starting a variable with a number, both forbidden practices, can result in syntax errors during execution. Poor naming can obscure the intention behind variables and functions, making the code harder to read and maintain, ultimately affecting overall program functionality and clarity .

You might also like