all python commands list and what they do with code examples
A s a language, Python is known for its simplistic yet powerful nature. The language boasts an extensive library of pre-defined tools and functions, making it a preferred language for developers of all experience levels. In this article, we will cover the most commonly used Python commands, along with their functionality and code examples.
- Print
The print command in Python is used to display output values from a program on the console.
Code Example:
- Input
The input command is used to take user input as a string value during the runtime of a program.
Code Example:
name = input("What is your name? ") print("Hello,", name)
- If Else
The If Else command is used to create decision-making structures in a program. It evaluates a certain condition and executes specific code based on the result of that condition.
Code Example:
num = 10 if num > 0: print("num is positive") else: print("num is negative")
- For Loop
The for loop is used to iterate through a sequence of elements (lists, tuples, etc.) in a program.
Code Example:
- While Loop
The while loop is used to execute a piece of code repeatedly while a specific condition is true.
Code Example:
x = 0 while x 5: print(x) x += 1
- List Comprehensions
List comprehensions are a concise and powerful way to create lists in Python.
Code Example:
nums = [x for x in range(10) if x % 2 == 0] print(nums)
- Functions
Functions are used to define reusable, modular chunks of code that perform specific actions.
Code Example:
def square(num): return num * num print(square(5))
- Dictionaries
Dictionaries are key-value pairs that allow you to store and retrieve data efficiently.
Code Example:
- Classes and Objects
Classes and objects are core concepts in Object-Oriented Programming (OOP), which is supported in Python.
Code Example:
class Circle: def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius * self.radius c = Circle(5) print(c.area())
- File Operations
File operations are used to read and write data to and from external files.
Code Example:
myfile = open("example.txt", "w") myfile.write("Hello, World!") myfile.close() myfile = open("example.txt", "r") print(myfile.read()) myfile.close()
- Exceptions
Exceptions are used to handle runtime errors in a program and gracefully exit or take corrective action.
Code Example:
try: num = int(input("Enter a number: ")) result = 10 / num print(result) except ZeroDivisionError: print("Error: division by zero") except ValueError: print("Error: invalid input")
- Modules and Packages
Python supports modularity by allowing developers to import external packages and modules of code.
Code Example:
import math print(math.sqrt(25))
In conclusion, Python offers a wide range of commands and functions that can make programming easier and more efficient. This list covers only some of the most commonly used commands in Python. As a developer, it is essential to understand and learn as many of these commands and their functionality as possible to enhance your programming skills.
The «print» command in Python is used for displaying output values from a program on the console. A simple code example can be:
This command can be used for printing any value that can be converted to a string. For instance:
will output «20» and «3.14» respectively.
To separate arguments with a different value, you can use the «sep» argument. For example:
print("The answer is", 10, sep="***")
will output «The answer is***10». By default, the «sep» argument is set to space character.
The «input» command is used to take user input as a string value during the runtime of a program. The input function can display a message to the user asking them for input. For example:
name = input("What is your name? ") print("Hello,", name)
This code will ask the user their name and then greet them. You can take an integer input by using the «int» function. For example:
age = int(input("What is your age? "))
If a user inputs a non-integer value, Python will raise a «ValueError» exception. You can take a float input by using the «float» function.
The If Else command is used to create decision-making structures in a program. It evaluates a certain condition and executes specific code based on the result of that condition. A simple example is:
num = 10 if num > 0: print("num is positive") else: print("num is negative")
Here, Python checks if the value of «num» is positive or negative and prints an appropriate message accordingly.
You can also use «elif» blocks to test multiple conditions. For instance:
num = 10 if num 0: print("num is negative") elif num > 0: print("num is positive") else: print("num is zero")
Here, Python first checks if the value of «num» is negative, then it checks if it is positive, and finally, it checks if it is zero.
The for loop is used to iterate through a sequence of elements (lists, tuples, etc.) in a program. A simple example is:
In this example, the loop will print the values of the list [1, 2, 3, 4], one at a time.
You can also use the «range» function to generate a sequence of numbers to loop through. For example:
This code will print the numbers 0 to 4.
The while loop is used to execute a piece of code repeatedly while a specific condition is true. A simple example is:
x = 0 while x 5: print(x) x += 1
In this example, the loop will print the values of «x» (0, 1, 2, 3, 4) as long as the value of «x» is less than 5.
You can use «break» and «continue» statements to modify the behavior of a while loop. A «break» statement is used to exit the loop altogether while a «continue» statement is used to skip the current iteration of the loop and move to the next one.
List comprehensions are a concise and powerful way to create lists in Python. They consist of a single line of code which can generate a list based on a condition. For example:
nums = [x for x in range(10) if x % 2 == 0]
In this example, Python generates a list of even numbers between 0 and 10 (exclusive).
List comprehensions can be used with various data types such as strings, tuples, sets, etc.
Functions are used to define reusable, modular chunks of code that perform specific actions. They are defined using the «def» keyword in Python. For example:
def square(num): return num * num print(square(5))
Here, the «square» function takes a single argument, «num», and returns its square.
Functions can also take multiple arguments and can return multiple values using tuples.
Dictionaries are key-value pairs that allow you to store and retrieve data efficiently. A simple example is:
In this example, the value associated with the key «age» in the «info» dictionary is printed.
Dictionaries can be used to represent any type of data, such as employee data, customer data, etc.
Classes and objects are core concepts in Object-Oriented Programming (OOP), which is supported in Python. A «class» is a blueprint for creating objects while an «object» is an instance of a class. For example:
class Circle: def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius * self.radius c = Circle(5) print(c.area())
In this example, the «Circle» class has a single instance variable, «radius», and a single method, «area». The «area» method calculates the area of the circle while the «init» method is used to initialize the instance variable «radius». The «c» object is an instance of the «Circle» class that is initialized with a radius of 5. The «c.area()» method is then called to calculate the area of the circle.
Classes and objects are used extensively in Python to represent real-world objects and concepts.
File operations are used to read and write data to and from external files. The «open» function is used to open a file while the «read» function is used to read the contents of a file. For example:
myfile = open("example.txt", "r") print(myfile.read()) myfile.close()
In this example, the «example.txt» file is opened and its contents are printed to the console.
You can also use the «write» function to write data to a file and the «append» mode to add data to an existing file. It is important to close the file using the «close» function when you are done working with it.
Exceptions are used to handle runtime errors in a program and gracefully exit or take corrective action. The «try» block is used to isolate code that may raise an exception while the «except» block is used to catch specific exceptions and provide appropriate error messages. For example:
try: num = int(input("Enter a number: ")) result = 10 / num print(result) except ZeroDivisionError: print("Error: division by zero") except ValueError: print("Error: invalid input")
In this example, the user is asked to enter a number, and then the program calculates the result of 10 divided by that number. If the user enters 0, a «ZeroDivisionError» is raised, and an appropriate error message is printed to the console. If the user enters an invalid input (such as a string), a «ValueError» is raised and an appropriate error message is printed.
Python supports modularity by allowing developers to import external packages and modules of code. A «module» is a file containing Python definitions and statements, while a «package» is a collection of modules. For example:
import math print(math.sqrt(25))
In this example, Python imports the «math» module, which contains various mathematical functions. The «sqrt» function is then called to calculate the square root of 25 and print the result.
In conclusion, Python offers an extensive library of commands and functions that can make programming easier and more efficient. Understanding these commands and their functionality is essential for any Python developer.
Popular questions
- What is the «print» command used for in Python, and how can it be used in a program with a code example?
Answer: The «print» command in Python is used for displaying output values from a program on the console. Here’s an example code:
This code will print «Hello, World!» on the console.
Answer: The «input» command is used to take user input as a string value during the runtime of a program. The input function can display a message to the user asking them for input. Here’s an example code:
name = input("What is your name? ") print("Hello,", name)
This code will take user input as a string and print it on the console.
Answer: Functions are used to define reusable, modular chunks of code that perform specific actions. They are defined using the «def» keyword in Python. Here’s an example code:
def square(num): return num * num print(square(5))
This code will define a function called «square» that takes a single argument «num» and returns its square. Then, calling «square(5)» will print 25 on the console.
Answer: List comprehensions are a concise and powerful way to create lists in Python. They consist of a single line of code which can generate a list based on a condition. Here’s an example code:
nums = [x for x in range(10) if x % 2 == 0]
This code will generate a list of even numbers between 0 and 10 (exclusive).
Answer: Exceptions are used to handle runtime errors in a program and gracefully exit or take corrective action. The «try» block is used to isolate code that may raise an exception while the «except» block is used to catch specific exceptions and provide appropriate error messages. Here’s an example code:
try: num = int(input("Enter a number: ")) result = 10 / num print(result) except ZeroDivisionError: print("Error: division by zero") except ValueError: print("Error: invalid input")
This code will try to calculate the result of 10 divided by the user input and handle any errors that may occur, such as a «ZeroDivisionError» or a «ValueError».
Tag
Ahmed Galal
As a senior DevOps Engineer, I possess extensive experience in cloud-native technologies. With my knowledge of the latest DevOps tools and technologies, I can assist your organization in growing and thriving. I am passionate about learning about modern technologies on a daily basis. My area of expertise includes, but is not limited to, Linux, Solaris, and Windows Servers, as well as Docker, K8s (AKS), Jenkins, Azure DevOps, AWS, Azure, Git, GitHub, Terraform, Ansible, Prometheus, Grafana, and Bash.