Python Quick Reference Guide for 2023 - IQCode

PYTHON: A HIGH-LEVEL LANGUAGE

Python is a popular high-level, interpreted, and object-oriented programming language with dynamic binding and inbuilt data structures. It has an easy-to-write and understand syntax that appeals to both novice and experienced programmers. Due to its extensive library support and high applicability, Python is capable of developing highly versatile and scalable software products.

TENETS OF PYTHON

The Zen of Python comprises a set of aphorisms by Tim Peters, listed below, that outline good programming practices in Python in a poetic manner.

> The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than right now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea – let's do more of those!

Free Mock Interview

LEARNING PYTHON: BASIC AND ADVANCED CONCEPTS

1. Python Arithmetic Operators

The arithmetic operators in Python include addition (+), subtraction (-), multiplication (*), division (/), modulo (%), and exponentiation (**). These operators work in the same way as similar operators in other programming languages.

Examples:

python
a = 21
b = 10
c = 0

c = a + b
print("Line 1 - Value of c is ", c)

c = a - b
print("Line 2 - Value of c is ", c)

c = a * b
print("Line 3 - Value of c is ", c)

c = a / b
print("Line 4 - Value of c is ", c)

c = a % b
print("Line 5 - Value of c is ", c)

a = 2
b = 3
c = a ** b 
print("Line 6 - Value of c is ", c)

Output:


Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2.1
Line 5 - Value of c is 1
Line 6 - Value of c is 8

PYTHON COMMENTS


# This is a single-line comment in Python

'''
This is a 
multi-line
comment in Python
'''

# This function below takes two numbers as input and returns their sum
def add_numbers(num1, num2):
    result = num1 + num2 # Adding num1 and num2
    return result # Returning the result

Comments are crucial in any programming language as they add clarity and make code easier to understand. In Python, you can add comments using the hash sign (#) for single-line comments and triple quotes (''') for multi-line comments. It is recommended to write descriptive comments that explain what the code is doing rather than just repeating the code in English.

Standard Python Functions

Code:


# Example of a standard Python function
def add_numbers(x, y):
    """
    This function adds two numbers and returns their sum.
    """
    return x + y

# Call the function and print the output
result = add_numbers(3, 5)
print(result)

In the above code, we have an example of a standard Python function that adds two numbers and returns their sum. The function is defined using the `def` keyword followed by the function name and arguments within parentheses. The function body is indented and contains the code for the function.

The `return` statement inside the function specifies the value to be returned when the function is called. Outside the function, we call the function and store the result in a variable `result`, which we then print to the console.

Python Type Casting


# Converting a variable of one data type to another data type is called type casting
# Syntax: newDataType(variable)

# Example 1: Converting int to float
a = 10
b = float(a)
print(b)

# Example 2: Converting float to int
c = 3.14
d = int(c)
print(d)

# Example 3: Converting string to int
e = "100"
f = int(e)
print(f)

# Example 4: Converting string to float
g = "3.14"
h = float(g)
print(h)

Python allows us to easily convert variables from one data type to another using type casting. This can be particularly useful when we need to perform operations on variables of different data types. We can convert variables using the syntax

newDataType(variable)

.

In example 1, we convert an integer to a floating point number using the

float()

function. In example 2, we convert a floating point number to an integer using the

int()

function. In example 3, we convert a string to an integer using the

int()

function. In example 4, we convert a string to a floating point number using the

float()

function.

Program Flow Control in Python

Python provides different methods to control the flow of a program. These methods include conditional statements (if/else/elif), loops (for and while), and function definitions with parameters.


# Example of a for loop that prints numbers from 0 to 4
for i in range(5):
    print(i)
    
# Example of a while loop that prints numbers from 0 to 4
i = 0
while i < 5:
    print(i)
    i += 1
    
# Example of a function that takes two parameters and returns their sum
def add_numbers(a, b):
    return a + b
    
# Example of an if/else statement that checks if a number is even or odd
num = 4
if num % 2 == 0:
    print("Number is even")
else:
    print("Number is odd")


Boolean Operators in Python

In Python, boolean operators are used to evaluate statements and return true or false values. There are three boolean operators in Python:

  • and

    : returns true if both statements are true

  • or

    : returns true if at least one statement is true

  • not

    : returns the opposite of a statement


# Example of boolean operators in Python

x = 5
y = 10

print(x < 10 and y > 5)   # Output: True

print(x < 5 or y < 5)     # Output: False

print(not(x > y))         # Output: True


Conditional Statements in Python


# Example code for conditional statements in Python

number = 10

if number > 0:
    print("Number is positive")
elif number < 0:
    print("Number is negative")
else:
    print("Number is zero")

Conditional statements (if/elif/else) are used to conditionally execute blocks of code based on different conditions. They are an important aspect of programming in Python and are used in various applications.

In the given example, the code checks whether a variable "number" is positive, negative or zero using conditional statements and prints out the corresponding message to the user.

Loop Statements in Python

Code:

Loop statements are used to execute a block of code repeatedly for a certain number of times or until a certain condition is met. In Python, there are two types of loop statements:

1. While loop:<br>
     while condition:<br>
          #code to be executed<br>
     else:<br>
          #code to be executed when while condition is false<br><br>
2. For loop:<br>
     for variable in sequence:<br>
          #code to be executed<br>
     else:<br>
          #code to be executed when for loop completes

Jump Statements in Python

Python allows the use of jump statements, such as "break" and "continue", to control the flow of a loop. "Break" is used to terminate a loop prematurely, while "continue" is used to skip over a part of the loop and continue to the next iteration.

Here is an example of how to use these jump statements in a "for" loop:


# loop through a range of numbers
for i in range(10):
    # if i is equal to 5, break out of the loop
    if i == 5:
        break
    # if i is equal to 2, skip this iteration
    if i == 2:
        continue
    # print out the current value of i
    print(i)

In this example, the loop will print out the numbers 0 through 9, except for 2 and 5. When i is equal to 5, the "break" statement is executed and the loop is terminated prematurely. When i is equal to 2, the "continue" statement is executed and the loop skips over the rest of the block (which would include the print statement) and continues to the next iteration.

Understanding how to properly use jump statements can greatly enhance the control flow and efficiency of your Python code.

Functions in Python


# This is an example of a function in Python
def greet(name):
    """
    This function greets the person passed in as a parameter.
    """
    print("Hello, " + name + ". Good morning!")
    
# Calling the function
greet("John")

In Python, a function is a block of code that runs when it is called. It takes input(s), does some processing, and produces an output. Functions are used to write reusable code, modularize the program, and make code easier to read and understand. The code snippet above defines a function that takes in a parameter 'name' and greets the person with 'Good morning!'. The function is called at the bottom with 'John' as the argument. The output of running the code is "Hello, John. Good morning!".

PYTHON VARIABLE SCOPE RESOLUTION

In Python, the scope of a variable is the region of a program where it is defined and accessible. There are two types of variable scoping in Python – global and local.

Global variables are defined outside of any function and can be accessed throughout the program. Local variables are defined inside a function and can only be accessed within it, i.e., they have a limited scope.

If a local variable has the same name as a global variable, the local variable takes precedence within the function. To access the global variable inside a function, the global keyword can be used.

Here is an example of variable scoping in Python:


global_variable = 10   # global variable

def some_function():
    local_variable = 5  # local variable
    print(local_variable)   # output: 5
    print(global_variable)  # output: 10

some_function()
print(global_variable)  # output: 10

In this example, we have a global variable named "global_variable" that can be accessed anywhere in the program. We also have a function "some_function" that defines a local variable named "local_variable".

When we call the function, it prints the value of the local variable and the global variable. The output is 5 and 10, respectively.

After calling the function, we print the value of the global variable outside of the function. The output is still 10, as expected.

Importing modules in Python

In Python, modules are files containing code that can be used in other Python files. To access the functions or variables defined in a module, you need to import it into your code.

Here is an example of importing the math module and using the sqrt function to find the square root of a number:


import math

x = 4
y = math.sqrt(x)

print(y)

In this example, we import the math module using the "import" keyword. We then use the dot notation to access the sqrt function defined in the math module and store the result in "y". Finally, we print the value of "y" to the console.

You can also import specific functions or variables from a module instead of importing the whole module. Here's an example:


from math import sqrt

x = 4
y = sqrt(x)

print(y)

In this example, we import only the sqrt function from the math module using the "from ... import" syntax. We can now use the "sqrt" function directly without needing to prefix it with "math.".

Importing modules is an essential part of Python programming as it allows you to reuse code and make your code more efficient and modular.

Exception Handling in Python

Code:


try:
    # some code that might cause an exception
except SomeException as e:
    # handle the exception
else:
    # code to be executed if no exception occurred in the try block
finally:
    # code that will be executed no matter what

Explanation:

Exception handling is a critical part of any programming language, and Python is no exception. The above code shows the structure of a typical exception handling block in Python.

The try block contains the code that might cause an exception to be thrown. If an exception occurs, the appropriate exception handler will be executed. In the above example, the SomeException handler is used to handle any exceptions of type SomeException.

If no exception occurs, the code in the else block will be executed. Finally, any code in the finally block will be executed regardless of whether an exception was thrown or not.

Properly handling exceptions is important for writing robust and reliable code. By anticipating potential errors and handling them appropriately, your code will be better equipped to handle unexpected situations and avoid crashes or other undesirable behavior.

PYTHON DICTIONARIES

Dictionaries are a fundamental data structure in Python that store data in key-value pairs. They are similar to a real-life dictionary where a word (the key) corresponds to its definition (the value).

Here's an example of a dictionary in Python:


    my_dict = {"apple": 1, "banana": 2, "orange": 3}

In this dictionary, "apple", "banana", and "orange" are the keys, and 1, 2, and 3 are their corresponding values.

You can access the values in a dictionary by using the keys, like this:


    print(my_dict["apple"])  # Output: 1

You can also add, remove, and modify items in a dictionary using its built-in methods. Overall, dictionaries are a powerful tool that can simplify your code and improve its readability.

Comprehensions in Python

Comprehensions in Python are a concise and elegant way of creating sequences (like lists, dictionaries, and sets) based on existing sequences. They can be used to simplify code and make it more readable.

Here is an example of a list comprehension that creates a list of squared numbers:

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers)

This will output:

[1, 4, 9, 16, 25]

Similarly, we can use dictionary comprehension to create dictionaries:

numbers = [1, 2, 3, 4, 5]
squared_numbers_dict = {num: num ** 2 for num in numbers}
print(squared_numbers_dict)

This will output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

We can also use set comprehension to create sets:

numbers = [1, 2, 3, 4, 5]
squared_numbers_set = {num ** 2 for num in numbers}
print(squared_numbers_set)

This will output:

{1, 4, 9, 16, 25}

Comprehensions can also include conditions:

numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)

This will output:

[2, 4]

Overall, comprehensions are a powerful tool to make your code more concise and efficient.

Guide to String Manipulation in Python

Python

has a lot of built-in functions for handling strings. Strings can be manipulated using various methods such as slicing, concatenation, formatting, and so on. Here's an example code that demonstrates some common string manipulation techniques:

python 
# create a string variable
my_string = "Hello, World!"

# print the string
print(my_string)

# accessing a character in the string using indexing
print(my_string[0])

# slicing the string
print(my_string[0:5])

# concatenating two strings
my_name = "John"
print("My name is " + my_name)

# formatting a string
age = 28
print("I am {} years old".format(age))

# converting the string to uppercase
print(my_string.upper())

# replacing a character in the string
print(my_string.replace("o", "a"))

# splitting the string into words
print(my_string.split(","))

This is just a simple example. There are many other string manipulation techniques in Python. With some practice, you'll be manipulating strings like a pro!

Formatting Dates in Python

Python offers various modules to work with dates and times. The most commonly used module is the datetime module. With this module, we can easily format dates in different styles. Here's an example:


import datetime

# Get current date and time
now = datetime.datetime.now()

# Format the date in the form of day-month-year
formatted_date = now.strftime("%d-%m-%Y")

print("Formatted Date:", formatted_date)

The output of the above code will be:


Formatted Date: 23-08-2021

In the above example, we first imported the datetime module. We then used the now() method to get the current date and time. Finally, we used the strftime() method to format the date in the desired string format.

The %d, %m, and %Y are format codes that correspond to day, month, and year respectively. We can use various other codes to format dates in different ways.

Debugging in Python

Code is written by humans. Therefore, it is natural to have errors in code. Debugging is the process of finding and resolving these errors, also known as bugs, in code. Python provides various tools and techniques to debug code effectively.

Code can be debugged in different ways: using print statements, using a debugger, using logging, and using an Integrated Development Environment (IDE).

Print statements are the simplest way to debug code. Inserting print statements after every few lines or at the points where you think the error may exist can help you identify the exact location and nature of the bug.

Debuggers are specialized tools for helping developers find and fix bugs. Debuggers provide features such as stepping through code line by line, setting breakpoints, examining variables, and modifying code while running the program.

Logging is another way to debug code. Logging involves writing messages to a file or console to track the flow of code execution and identify problems.

IDEs such as PyCharm, Visual Studio Code, and Eclipse provide a suite of debugging tools and features. These tools can be particularly useful for complex projects with many modules and classes.

Python also provides built-in debugging tools such as assert statements, which can help you find code errors quickly.

Debugging is an essential skill for any developer, and mastering it can save time and reduce frustration when developing software.

Logging in Python

Code:

python
import logging

# Configure logging level and file
logging.basicConfig(filename='example.log', level=logging.DEBUG)

# Example variables
num1 = 10
num2 = 5

# Perform division
try:
    result = num1 / num2
except ZeroDivisionError:
    # Log error with traceback
    logging.exception("Attempted to divide by zero")
else:
    # Log result
    logging.info(f"Division result: {result}")

The above code demonstrates how to use the logging module in Python to output information, warnings, errors, and exceptions to a log file. The logging level can be adjusted to control the amount of logging information that is outputted.

Lambda Function in Python

Lambda functions, also known as anonymous functions, are a type of functions in Python that do not have a name and are defined in a single line. They are commonly used for simple and concise operations that do not require a full function definition.

Here is an example of a lambda function that adds two numbers:

add_numbers = lambda x, y: x + y

This lambda function takes two arguments, x and y, and returns their sum. It can be called using the following syntax:

result = add_numbers(10, 20)

The result will be 30.

Lambda functions can also be used with built-in functions such as filter() and map(). Here is an example of a lambda function used with filter() to filter out even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

The resulting even_numbers list will contain [2, 4, 6, 8, 10].

Overall, lambda functions provide a convenient and efficient way to perform simple operations without the need for a full function definition.

Ternary Operator in Python


variable = value_if_true if condition else value_if_false 

The ternary operator in Python is a shorthand way of writing an if-else statement in a single line. The syntax of the ternary operator is similar to that of the if-else statement with the difference being that it includes only a single expression for each condition.

For example, consider the following code:


x = 5
y = 10
result = "x is greater than y" if x > y else "y is greater than x"
print(result)

This code assigns the string "y is greater than x" to the variable "result" because the condition "x > y" is false. If the condition were true, the string "x is greater than y" would be assigned to the variable.

Using the ternary operator can make your code more concise and easier to read. However, it is important to use it judiciously as it can lead to less readable code if overused or nested too deeply.

Understanding *args and **kwargs in Python

When working with Python, you might come across the terms *args and **kwargs. These are special syntaxes used in function definitions that allow you to pass a variable number of arguments to a function. The asterisk (*) before args and double asterisks (**) before kwargs indicate that the arguments are optional and can take any number of arguments.

def my_function(*args, **kwargs): # *args is used to pass a variable number of non-keyworded arguments for arg in args: print(arg)

# **kwargs is used to pass a variable number of keyworded arguments for key, value in kwargs.items(): print("{} == {}".format(key, value))

In the above example, the function my_function takes any number of non-keyworded arguments (*args) and any number of keyworded arguments (**kwargs). We can call this function with any number of arguments as shown below:

my_function('a', 'b', 'c', name='John', age=25, country='US')

The output of the function will be:

a b c name == John age == 25 country == US

Using *args and **kwargs can simplify your code and make it more flexible, allowing you to pass any number of arguments to a function without having to specify them all in advance.

Understanding the "__name__ == "__main__" in Python

__name__

is a special built-in variable in Python that represents the name of the current module. When a Python script/module is run, the Python interpreter automatically sets the

__name__

variable to

"__main__"

if the script/module is being run as the main program.

This is useful when you want to write a script that can be used as both an executable script and an imported module. You can put the code that is only meant to be executed when the script is run as the main program under the

if __name__ == "__main__"

statement. This way, the code under this statement will only be executed when the file is being run as the main program.

Here is an example:


def my_function():
    print("My function was called!")

if __name__ == "__main__":
    print("This is the main program.")
    my_function()

In this example, the

my_function

will only be called if the script is being executed as the main program. If the script is being imported as a module, the

my_function

will not be called.

Python Dataclasses

Python's Dataclasses module simplifies the process of defining classes with attributes. It provides decorators and functions to automatically generate special methods like __init__(), __repr__(), __eq__() and others based on the class attributes defined.


  from dataclasses import dataclass
  
  
  @dataclass
  class MyClass:
      name: str
      age: int
      profession: str
      
      
  obj = MyClass("John", 25, "Software Engineer")
  print(obj.name)
  print(obj.age)
  print(obj.profession)

In the example above, we create a class called MyClass and use the @dataclass decorator to define its attributes. Then, we create an object of this class and can access its attributes using dot notation. It's that simple!

Python Virtual Environment

Code:

The following code sets up a Python virtual environment:


  python3 -m venv myenv

This will create a new virtual environment with the name "myenv" in your current directory. To activate the virtual environment and begin using it, run the following command:


  source myenv/bin/activate

You should see the name of your virtual environment appear in your command prompt. Now you can install any necessary packages without worrying about conflicts with the system-level Python installation. To exit the virtual environment, simply run:


  deactivate

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.