Comments are notes you add to your code to explain what it does. They don't affect the program's operation but help you and others understand the code better.
# This is a comment explaining the next line of code user = "JDoe" # Comment after code
You can perform basic arithmetic like addition, subtraction, multiplication, and division in Python. These are done using symbols like +, -, *, and /.
# Simple 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 an existing variable. It makes the code shorter and easier to read. It can also be used to join strings together.
# Using += to update a number counter = 0 counter += 10 # Same as counter = counter + 10 # Using += to concatenate strings message = "Part 1" message += " and Part 2"
Variables are like containers that hold data. You can change what data they hold by assigning new values to them. You can use names that are easy to remember for these containers.
# Example of variables user_name = "codey" user_id = 100 verified = False # Changing the value of a variable points = 100 points = 120
The % symbol gives you the remainder after dividing one number by another. It's useful for checking if a number is divisible by another number.
# Finding remainders remainder1 = 8 % 4 # Remainder is 0 remainder2 = 12 % 5 # Remainder is 2
Whole numbers, or integers, are numbers without any fractions or decimals. They can be positive, negative, or zero.
# Whole numbers chairs = 4 tables = 1 broken_chairs = -2 sofas = 0 # Decimal numbers (not integers) lights = 2.5 left_overs = 0.0
You can join (concatenate) strings using the + operator. Strings are sequences of characters, like words or sentences.
# Joining strings first = "Hello" second = "World" result = first + " " + second # Result is "Hello World"
Sometimes, mistakes in code can cause errors. Python will show you where it found the mistake, like a misplaced symbol or typo.
# Example of a syntax error if False ISNOTEQUAL True: ^ SyntaxError: invalid syntax
Dividing any number by zero is not allowed and causes an error. Python reports this as a ZeroDivisionError.
# Example of division by zero numerator = 100 denominator = 0 result = numerator / denominator ZeroDivisionError: division by zero
Strings are sequences of characters. They can be enclosed in single or double quotes, and can span multiple lines if needed.
# Examples of strings user = "User Full Name" game = 'Monopoly' long_string = "This string is broken up \ over multiple lines"
You can't use the + operator to assign values. The + operator is for addition or concatenation, not for assignment.
age = 7 + 5 = 4 File "", line 1 SyntaxError: can't assign to operator
If you try to use a variable that hasn't been defined, Python will show an error. This helps you find and fix typos or missing code.
# Example of using an undefined variable misspelled_variable NameError: name 'misspelled_variable' is not defined
Decimal numbers, or floats, include a fraction part, like 3.14. They are used when you need more precision than whole numbers.
# Example of decimal numbers pi = 3.14159 meal_cost = 12.99 tip_percent = 0.20
The print() function shows information on the screen. You can print text, numbers, or results from calculations.
print("Hello World!") # Displays text print(100) # Displays a number pi = 3.14159 print(pi) # Displays the value of a variable
A lambda function is a quick, unnamed function you can use for simple operations. It's handy for tasks like mapping or filtering data in one line.
# Syntax for a lambda function lambda x: x + 1
Lambda functions can take inputs (arguments) to perform a task. They are used for short, one-off functions where a full function definition isn't necessary.
# Example of a lambda function add = lambda x, y: x + y print(add(5, 3)) # Output: 8
Parameters are placeholders in a function that hold the values you pass to it. They let the function know what data to work with.
# Example function with parameters def greet(name): print("Hello, " + name) greet("Alice") # Output: Hello, Alice
Functions can take multiple parameters. This allows them to handle more complex tasks by providing several pieces of information.
# Function with multiple parameters def prepare_for_school(backpack, pencil_case): if backpack == 'full' and pencil_case == 'full': print("Ready for school!") prepare_for_school('full', 'full') # Output: Ready for school!
Functions in Python can be created with the def keyword and can have parameters. They let you write reusable code to perform specific tasks.
# Defining and using a function def add_one(x): return x + 1 print(add_one(2)) # Output: 3 print(add_one(5)) # Output: 6
Python uses indentation to define the blocks of code that belong to a function. Proper indentation is crucial for defining what code is inside the function.
# Example of indentation def calculate_sum(number): sum = 0 for x in range(number): sum += x return sum print(calculate_sum(5)) # Output: 10
You call a function by writing its name followed by parentheses. This allows you to execute the function's code whenever needed.
# Calling a function def say_hello(): print("Hello, world!") say_hello() # Output: Hello, world!
Functions can return a value using the return keyword. This lets you use the result of the function in other parts of your program.
# Function that returns a value def describe_item(store, item, price): return store + " is selling " + item + " for " + price print(describe_item("The Market", "apples", "$2")) # Output: The Market is selling apples for $2
When calling a function, you can specify arguments by name, allowing you to pass them in any order. Default values can be provided for parameters.
# Using keyword arguments def volume(length=1, width=1, depth=1): return length * width * depth print(volume(length=2, width=3, depth=4)) # Output: 24
A function can return more than one value. These values can be captured and used individually.
# Function returning multiple values def square_numbers(x, y, z): return x*x, y*y, z*z squared = square_numbers(3, 4, 5) print(squared) # Output: (9, 16, 25)
Variables in functions are local to the function unless specified otherwise. This means they only exist within the function’s code block.
# Example of variable scope def my_function(): a = 10 print(a) # Output: 10 my_function() print(a) # Error: a is not defined outside the function
Global variables are accessible from anywhere in the code, not just inside functions. You can use them across different functions.
# Example of global variable a = "Hello" def print_message(): print(a) # Output: Hello print_message()
Parameters in functions act as local variables. They only exist within the function and can be used only there.
# Example of local variable def display_value(value): print(value) display_value(7) # Output: 7 print(value) # Error: value is not defined outside the function
In a loop, the `break` keyword stops the loop immediately, no matter where you are in the loop. After the loop stops, the program continues with the code that follows it.
numbers = [0, 254, 2, -1, 3] for num in numbers: if num < 0: print("Negative number detected!") break print(num) # Output: # 0 # 254 # 2 # Negative number detected!
List comprehension is a quick way to create lists. It uses brackets with an expression and a `for` loop to generate a new list. Here, it creates a list of squares for even numbers between 0 and 9.
# Create a list of squares for even numbers from 0 to 9 result = [x**2 for x in range(10) if x % 2 == 0] print(result) # Output: [0, 4, 16, 36, 64]
A `for` loop is used to repeat actions for each item in a list. The loop goes through each item one by one and performs the actions inside the loop.
# Print each number in the list nums = [1, 2, 3, 4, 5] for num in nums: print(num) # Output: # 1 # 2 # 3 # 4 # 5
The `continue` keyword in a loop skips the rest of the code inside the loop for that iteration and moves on to the next iteration. Here, it skips printing negative numbers.
big_number_list = [1, 2, -1, 4, -5, 5, 2, -9] # Print only positive numbers: for i in big_number_list: if i < 0: continue print(i) # Output: # 1 # 2 # 4 # 5 # 2
`range()` generates a sequence of numbers, which can be used in a loop to repeat actions a specific number of times.
# Print numbers 0, 1, 2 for i in range(3): print(i) # Print "WARNING" 3 times for i in range(3): print("WARNING") # Output: # 0 # 1 # 2 # WARNING # WARNING # WARNING
An infinite loop keeps running until you manually stop it or it meets a stopping condition. Here, a loop runs once because it sets `hungry` to `False` after the first iteration.
# This loop will only run once hungry = True while hungry: print("Time to eat!") hungry = False # This loop will run 5 times i = 1 while i < 6: print(i) i = i + 1 # Output: # Time to eat! # 1 # 2 # 3 # 4 # 5
Nested loops have one loop inside another. They are used to perform actions on items within items, such as names within groups. Each loop works through its set of actions separately.
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]] # Loop through each group and each name within the group for group in groups: for name in group: print(name) # Output: # Jobs # Gates # Newton # Euclid # Einstein # Feynman
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!