Python Trick: Build a Calculator in just one line! #python #coding

preview_player
Показать описание
Discover the secrets of python that enhances your coding efficiency and makes your logic clearer. Watch now and elevate your Python coding game! 💻🔍 #Python #Coding

Рекомендации по теме
Комментарии
Автор

While using eval() for a one-line calculator is concise, it's important to consider security risks that may arise, such as allowing the execution of arbitrary code. Therefore, it's advisable to exercise caution, especially with untrusted input. For example, you can implement input validation to only allow mathematical expressions:

try:
user_input = input("Enter a mathematical expression: ")
if any(char.isalpha() for char in user_input):
raise ValueError("Error: Input must be a valid mathematical expression.")

result = eval(user_input)
print(result)
except Exception as error:
print(f"Error: {error}")

LearningBot
Автор

There's no need to put input() inside an f-string, as the results are already a string.

ezsnova
Автор

This is extremely unsafe, as the user can also input python code, which will be evaluated. To prevent this you can add checks beforehand to the input to make sure that it is an integer or float only, if not then throw an error.

Here's the fixed code:
try:
calc = int(input(""))
eval(calc)
except Exception as error:
print(error)

This code will prevent the input of python code, if python code is inserted by the user, it will just give the error: invalid literal for int() with base 10: 'Insert_code_here'

SapphireKR
Автор

guess what happens when user input is:
import os; os.system('rm -rf /')

gagakagaga
welcome to shbcf.ru