Example
Python
name = "Rahul"
age = 21
print("My name is", name, "& I am", age, "years old.")

You can also try this code with Online Python Compiler
Run Code
Output:
My name is Rahul & I am 21 years old.
The print command provides a convenient way to display information & inspect variable values during the development process.
type command
The type command is used to determine the data type of an object in Python. It returns the type of the specified object, which can be helpful for debugging, type checking, & understanding the nature of variables in your code.
The syntax for the type command is straightforward:
type(object)
Example :
x = 42
y = 3.14
z = "Hello, world!"
a = [1, 2, 3]
b = (4, 5, 6)
c = {7, 8, 9}
d = {"name": "Rinki", "age": 20}
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'str'>
print(type(a)) # Output: <class 'list'>
print(type(b)) # Output: <class 'tuple'>
print(type(c)) # Output: <class 'set'>
print(type(d)) # Output: <class 'dict'>
In this example, we define various objects of different data types & use the type command to display their respective types. The type command returns the class of the object, indicating whether it is an integer, float, string, list, tuple, set, or dictionary.
range command
The range command in Python is used to generate a sequence of numbers. It returns an iterable range object that can be used in loops or converted to other iterable objects like lists or tuples. The syntax for the range command is :
range(start, stop, step)
Let’s see the parameters :
-
start (optional): The starting number of the sequence. Default is 0.
-
stop: The number at which the sequence stops (exclusive).
- step (optional): The difference between each number in the sequence. Default is 1.
Example :
# Generate numbers from 0 to 4
for i in range(5):
print(i) # Output: 0 1 2 3 4
# Generate numbers from 2 to 8 with a step of 2
for i in range(2, 10, 2):
print(i) # Output: 2 4 6 8
# Convert range to a list
numbers = list(range(1, 6))
print(numbers) # Output: [1, 2, 3, 4, 5]
In the first example, range(5) generates a sequence of numbers from 0 to 4. The second example demonstrates how to specify the start, stop, & step parameters to generate a customized sequence. The third example shows how to convert a range object to a list using the list() function.
The range command is commonly used in loops to iterate over a specific sequence of numbers, making it a powerful tool for controlling the flow of your Python program.
round command
The round command in Python is used to round a number to a specified number of decimal places. It takes a number as input and returns the nearest integer or floating-point number with the desired precision.
The syntax for the round command is as follows:
round(number, ndigits)
Here's a breakdown of the parameters:
-
number: The number to be rounded.
- ndigits (optional): The number of decimal places to round to. Default is 0, which rounds to the nearest integer.
Example :
# Round a number to the nearest integer
x = 3.14159
rounded_x = round(x)
print(rounded_x) # Output: 3
# Round a number to 2 decimal places
y = 2.71828
rounded_y = round(y, 2)
print(rounded_y) # Output: 2.72
# Round a number to the nearest ten
z = 1234.5
rounded_z = round(z, -1)
print(rounded_z) # Output: 1230.0
In the first example, round(x) rounds the number 3.14159 to the nearest integer, which is 3.
The second example demonstrates how to round a number to a specific number of decimal places by specifying the ndigits parameter. In this case, 2.71828 is rounded to 2 decimal places, resulting in 2.72. The third example shows how to round a number to the nearest ten by using a negative value for ndigits.
The round command is useful when you need to format numbers for display or perform calculations that require a specific level of precision.
input command
The input command in Python is used to accept user input from the console. It allows your program to interact with the user by prompting them to enter data, which can then be stored in a variable for further processing.
The syntax for the input command is as follows:
variable = input("Prompt message")
Let’s see how it works :
-
"Prompt message": The message that is displayed to the user, prompting them to enter input. This is an optional parameter.
-
variable: The variable that stores the user's input as a string.
Example :
Python
# Prompt the user for their name
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Prompt the user for a number and perform a calculation
num = int(input("Enter a number: "))
result = num * 2
print("Double of", num, "is", result)

You can also try this code with Online Python Compiler
Run Code
Output:
Enter your name: Riya
Hello, Riya!
Enter a number: 6
Double of 6 is 12
In the first example, the input command prompts the user to enter their name with the message "Enter your name: ". The user's input is stored in the name variable, which is then used to print a personalized greeting.
In the second example, the input command prompts the user to enter a number. Since the input command always returns a string, we use the int() function to convert the user's input to an integer. The number is then stored in the num variable, & a calculation is performed to double its value. Finally, the result is printed.
The input command is essential for creating interactive programs that require user input, such as calculators, form fillers, or command-line interfaces.
len command
The len command in Python is used to determine the length or size of an object. It returns the number of elements in a sequence (such as a string, list, tuple, or dictionary) or the number of characters in a string.
The syntax for the len command is straightforward:
len(object)
Let’s look at a few examples :
# Length of a string
string = "Hello, world!"
print(len(string)) # Output: 13
# Length of a list
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
# Length of a tuple
my_tuple = (1, 2, 3)
print(len(my_tuple)) # Output: 3
# Length of a dictionary
my_dict = {"name": "Harsh", "age": 25, "city": "New York"}
print(len(my_dict)) # Output: 3
In the first example, len(string) returns the number of characters in the string "Hello, world!", which is 13.
The second example shows how to use len to determine the number of elements in a list. len(my_list) returns 5, which is the number of elements in the list [1, 2, 3, 4, 5].
Similarly, in the third example, len(my_tuple) returns the number of elements in the tuple (1, 2, 3), which is 3.
In the fourth example, len(my_dict) returns the number of key-value pairs in the dictionary {"name": "Harsh", "age": 25, "city": "New York"}, which is 3.
The len command is widely used in Python for various purposes, such as iterating over sequences, checking the size of data structures, or validating input lengths.
Loop commands
Python provides several loop commands that allow you to repeatedly execute a block of code based on certain conditions. The two primary loop commands in Python are for and while.
for loop
The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. It executes a block of code for each item in the sequence.
The syntax for the for loop is as follows:
for item in sequence:
# Code block to be executed
Example :
Python
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

You can also try this code with Online Python Compiler
Run Code
Output:
apple
banana
cherry
while loop
The while loop repeatedly executes a block of code as long as a given condition is true. It continues iterating until the condition becomes false. The syntax for the while loop is as follows:
while condition:
# Code block to be executed
Example
Python
# Print numbers from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1

You can also try this code with Online Python Compiler
Run Code
Output:
1
2
3
4
5
In addition to these basic loop commands, Python provides break and continue statements to modify the loop behavior:
Break
Immediately terminates the loop and exits to the next statement after the loop.
continue: Skips the rest of the current iteration and moves to the next iteration of the loop.
Example :
Python
# Break the loop when a specific condition is met
for i in range(1, 6):
if i == 4:
break
print(i)

You can also try this code with Online Python Compiler
Run Code
Output:
1
2
3
These loop commands provide powerful tools for automating repetitive tasks, processing sequences of data, and controlling the flow of your Python programs.
String Commands
Python provides a rich set of string commands that allow you to manipulate and work with strings efficiently.
Here are some commonly used string commands:
capitalize()
The capitalize() command returns a copy of the string with the first character capitalized and the rest lowercased.
Example:
Python
text = "hello, world!"
capitalized_text = text.capitalize()
print(capitalized_text)

You can also try this code with Online Python Compiler
Run Code
Output:
"Hello, world!"
find()
The find() command searches for a specified substring within a string and returns the index of the first occurrence. If the substring is not found, it returns -1.
Example:
Python
text = "Hello, world!"
index = text.find("world")
print(index)

You can also try this code with Online Python Compiler
Run Code
Output:
7
center()
The center() command returns a centered string padded with a specified character. It takes the desired width and an optional fill character as arguments.
Example:
Python
text = "Python"
centered_text = text.center(10, "*")
print(centered_text)

You can also try this code with Online Python Compiler
Run Code
Output:
"**Python**"
These are just a few examples of the string commands available in Python. Some other useful string commands include:
-
lower() and upper(): Convert the string to lowercase or uppercase.
-
replace(): Replace occurrences of a substring with another substring.
-
split(): Split the string into a list based on a specified delimiter.
-
join(): Join the elements of an iterable (such as a list) into a string.
-
strip(), lstrip(), rstrip(): Remove leading and/or trailing whitespace or specified characters.
String commands are essential for text processing, data cleaning, and formatting output in Python. They provide a convenient way to manipulate and transform strings according to your program's requirements.
List Commands
Python offers several built-in commands to manipulate and work with lists efficiently. Here are some commonly used list commands:
copy()
The copy() command creates a shallow copy of a list. It returns a new list object with the same elements as the original list.
Example:
Python
original_list = [1, 2, 3]
new_list = original_list.copy()
print(new_list)

You can also try this code with Online Python Compiler
Run Code
Output:
[1, 2, 3]
insert()
The insert() command inserts an element at a specified position in a list.
Example:
Python
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)

You can also try this code with Online Python Compiler
Run Code
Output:
[1, 4, 2, 3]
pop()
The pop() command removes and returns the element at a specified index in a list. If no index is provided, it removes and returns the last element.
Example:
Python
my_list = [1, 2, 3]
popped_element = my_list.pop(1)
print(popped_element) # Output: 2
print(my_list)

You can also try this code with Online Python Compiler
Run Code
Output:
[1, 3]
reverse()
The reverse() command reverses the order of elements in a list.
Example:
Python
my_list = [1, 2, 3]
my_list.reverse()
print(my_list)

You can also try this code with Online Python Compiler
Run Code
Output:
[3, 2, 1]
sort()
The sort() command sorts the elements of a list in ascending order. It modifies the original list.
Example:
Python
my_list = [3, 1, 2]
my_list.sort()
print(my_list)

You can also try this code with Online Python Compiler
Run Code
Output:
[1, 2, 3]
These are just a few examples of the list commands available in Python. Some other useful list commands include:
-
append(): Add an element to the end of a list.
-
extend(): Extend a list by appending elements from another iterable.
-
count(): Return the number of occurrences of a specified element in a list.
-
index(): Return the index of the first occurrence of a specified element in a list.
-
remove(): Remove the first occurrence of a specified element from a list.
List commands provide powerful tools for managing and manipulating collections of elements in Python. They allow you to add, remove, modify, and rearrange elements within a list efficiently.
Tuple Commands
Python provides a few built-in commands specifically for tuples. Since tuples are immutable, the available commands are limited compared to lists. Here are the commonly used tuple commands:
index()
The index() command returns the index of the first occurrence of a specified element in a tuple. If the element is not found, it raises a ValueError.
Example:
Python
my_tuple = (1, 2, 3, 2, 4)
index = my_tuple.index(2)
print(index)

You can also try this code with Online Python Compiler
Run Code
Output:
1
In this example, index() returns the index of the first occurrence of the element 2 in the tuple, which is 1.
Apart from index(), tuples support the following built-in functions:
-
len(): Returns the number of elements in a tuple.
-
max(): Returns the maximum element in a tuple.
-
min(): Returns the minimum element in a tuple.
-
sum(): Returns the sum of all elements in a tuple (numeric values only).
-
sorted(): Returns a new sorted list from the elements of a tuple.
- tuple(): Creates a new tuple object from an iterable.
Example:
my_tuple = (5, 2, 8, 1, 9)
print(len(my_tuple)) # Output: 5
print(max(my_tuple)) # Output: 9
print(min(my_tuple)) # Output: 1
print(sum(my_tuple)) # Output: 25
print(sorted(my_tuple)) # Output: [1, 2, 5, 8, 9]
new_tuple = tuple([1, 2, 3])
print(new_tuple) # Output: (1, 2, 3)
Since tuples are immutable, you cannot modify them once they are created. However, you can perform operations like concatenation and repetition to create new tuples based on existing ones.
Example:
Python
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple)
repeated_tuple = tuple1 * 3
print(repeated_tuple)

You can also try this code with Online Python Compiler
Run Code
Output:
(1, 2, 3, 4, 5, 6)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
Tuples are commonly used when you need to store a collection of related values that should not be modified. They are faster than lists and can be used as keys in dictionaries or elements in sets.
Set Commands
Python provides a variety of built-in commands to work with sets efficiently. Sets are unordered collections of unique elements. Here are some commonly used set commands:
add()
The add() command adds a single element to a set. If the element already exists in the set, it does not add a duplicate.
Example:
Python
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)

You can also try this code with Online Python Compiler
Run Code
Output:
{1, 2, 3, 4}
update()
The update() command adds multiple elements from an iterable (such as a list, tuple, or another set) to a set.
Example:
Python
my_set = {1, 2, 3}
my_set.update([4, 5, 6])
print(my_set)

You can also try this code with Online Python Compiler
Run Code
Output:
{1, 2, 3, 4, 5, 6}
remove() and discard()
The remove() command removes a specified element from a set. If the element does not exist, it raises a KeyError. On the other hand, discard() also removes a specified element but does not raise an error if the element does not exist.
Example:
Python
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)
my_set.discard(4) # No error raised
print(my_set)

You can also try this code with Online Python Compiler
Run Code
Output:
{1, 3}
{1, 3}
pop()
The pop() command removes and returns an arbitrary element from a set. Since sets are unordered, there is no guarantee which element will be removed. If the set is empty, it raises a KeyError.
Example:
Python
my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element) # Output: 1 (or any other element)
print(my_set)

You can also try this code with Online Python Compiler
Run Code
Output:
{2, 3}
clear()
The clear() command removes all elements from a set, making it an empty set.
Example:
Python
my_set = {1, 2, 3}
my_set.clear()
print(my_set)

You can also try this code with Online Python Compiler
Run Code
Output:
set()
Set operations
Python provides several commands for performing set operations, such as:
-
union() or |: Returns a new set with elements from both sets.
-
intersection() or &: Returns a new set with elements common to both sets.
-
difference() or -: Returns a new set with elements that are in the first set but not in the second set.
-
symmetric_difference() or ^: Returns a new set with elements that are in either set but not in both.
-
issubset() or <=: Checks if a set is a subset of another set.
- issuperset() or >=: Checks if a set is a superset of another set.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
print(set1.issubset(set2)) # Output: False
print(set1.issuperset(set2)) # Output: False
These are some of the commonly used set commands in Python. Sets are useful when you need to store unique elements and perform operations like membership testing, removing duplicates, or calculating set operations efficiently.
Dictionary Commands
Python provides a variety of built-in commands to work with dictionaries efficiently. Dictionaries are unordered collections of key-value pairs, where each key is unique.
Here are some commonly used dictionary commands:
get()
The get() command retrieves the value associated with a specified key from a dictionary. If the key does not exist, it returns a default value (which is None by default).
Example:
Python
my_dict = {"name": "Ravi", "age": 25}
value = my_dict.get("name")
print(value)
value = my_dict.get("city", "Unknown")
print(value)

You can also try this code with Online Python Compiler
Run Code
Output:
"Ravi"
"Unknown"
items()
The items() command returns a view object that contains key-value pairs of the dictionary as tuples.
Example:
Python
my_dict = {"name": "Mehak", "age": 30, "city": "New York"}
items = my_dict.items()
print(items)

You can also try this code with Online Python Compiler
Run Code
Output:
dict_items([('name', 'Mehak'), ('age', 30), ('city', 'New York')])
keys():
The keys() command returns a view object that contains all the keys of the dictionary.
Example:
Python
my_dict = {"name": "Sinki", "age": 28, "city": "London"}
keys = my_dict.keys()
print(keys)

You can also try this code with Online Python Compiler
Run Code
Output:
dict_keys(['name', 'age', 'city'])
values():
The values() command returns a view object that contains all the values of the dictionary.
Example:
Python
my_dict = {"name": "Rahul", "age": 32, "city": "Paris"}
values = my_dict.values()
print(values)

You can also try this code with Online Python Compiler
Run Code
Output:
dict_values(['Rahul', 32, 'Paris'])
pop()
The pop() command removes and returns the value associated with a specified key from the dictionary. If the key does not exist, it raises a KeyError unless a default value is provided.
Example:
Python
my_dict = {"name": "Sanjana", "age": 27}
value = my_dict.pop("age")
print(value)
print(my_dict)
value = my_dict.pop("city", "Unknown")
print(value)

You can also try this code with Online Python Compiler
Run Code
Output:
27
{'name': 'Sanjana'}
"Unknown"
popitem()
The popitem() command removes and returns an arbitrary key-value pair from the dictionary as a tuple. In Python 3.7 and later versions, it removes the last inserted pair.
Example:
Python
my_dict = {"name": "Harsh", "age": 29, "city": "Tokyo"}
item = my_dict.popitem()
print(item)
print(my_dict)

You can also try this code with Online Python Compiler
Run Code
Output:
('city', 'Tokyo')
{'name': 'Harsh', 'age': 29}
setdefault()
The setdefault() command retrieves the value associated with a specified key from the dictionary. If the key does not exist, it inserts the key with a default value (which is None by default) and returns the default value.
Example:
Python
my_dict = {"name": "Rinki", "age": 24}
value = my_dict.setdefault("city", "Unknown")
print(value) # Output: "Unknown"
print(my_dict)

You can also try this code with Online Python Compiler
Run Code
Output:
"Unknown"
{'name': 'Rinki', 'age': 24, 'city': 'Unknown'}
These are some of the commonly used dictionary commands in Python. Dictionaries are useful when you need to store and retrieve values based on unique keys, making them efficient for lookup operations.
Frequently Asked Questions
What is the purpose of the pip install command?
It installs Python packages from the Python Package Index (PyPI), allowing you to add external libraries to your environment.
How do I display multiple items using the print command?
You can separate items with commas in the print() function, & Python will output them sequentially, separated by spaces by default.
Can the print command output to places other than the console?
Yes, you can direct the output of the print command to files or other I/O streams by using the file parameter.
Conclusion
In this article, we have discussed a wide range of Python commands that are essential for efficient programming. We covered the pip install command for installing packages, the print command for displaying output, the type command for determining data types, the range command for generating sequences of numbers, the round command for rounding numbers, the input command for accepting user input, the len command for finding the length of objects, loop commands for repetitive execution, and various commands for working with strings, lists, tuples, sets, and dictionaries.
You can refer to our guided paths on Code 360. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.