Comments are notes you add to your code to help explain what it does. Python ignores these notes when running your code.
# This is a comment username = "JDoe" # This is a comment after some code
In Python, you can perform basic math operations like addition, subtraction, multiplication, and division.
# Examples of basic math result = 10 + 5 # Adds 10 and 5 result = 20 - 3 # Subtracts 3 from 20 result = 4 * 2 # Multiplies 4 by 2 result = 10 / 2 # Divides 10 by 2 result = 10 % 3 # Finds the remainder when 10 is divided by 3 result = 2 ** 3 # Raises 2 to the power of 3
The += operator is a shorthand way to add a value to a variable. It also works with strings to combine text.
# Using the += operator counter = 0 counter += 10 # Adds 10 to counter # This is the same as writing: counter = counter + 10 # You can also use += to combine strings message = "Hello, " message += "World!" # Combines the two strings
Variables are used to store information like numbers or text. You can change the value of a variable after you create it.
# Examples of variables user_name = "codey" user_id = 101 verified = True # Changing the value of a variable points = 50 points = 75 # Now points is 75
The % operator is used to find the remainder when one number is divided by another.
# Using the % operator remainder = 8 % 3 # The remainder of 8 divided by 3 is 2
Integers are whole numbers, meaning they have no decimals. They can be positive, negative, or zero.
# Examples of integers chairs = 4 broken_chairs = -2 sofas = 0 # Non-integer example (with a decimal) lights = 2.5
You can combine two or more strings into one using the + operator. This is called string concatenation.
# Combining strings first = "Hello, " second = "World!" result = first + second # Result is "Hello, World!"
If your code has a mistake, Python will stop running it and show you an error message to help you fix the problem.
# Example of an error if False ISNOTEQUAL True: ^ SyntaxError: invalid syntax
Dividing by zero is not allowed in Python. If you try, Python will give you an error called ZeroDivisionError.
numerator = 10 denominator = 0 result = numerator / denominator # This will cause an error # ZeroDivisionError: division by zero
Strings are sequences of characters like letters, numbers, and symbols. You create strings by putting text between quotes.
# Examples of strings user_name = "Alice" user_game = 'Chess' long_string = "This string is broken up \ over multiple lines"
A SyntaxError happens when there is a mistake in the way your code is written, making it impossible for Python to understand.
# Example of a SyntaxError age = 7 + 5 = 4 File "", line 1 SyntaxError: can't assign to operator
A NameError occurs when you try to use a variable or function that hasn’t been defined yet in your code.
# Example of a NameError unknown_variable NameError: name 'unknown_variable' is not defined
Floating point numbers are numbers with a decimal point. They are used for more precise measurements.
# Examples of floating point numbers pi = 3.14159 meal_cost = 12.99 tip_percent = 0.2
The print() function in Python displays text or values on the screen. You can print strings, numbers, and even variables.
# Examples of using the print function print("Hello, World!") print(100) pi = 3.14159 print(pi)
The break keyword lets you stop a loop immediately, even if the loop hasn’t finished all its cycles. After the break, the program moves on to the code that comes after the loop.
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 concise way to create lists in Python. It allows you to generate a list by applying an expression to each item in an existing list or sequence, optionally filtering out some elements.
# Create a list of squares for even numbers between 0 and 9 result = [x**2 for x in range(10) if x % 2 == 0] print(result) # Output: # [0, 4, 16, 36, 64]
A for loop in Python allows you to repeat a block of code for each item in a list or sequence. The loop assigns each item to a temporary variable, which you can then use within the loop to perform actions.
nums = [1, 2, 3, 4, 5] for num in nums: print(num) # Output: # 1 # 2 # 3 # 4 # 5
The continue keyword in Python skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.
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
The range() function in Python is useful for creating a loop that runs a specific number of times. It generates a sequence of numbers, which you can loop through.
# Print the 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 occurs when a loop never ends. To prevent this, ensure that the condition of the loop eventually becomes false. Otherwise, the loop will keep running indefinitely.
# This loop runs once hungry = True while hungry: print("Time to eat!") hungry = False # This loop runs five times counter = 1 while counter < 6: print(counter) counter += 1 # Output: # Time to eat! # 1 # 2 # 3 # 4 # 5
A while loop in Python repeats a block of code as long as a specified condition is true. Be careful to update the condition within the loop to prevent infinite loops.
count = 0 while count < 3: print("Counting...") count += 1 # Output: # Counting... # Counting... # Counting...
A nested loop is when one loop runs inside another loop. This is useful when working with multiple lists or when you need to compare items across different sequences.
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]] # Outer loop goes through each list in groups for group in groups: # Inner loop goes through each name in the current group for name in group: print(name) # Output: # Jobs # Gates # Newton # Euclid # Einstein # Feynman
A lambda function is a quick, one-line function that doesn't have a name. It's useful when you need a small function just for a short task, like filtering or mapping data. Here's how to define a lambda function:
lambda arguments: expression # Example: Multiply a number by 2 multiply_by_two = lambda x: x * 2 print(multiply_by_two(5)) # Output: 10
When a function needs some information to do its job, we give it that information through parameters. These are like placeholders in the function that get replaced with actual values when the function runs.
def greet(name): print("Hello, " + name + "!") greet("Alice") # Output: Hello, Alice!
Functions can take more than one piece of information as input. For example, a function might need a character, a setting, and a skill to create a sentence.
def make_sentence(character, setting, skill): print(character + " is in " + setting + " using " + skill) make_sentence("Lara", "the forest", "archery") # Output: Lara is in the forest using archery
Just like you wouldn't go to school without your backpack and pencil case, some functions need multiple inputs to work properly. You can define these inputs by listing them as parameters in the function.
def prepare_for_school(backpack, lunchbox): if backpack == 'ready' and lunchbox == 'packed': print("Ready for school!") prepare_for_school('ready', 'packed') # Output: Ready for school!
In Python, indentation (spacing at the beginning of a line) is used to define blocks of code. For example, all the code inside a function must be indented to show that it belongs to that function.
def add_numbers(a, b): # This line is part of the function return a + b print(add_numbers(2, 3)) # Output: 5
To use a function you've defined, just write its name followed by parentheses. If the function has parameters, you put the values inside the parentheses.
def say_hello(): print("Hello!") say_hello() # Output: Hello!
Functions can give back a result using the return keyword. This is useful when you want to use the result in other parts of your program.
def add(a, b): return a + b result = add(3, 4) print(result) # Output: 7
In Python, you can pass values to a function by naming the parameters, which allows you to give them in any order. If you don't provide a value, the function will use a default value.
def introduce(name, age=18): print(f"My name is {name} and I am {age} years old.") introduce(name="Alice", age=25) # Output: My name is Alice and I am 25 years old. introduce(name="Bob") # Output: My name is Bob and I am 18 years old.
A function can return more than one value by separating them with commas. This is helpful when you want to get several results from a single function call.
def calculate_squares(x, y): return x * x, y * y x_squared, y_squared = calculate_squares(2, 3) print(x_squared, y_squared) # Output: 4 9
The scope of a variable determines where in the code it can be used. Variables created inside a function can't be used outside of it, but those created outside can be accessed by the function.
number = 10 # Global scope def display_number(): number = 5 # Local scope inside the function print(number) display_number() # Output: 5 print(number) # Output: 10
The .format() method allows you to insert values into a string by placing them inside empty braces ({}). You can specify the values directly in the order you want them to appear.
msg = 'You have {} new messages.' print(msg.format(5)) # Output: You have 5 new messages.
The .lower() method in Python converts all uppercase letters in a string to lowercase.
greeting = "HELLO THERE" print(greeting.lower()) # Output: hello there
The .strip() method removes unwanted characters from the beginning and end of a string. By default, it removes spaces, but you can specify other characters to remove as well.
text = '---Hello World---' print(text.strip('-')) # Output: Hello World
The .title() method capitalizes the first letter of each word in a string.
book_title = "the great gatsby" print(book_title.title()) # Output: The Great Gatsby
The .split() method divides a string into a list of words based on a specified separator. By default, it splits at spaces.
sentence = "Python is fun" print(sentence.split()) # Output: ['Python', 'is', 'fun']
The .find() method returns the index (position) of the first occurrence of a specified substring within a string. If the substring is not found, it returns -1.
quote = "To be or not to be" print(quote.find("be")) # Output: 3
The .replace() method replaces all occurrences of a specified substring within a string with another substring.
greeting = "Hello world" print(greeting.replace('world', 'Python')) # Output: Hello Python
The .upper() method converts all lowercase letters in a string to uppercase.
name = "john doe" print(name.upper()) # Output: JOHN DOE
The .join() method combines a list of words into a single string, with each word separated by a specified separator.
words = ["Python", "is", "awesome"] sentence = " ".join(words) print(sentence) # Output: Python is awesome
Special characters like quotation marks can be included in a string by using a backslash (\) to escape them.
quote = "She said, \"Hello!\"" print(quote) # Output: She said, "Hello!"
You can check if a substring exists within a string using the 'in' keyword, which returns True if the substring is found, otherwise False.
text = "Welcome to Python" print("Python" in text) # Output: True
Strings are like lists of characters, and you can access individual characters using their index. You can also slice the string to get a substring.
word = "Python" print(word[0]) # Output: P print(word[1:4]) # Output: yth
You can use a for loop to go through each character in a string, one by one.
word = "Hello" for letter in word: print(letter) # Output: # H # e # l # l # o
The len() function returns the number of characters in a string, including spaces and special characters.
word = "Python" print(len(word)) # Output: 6
You can combine (concatenate) multiple strings into one using the + operator.
part1 = "Hello, " part2 = "world!" message = part1 + part2 print(message) # Output: Hello, world!
In Python, strings are immutable, meaning they cannot be changed after they are created. If you try to modify a string, you will create a new string instead.
word = "Hello" new_word = word.replace("H", "J") print(new_word) # Output: Jello
When working with strings, trying to access a character at an index that doesn't exist will raise an IndexError. Always ensure the index is within the string's range.
word = "Hello" print(word[5]) # This will raise an IndexError
Python has a built-in module called datetime that makes it easy to work with dates and times. You can create date, time, or a combination of both (timestamp) using datetime's date(), time(), and datetime() functions.
import datetime # Creating a specific date specific_date = datetime.date(2023, 9, 3) print(specific_date) # Output: 2023-09-03 # Creating a specific time specific_time = datetime.time(14, 30, 0) print(specific_time) # Output: 14:30:00 # Creating a full timestamp (date + time) specific_timestamp = datetime.datetime(2023, 9, 3, 14, 30, 0) print(specific_timestamp) # Output: 2023-09-03 14:30:00
In Python, you can rename imported modules using the 'as' keyword. This is useful when you want to shorten the name of a module to make your code easier to write.
# Renaming the calendar module as 'cal' for easier use import calendar as cal print(cal.month_name[1]) # Output: January
Modules are pieces of code in Python that you can import and use in your own programs. There are three common ways to import modules: importing the entire module, importing specific functions from a module, or importing everything from a module (not recommended).
# Importing the entire module import math print(math.sqrt(16)) # Output: 4.0 # Importing only a specific function from a module from math import sqrt print(sqrt(25)) # Output: 5.0 # Importing everything from a module (not recommended) from math import * print(factorial(5)) # Output: 120
The random module in Python lets you generate random numbers and choose random items from a list. The random.randint() function returns a random integer within a specified range, and random.choice() picks a random item from a sequence.
import random # Generate a random integer between 1 and 10 random_number = random.randint(1, 10) print(random_number) # Pick a random item from a list colors = ['red', 'green', 'blue'] random_color = random.choice(colors) print(random_color)
There are three main ways to import modules in Python: importing the whole module, importing specific parts of a module, and importing everything from a module. It's best to avoid importing everything, as it can cause confusion in your code.
# Assuming file1.py contains a function called greet # file1.py # def greet(): # return "Hello" # Importing the entire module import file1 print(file1.greet()) # Output: Hello
In a Python dictionary, you can access a value by using its key inside square brackets. To change a value, use the key with the assignment operator (=). If the key already exists, the old value will be replaced. If you try to access a key that doesn’t exist, Python will show a KeyError.
my_dict = {"song": "Estranged", "artist": "Guns N' Roses"} print(my_dict["song"]) my_dict["song"] = "Paradise City" print(my_dict["song"]) # Output: Paradise City
A Python dictionary is enclosed in curly braces ({}) and contains key-value pairs separated by commas. Each key is followed by a colon and then its value. Keys and values can be of any data type.
my_dict = {"first_name": "John", "last_name": "Doe"} print(my_dict) # Output: {'first_name': 'John', 'last_name': 'Doe'}
You can combine two dictionaries using the .update() method. The .update() method adds the key-value pairs from one dictionary into another. If the key already exists, the value is updated.
dict1 = {'color': 'blue', 'shape': 'circle'} dict2 = {'color': 'red', 'number': 42} dict1.update(dict2) print(dict1) # Output: {'color': 'red', 'shape': 'circle', 'number': 42}
Python dictionaries can hold various types of values like strings, numbers, lists, or even other dictionaries. Keys, however, must be immutable types like strings, numbers, or tuples.
my_dict = { 'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'cycling'], 'address': {'city': 'New York'} } print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'cycling'], 'address': {'city': 'New York'}}
When using the .update() method, the values from the second dictionary replace the values in the first dictionary if the keys are the same. New key-value pairs are added if the keys do not already exist in the first dictionary.
my_dict = {1: "Apple", 2: "Banana"} update_dict = {2: "Blueberry", 3: "Cherry"} my_dict.update(update_dict) print(my_dict) # Output: {1: 'Apple', 2: 'Blueberry', 3: 'Cherry'}
You can use .keys() to get all the keys, .values() to get all the values, and .items() to get all key-value pairs in a dictionary.
my_dict = {"a": "apple", "b": "banana", "c": "cherry"} print(my_dict.keys()) # Output: dict_keys(['a', 'b', 'c']) print(my_dict.values()) # Output: dict_values(['apple', 'banana', 'cherry']) print(my_dict.items()) # Output: dict_items([('a', 'apple'), ('b', 'banana'), ('c', 'cherry')])
The .get() method retrieves the value for a given key in a dictionary. If the key doesn’t exist, it returns None or a default value if specified.
my_dict = {'name': 'Victor'} print(my_dict.get('name')) # Output: Victor print(my_dict.get('nickname')) # Output: None print(my_dict.get('nickname', 'No nickname available')) # Output: No nickname available
The .pop() method removes a key-value pair from the dictionary using the specified key and returns its value. If the key doesn’t exist, it raises a KeyError.
museums = {'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre', 'Athens': 'The Acropolis Museum'} removed_value = museums.pop('Athens') print(museums) # Output: {'Washington': 'Smithsonian Institution', 'Paris': 'Le Louvre'} print(removed_value) # Output: The Acropolis Museum
When you open a file in Python using the open() function, it creates a file object. This file object lets you read from or write to the file. You can use the 'with' statement to manage the file automatically.
with open('example.txt') as file: content = file.read() print(content) # This code opens 'example.txt', reads its content, and prints it.
To read one line at a time from a file, use the .readline() method. Each call to .readline() will give you the next line in the file.
with open('example.txt') as file: first_line = file.readline() print(first_line) # This code reads and prints the first line of 'example.txt'.
JSON files store data in a structured format. You can use Python's json module to read a JSON file and convert its data into a dictionary for easy access.
import json with open('data.json') as file: data = json.load(file) print(data) # This code reads 'data.json' and prints its content as a dictionary.
To add new content to the end of an existing file without overwriting it, open the file with the 'a' (append) mode. If the file doesn't exist, it will be created.
with open('example.txt', 'a') as file: file.write('New line of text.') # This code appends 'New line of text.' to 'example.txt'.
To write to a file and replace its existing content, open the file with the 'w' (write) mode. If the file already contains data, it will be erased.
with open('example.txt', 'w') as file: file.write('This is new content.') # This code overwrites 'example.txt' with 'This is new content.'.
To read all lines of a file at once into a list, use the .readlines() method. Each element in the list represents a line from the file.
with open('example.txt') as file: lines = file.readlines() print(lines) # This code reads all lines from 'example.txt' into a list and prints it.
When writing data to a file in CSV format, you can use the csv.DictWriter class to handle dictionaries and write them to the file.
import csv with open('data.csv', 'w', newline='') as file: writer = csv.DictWriter(file, fieldnames=['name', 'age']) writer.writeheader() writer.writerow({'name': 'Alice', 'age': 30}) # This code writes a header and one row to 'data.csv'.
To read the entire content of a file into a single string, use the .read() method. By default, files are opened in read mode ('r').
with open('example.txt') as file: content = file.read() print(content) # This code reads the whole content of 'example.txt' and prints it.
The __repr__() method in Python defines how an object should be represented as a string. This method should return a string that gives a clear representation of the object, usually including details that help recreate the object.
class Employee: def __init__(self, name): self.name = name def __repr__(self): return f'Employee(name={self.name!r})' john = Employee('John') print(repr(john)) # Output: Employee(name='John')
In Python, methods are functions defined inside a class that operate on instances of that class. The first parameter of a method is always the instance of the class itself, typically named self.
class Dog: def bark(self): print('Woof!') charlie = Dog() charlie.bark() # Output: Woof!
To use a class in Python, you first need to create an instance of the class. This is called instantiation. You can then use this instance to access methods and properties defined in the class.
class Car: pass my_car = Car() # Now 'my_car' is an instance of the Car class
Class variables are shared by all instances of a class. They are defined inside the class but outside any methods and have the same value across all instances of the class.
class MyClass: class_variable = 'I am a class variable' instance1 = MyClass() instance2 = MyClass() print(instance1.class_variable) # Output: I am a class variable print(instance2.class_variable) # Output: I am a class variable
The __init__() method initializes a new object when it is created. It sets up the initial state of the object by defining properties based on the parameters passed to the method.
class Animal: def __init__(self, name, sound): self.name = name self.sound = sound cat = Animal('Cat', 'Meow') print(cat.name) # Output: Cat print(cat.sound) # Output: Meow
The type() function in Python tells you what type of data a variable holds, such as integer, string, or list.
number = 10 print(type(number)) # Output:text = 'Hello' print(type(text)) # Output:
A class in Python is like a blueprint for creating objects. You define a class using the class keyword, and inside the class, you define methods and variables that the objects will use.
class Animal: def __init__(self, name): self.name = name # Define a new instance lion = Animal('Lion')
The dir() function lists all the attributes and methods of an object or module. It helps you see what is available for use in that object or module.
class Employee: def __init__(self, name): self.name = name def greet(self): return f'Hello, my name is {self.name}' print(dir(Employee)) # Lists all attributes and methods of the Employee class
In Python, __main__ indicates the top-level script environment. When a Python script is run, the code under the __main__ check will execute, allowing you to run code only if the file is run directly, not when imported as a module.
if __name__ == '__main__': print('This script is running directly') else: print('This script is being imported')
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!