Flexiple Logo
  1. Home
  2. Blogs
  3. Python
  4. Python Commands List with Example

Python Commands List with Example

Author image

Mayank Jain

Software Developer

Published onĀ Thu Jan 04 2024

Python Commands List with Examples provides a comprehensive overview of various Python commands accompanied by practical examples. These commands cover fundamental operations such as data manipulation, file handling, and control structures, essential for effective Python programming. Each command is illustrated with an example, demonstrating its application in real-world scenarios.

Python's simplicity and readability are evident in this list of Python commands, making them accessible to both beginners and experienced programmers. The examples ensure that users understand the context and functionality of each command. Employ these commands to enhance coding efficiency and problem-solving skills in Python.

Basic Python Commands List

Here's a list of basic Python commands with examples.

1. pip install command:

The pip command is a package manager for Python, written in Python itself. It is used to install and manage software packages. Use the pip install command to install any software package from the Python Package Index (PyPI), which is an online repository of public packages.

To install a package, open your Windows PowerShell or terminal and use the following syntax:

pip install package-name

Example:

Install the popular requests library using pip install requests.

2. print command:

The print command is used to display a message or an object on the screen or other standard output devices. You can use it to print various types of objects, including strings, integers, lists, tuples, and more.

Syntax:

print(object)

Example:

Print a simple message like "Hello, World!" or print the value of a variable.

print("Hello, World!")

3. type command:

The type command is used to determine the type or class of an object in Python. It helps you check the data type of a variable, which is crucial when working with dynamic typing in Python.

Syntax:

type(object)

Example:

Determine the data type of a variable, e.g., type(x) where x is a variable.

x = 2
print(type(x))

4. range command:

The range command is used to generate a sequence of integers. It is commonly used in for loops to iterate a specific number of times. The range function can take three arguments: start, stop, and step. The start is optional and defaults to 0, stop is mandatory and defines where the sequence stops (exclusive), and step is optional and defaults to 1.

Syntax:

range(start, stop, step)

Example:

Generate a sequence of numbers from 0 to 9 using range(10).

print(list(range(10)))

5. round command:

The round command is used to round a floating-point number to a specified precision in decimal digits. It allows you to control the number of digits after the decimal point. The number argument is the floating-point number you want to round, and digits (optional) specifies the count of digits after the decimal point (default is 0).

Syntax:

round(number, digits)

Example:

Round the number 3.14159 to two decimal places using round(3.14159, 2).

print(round(3.14159, 2))

6. input command:

The input command is used to receive input from the user. It stops the program's execution until the user provides input. By default, the input is treated as a string. If you need to take an integer input, you must explicitly convert it.

Syntax:

input(message)

Example:

Prompt the user to enter their name and store it in a variable, e.g., name = input("Enter your name: ").

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

7. len command:

The len command or len() function is used to find the length of an object. It returns the number of items in an object. For strings, it returns the number of characters, and for lists or tuples, it returns the number of elements.

Syntax:

len(object)

Example:

Determine the length of a string, list, or tuple, e.g., len(my_list) where my_list is a list.

8. if-else command:

The if-else command is used to implement conditional logic in Python. It allows you to execute different blocks of code based on whether a condition is true or false. If the condition is true, the code inside the if block is executed; otherwise, the code inside the else block is executed.

Syntax:

if condition:
    # Code to execute if the condition is True
else:
    # Code to execute if the condition is False

Example:

Check if a number is even or odd and print the result using an if-else statement.

n = 2
if n % 2 == 0:
    print("Given value is even")
else:
    print("Given value is odd")

9. elif command:

The elif (short for "else if") command extends conditional logic by allowing you to check multiple conditions sequentially. It is used after an if statement to test additional conditions if the initial condition is false. You can have multiple elif blocks.

Syntax:

if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if neither condition1 nor condition2 is True

Example:

Implement a grading system using if-elif-else to assign grades based on a student's score.

score = int(input("Enter the student's score: "))
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"The student's grade is: {grade}")

10. Lists and Indexing:

Lists are one of the most versatile data structures in Python. They are ordered collections of items, and you can access individual items by their index. Indexing starts from 0 for the first element, 1 for the second, and so on.

Example:

Create a list of numbers and access specific elements by their index, e.g., my_list[0] to get the first element.

my_list = [0, 1, 2, 3]
print(my_list[0])

11. String Manipulation:

Python provides various string manipulation operations like concatenation, slicing, and formatting. You can join strings together, extract substrings, and format text according to your needs.

Example:

Concatenate two strings using the + operator, e.g., "Hello, " + "World!".

12. Dictionary:

Dictionaries are data structures that store key-value pairs. Each key is associated with a value, and you can access values by their keys. Dictionaries are useful for mapping between related data.

Example:

Create a dictionary to store information about a person, e.g., person = {"name": "John", "age": 30}.

13. Functions with Parameters:

Functions in Python allow you to define reusable blocks of code. You can pass parameters to functions, and they can return values. This enables you to write modular and organized code.

Example:

Define a function that adds two numbers and returns the result, e.g., def add(x, y): return x + y.

14. Boolean Operators (and, or, not):

Boolean operators allow you to combine conditions. and returns True if both conditions are true, or returns True if at least one condition is true, and not negates a condition.

Example:

Use boolean operators to check multiple conditions in an if statement, e.g., if condition1 and condition2:

15. Comments:

Comments are used to add explanatory notes within your code. They are not executed and are meant for documentation and readability. Python supports single-line comments with # and multi-line comments with triple quotes (''' or """).

Example:

Add comments to describe the purpose of code blocks and functions, e.g., # This is a comment.

Intermediate Python Commands List

Intermediate Python commands enable more sophisticated programming by introducing concepts like list comprehensions, functions, and exception handling. Each command serves a specific purpose and enhances the capability of Python programming.

String Commands

Strings in Python are fundamental data types, and there are several useful commands to manipulate them:

16. isalnum:

This method checks whether all characters in a string are alphanumeric (letters and numbers) and returns a Boolean value (True or False).

Syntax: stringname.isalnum()

Example:

text = "Python123"
result = text.isalnum()
print(result)  # Returns True

In this example, the isalnum() method verifies that all characters in the string "Python123" are alphanumeric, hence it returns True.

17. capitalize:

The capitalize() function transforms the first character of a string to uppercase if it's currently in lowercase.

Syntax: stringname.capitalize()

Example:

sentence = "hello world"
result = sentence.capitalize()
print(result)  # Returns "Hello world"

Here, the capitalize() method capitalizes the first letter of the string "hello world," resulting in "Hello world."

18. find:

The find() command is used to search for a substring within a string. It returns the index of the first occurrence of the substring if it's present, or -1 if it's not found.

Syntax: string.find(substring)

Example:

sentence = "Python is powerful"
index = sentence.find("is")
print(index)  # Returns 7

In this case, the find() method locates the substring "is" within the sentence "Python is powerful" and returns the index where it starts (7 in this case).

19. count:

The count() function is used to count the occurrences of a substring in a string.

Syntax: stringname.count(substring, start, end)

Example:

text = "Python is easy, Python is fun"
count = text.count("Python")
print(count)  # Returns 2

The count() method counts how many times the substring "Python" appears in the given text.

20. center:

The center() command aligns a string in the center of a given length, using a specified character as the fill character.

Syntax: string.center(length, character)

Example:

word = "Python"
centered_word = word.center(10, "-")
print(centered_word)  # Returns "--Python--"

In this example, the center() method centers the word "Python" within a total length of 10 characters, filling the extra spaces with hyphens ("-").

22. upper:

The upper() method converts all characters in a string to uppercase.

Syntax: stringname.upper()

Example:

text = "python is great"
upper_text = text.upper()
print(upper_text)  # Returns "PYTHON IS GREAT"

The upper() method transforms all characters in the string to uppercase.

23. strip:

The strip() function removes leading and trailing whitespace (including newline characters) from a string.

Syntax: stringname.strip()

Example:

sentence = "   Hello, World!   \n"
stripped_sentence = sentence.strip()
print(stripped_sentence)  # Returns "Hello, World!"

In this example, strip() eliminates the extra whitespace and newline characters.

These string commands provide powerful tools for manipulating and analyzing text data in Python.

List Commands

Lists are versatile data structures in Python, and they come with various commands for manipulation:

24. append:

The append() command adds an element to the end of a list.

Syntax: list.append(element)

Example:

numbers = [1, 2, 3]
numbers.append(4)
print(numbers)  # Now numbers is [1, 2, 3, 4]

Here, the append() method adds the number 4 to the end of the numbers list.

25. copy:

The copy() method creates a new copy of a list object.

Syntax: list.copy()

Example:

original_list = [1, 2, 3]
copied_list = original_list.copy()
print(copied_list)  # Returns [1, 2, 3]

The copy() function generates a separate copy of the original_list, ensuring that changes to one list do not affect the other.

26. insert:

The insert() command is used to add an element at a specified position within a list.

Syntax: listname.insert(position, element)

Example:

numbers = [1, 2, 4]
numbers.insert(2, 3)
print(numbers)  # Now numbers is [1, 2, 3, 4]

In this example, the insert() method adds the number 3 to the numbers list at position 2.

27. pop:

The pop() method removes an element from a specified position within the list and returns it.

Syntax: listname.pop(position)

Example:

fruits = ["apple", "banana", "cherry"]
removed_fruit = fruits.pop(1)
print(removed_fruit)  # Returns "banana" and fruits becomes ["apple", "cherry"]

Here, the pop() method removes the element at position 1 ("banana") from the fruits list and returns it.

28. reverse:

The reverse() method reverses the order of elements in a list in-place.

Syntax: list.reverse()

Example:

numbers = [1, 2, 3]
numbers.reverse()
print(numbers)  # Now numbers is [3, 2, 1]

The reverse() method modifies the original list to reverse its elements.

29. sort:

The sort() method is used to sort the elements of a list in ascending order (by default).

Syntax: list.sort()

Example:

numbers = [3, 1, 2]
numbers.sort()
print(numbers)  # Now numbers is [1, 2, 3]

The sort() method arranges the elements of numbers in ascending order.

Tuple Commands

Tuples are ordered and immutable data structures in Python, and they offer a couple of essential methods:

30. count:

The count() method counts the occurrences of an element in a tuple.

Syntax: tuple.count(element)

Example:

my_tuple = (1, 2, 2, 3, 4)
count = my_tuple.count(2)
print(count)  # Returns 2

In this case, the count() method calculates how many times the element 2 appears in the tuple.

31. index:

The index() method finds the index of the first occurrence of an element in a tuple. If the element is not found, it raises a ValueError.

Syntax: tuple.index(element)

Example:

my_tuple = (10, 20, 30, 40)
index = my_tuple.index(30)
print(index)  # Returns 2

The index() method locates the element 30 at index 2 in the my_tuple tuple.

These commands provide developers with powerful tools for working with strings, lists, and tuples in Python, making it easier to manipulate and analyze data.

Advanced Python Commands List

In advanced Python programming, several commands and features enable more efficient and powerful coding. These features are often utilized to write cleaner, more concise, and more readable code.

Here is a list of Advanced Python Commands given below.

32. List Comprehension:

List comprehensions provide a more readable and efficient way to create lists compared to traditional loops. They are generally used for transforming one list into another by applying an expression to each item in the original list.

Syntax: [expression for item in iterable if condition]

Example:

[x**2 for x in range(10)]  # creates a list of squares for the numbers 0 through 9.

33. Lambda Functions

Lambda functions are small, anonymous functions defined by the keyword lambda. They can take any number of arguments, but can only have one expression. They are useful for short operations that are impractical to define in a standard function.

Syntax: lambda arguments: expression

Example:

f = lambda x, y: x + y
print(f(1, 2))  # returns 3

34. Map Function

The map() applies a given function to each item of an iterable (like a list) and returns a list of the results.

Syntax: map(function, iterable)

Example:

print(list(map(lambda x: x * 2, [1, 2, 3, 4])))  # returns [2, 4, 6, 8]

35. Filter Function

The filter() constructs an iterator from elements of an iterable for which a function returns true.

Syntax: filter(function, iterable)

Example:

print(list(filter(lambda x: x > 2, [1, 2, 3, 4])))  # returns [3, 4]

36. Generators

Generators are a simple way to create iterators using functions. They yield items instead of returning a list to save memory.

Syntax: (expression for item in iterable)

Example:

print((x*x for x in range(3)))  # yields 0, 1, 4

37. Decorators

Decorators allow you to modify the behavior of a function or class. They are higher-order functions that take a function as an argument and return a new function.

Syntax: @decorator_function

Example:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

38. Set Comprehensions

Set Comprehensions are similar to list comprehensions, but for creating sets, which are collections of unique elements.

Syntax: {expression for item in iterable}

Example:

d = {x for x in 'hello world' if x not in 'aeiou'}  # creates a set of consonants in the phrase 'hello world'

39. Dictionary Comprehensions

Dictionary Comprehension allows the creation of dictionaries using an expressive syntax. They consist of key-value pairs and are similar to list comprehensions but for dictionaries.

Syntax: {key: value for item in iterable}

Example:

d = {x: x**2 for x in range(5)}  # creates a dictionary where keys are numbers 0-4 and values are their squares

40. zip() Function

zip() makes an iterator that aggregates elements from multiple iterables (like lists, tuples).

Syntax: zip(*iterables)

Example:

print(list(zip([1, 2, 3], ['a', 'b', 'c'])))  # returns [(1, 'a'), (2, 'b'), (3, 'c')]

41. enumerate

The enumerate() command adds a counter to an iterable and returns it as an enumerate object.

Syntax: enumerate(iterable, start=0)

Example:

print(list(enumerate(['apple', 'banana', 'grape'])))  # returns [(0, 'apple'), (1, 'banana'), (2, 'grape')]

42. Global and Nonlocal Keywords

global and nonlocal keywords allow you to work with variables outside the current scope, in the global and enclosing scopes, respectively.

Syntax: global variable / nonlocal variable

Example:

x = "global"
def foo():
    global x
    x = x * 2
foo()
print(x)  # prints "globalglobal"

43. Slicing

Slicing is used to extract a subset of a sequence (like strings, lists, tuples).

Syntax: sequence[start:stop:step]

Example:

print('Hello World'[1:5])  # returns 'ello'

44. try, except, finally Blocks

These are used for handling and managing exceptions or errors in a graceful manner.

Syntax:

try:
    # code to try to execute
except SomeError:
    # code to execute if there is SomeError
finally:
    # code to execute regardless of errors

Example:

try:
    print(1 / 0)
except ZeroDivisionError:
    print("You can't divide by zero!")
finally:
    print("This is executed last.")

45. with Statement

The with statement is used for resource management, like file reading/writing, ensuring that resources are properly acquired and released.

Syntax: with expression as variable:

Example:

with open('file.txt', 'r') as file:
    contents = file.read()

46. List Slicing with Step

This slicing method allows you to specify a step with which to extract elements from a list.

Syntax: list[start:stop:step]

Example:

print([1, 2, 3, 4, 5][::2])  # results in [1, 3, 5]

These advanced commands illustrate the versatility and power of Python as a programming language, capable of handling a wide range of programming tasks with concise and efficient code.

FAQs on Python Commands

How to use Python commands?

Using Python commands involves executing specific instructions in a Python interpreter or script. These commands allow interaction with data, control the flow of the program, and perform various computational tasks. For example, the print command outputs text or variables to the console. Use the import command to include external modules, enhancing Python's functionality.

Begin with basic commands like print("Hello, World!") to display text. Utilize arithmetic commands like a = 5 + 3 to perform calculations and store results in variables. Employ conditional statements such as if a == 8: print("Correct!") to execute code based on conditions. This approach forms the foundation for developing more complex Python applications.

What are some common Python commands?

Some common Python commands include print(), which displays the output of the given expression. The import statement allows the inclusion of modules in the script. def defines a new function. Use for to create a loop over a sequence. The if statement enables conditional execution of a block of code.

Variables are assigned using =, and arithmetic operations use operators like +, -, *, and /. The len() function returns the length of an object. input() reads a line from the input, converted into a string. Execute break to exit a loop before its normal termination. Use continue to skip the rest of the loop's body and immediately retest its condition.

What is the python3 command?

The python3 command initiates the Python interpreter in its version 3.x. This command is essential for running Python scripts that are compatible with Python version 3. The python3 command executes Python code, processes Python scripts, and launches the interactive Python shell. This command differentiates between Python 2.x and Python 3.x environments, ensuring the correct version is used for execution.

The system runs the Python 3 interpreter when a user types python3 in a terminal or command prompt. This allows for running scripts, modules, or packages specifically designed for Python 3. Entering python3 followed by a script name executes that script using Python 3, ensuring compatibility with Python 3 syntax and libraries.

Related Blogs

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.