Comments are notes in your code that the computer ignores. They help you understand and explain what your code does.
# This is a comment on a single line user = "JDoe" # This is a comment next to code
Python can perform basic math operations like addition, subtraction, multiplication, and division.
# Basic math operations result = 10 + 30 # Addition result = 40 - 10 # Subtraction result = 50 * 5 # Multiplication result = 16 / 4 # Division result = 25 % 2 # Modulo (remainder) result = 5 ** 3 # Exponentiation (5 raised to the power of 3)
The += operator adds a value to a variable and updates it. It can also be used to join strings.
# Using += operator counter = 0 counter += 10 # Increases counter by 10 message = "Part 1" message += " Part 2" # Joins two strings
Variables store data such as numbers or text. You can change their values as needed.
# Example variables user_name = "codey" user_id = 100 verified = False # Changing a variable's value points = 100 points = 120
The % operator gives the remainder of a division. It helps determine how many times a number can be divided by another with a remainder.
# Using modulo operator zero = 8 % 4 # Remainder is 0 nonzero = 12 % 5 # Remainder is 2
Integers are whole numbers without decimals. They can be positive, negative, or zero.
# Examples of integers chairs = 4 tables = 1 broken_chairs = -2 sofas = 0 # Examples of non-integers lights = 2.5 left_overs = 0.0
Strings (text) can be combined using the + operator to make longer messages.
# Combining strings first = "Hello " second = "World" result = first + second # Joins strings long_result = first + second + "!"
Errors occur when there are mistakes in your code, like typos or incorrect syntax.
if False ISNOTEQUAL True: ^ SyntaxError: invalid syntax
Dividing a number by zero is not allowed and results in an error.
# Division by zero error numerator = 100 denominator = 0 bad_results = numerator / denominator ZeroDivisionError: division by zero
Strings are sequences of characters. They can be enclosed in single or double quotes.
# Examples of strings user = "User Full Name" game = 'Monopoly' longer = "This string is broken up \ over multiple lines"
Syntax errors happen when the code doesn’t follow Python’s rules, such as using incorrect operators or missing symbols.
age = 7 + 5 = 4 File "", line 1 SyntaxError: can't assign to operator
NameErrors occur when you try to use a variable that doesn’t exist or was mistyped.
misspelled_variable_name NameError: name 'misspelled_variable_name' is not defined
Floating point numbers (floats) include decimals, representing non-integer numbers.
# Examples of floats pi = 3.14159 meal_cost = 12.99 tip_percent = 0.20
The print() function displays text or numbers on the screen.
print("Hello World!") print(100) pi = 3.14159 print(pi)
Lambda functions are small, unnamed functions used for simple operations in a single line of code.
# Defining a lambda function add_one = lambda x: x + 1 print(add_one(5)) # Output will be 6
Parameters are variables in functions that accept input values when the function is called.
# Function with parameters def write_a_book(character, setting, special_skill): print(character + " is in " + setting + " practicing her " + special_skill)
Functions can take multiple inputs (parameters) to perform more complex tasks.
# Function with multiple parameters def ready_for_school(backpack, pencil_case): if (backpack == 'full' and pencil_case == 'full'): print("I'm ready for school!")
Functions are blocks of reusable code that perform specific tasks. They can be defined once and used multiple times.
# Defining a function def my_function(x): return x + 1 # Using the function print(my_function(2)) # Output: 3 print(my_function(3 + 5)) # Output: 9
Indentation shows which lines of code are part of the function. Indent all code inside a function.
# Function with indentation def testfunction(number): print("Inside the function") sum = 0 for x in range(number): sum += x return sum print("Outside the function")
To use a function, call it by writing its name followed by parentheses.
doHomework()
Functions can return values using the return keyword. These values can be used later in the program.
# Function that returns a value def sales(grocery_store, item_on_sale, cost): print(grocery_store + " is selling " + item_on_sale + " for " + cost) sales("The Farmer’s Market", "toothpaste", "$1")
Keyword arguments specify which value goes to which parameter by name, not just by position.
def findvolume(length, width, depth): print("Length = " + str(length)) print("Width = " + str(width)) print("Depth = " + str(depth)) return length * width * depth # Calling the function with keyword arguments volume = findvolume(width=2, depth=3, length=4) print(f"Volume: {volume}")
Default parameters have preset values that are used if no other value is provided.
# Function with default parameters def favorite_color(color="blue"): print("My favorite color is " + color) # Calling the function favorite_color() favorite_color("green")
If statements run code only if a condition is true.
# If statement example if 5 > 3: print("5 is greater than 3")
If-else statements provide an alternative block of code to execute if the condition is false.
# If-else statement example if 5 > 10: print("5 is greater than 10") else: print("5 is not greater than 10")
Elif (else if) allows checking multiple conditions.
# Elif statement example score = 85 if score >= 90: print("Grade A") elif score >= 80: print("Grade B") else: print("Grade C")
For loops repeat a block of code for each item in a sequence, such as a list or range.
# For loop example for i in range(5): print(i)
While loops continue to execute code as long as a condition remains true.
# While loop example count = 0 while count < 5: print(count) count += 1
Use the break statement to stop a loop before it finishes all iterations.
# Breaking out of a loop for i in range(10): if i == 5: break print(i)
Use the continue statement to skip the rest of the loop's code and start the next iteration.
# Continue statement example for i in range(10): if i % 2 == 0: continue print(i) # Only odd numbers will be printed
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!