Do not use eval in that way!squareNum = eval(input("Enter a number: "))
while True:
try:
# Prompt the user to enter a number and convert the input to an integer
squareNumber = int(input("Please enter a number: "))
# Calculate the square of the number and display the result
print("The square of " + str(squareNumber) + " is " + str(squareNumber**2) + ".", sep=" ")
# or
# print(f"The square of {squareNumber} is {squareNumber**2}.")
# Exit the loop if the input was successfully converted and processed
break
except ValueError:
# Inform the user that the input was not a valid number and prompt to try again
print("That's not a valid number. Please try again.")
# Wait for the user to press ENTER before exiting
input("Press ENTER to Exit")
import os
import re
def clearConsole():
# Clear the console screen based on the operating system
os.system('cls' if os.name in ('nt', 'dos') else 'clear')
def comma2Dot(value):
# Replace commas with dots in the value
return value.replace(",", ".")
def removeSpaces(value):
# Remove all spaces from the value
return re.sub(r"\s", "", value)
def insertValueFor(expression, variable, value):
# Replace variable placeholders in the expression with actual values
return expression.replace(variable, value)
# List of allowed characters in the expression
allowedCharacters = [
' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'+', '-', '*', '/', '(', ')', '.', ',', 'p', 'i', 'x', 'r'
]
while True:
# Prompt the user to input an expression
expression = input("Enter expression: ")
# Remove spaces and convert to lowercase
expression = removeSpaces(expression.lower())
if expression == "":
continue
# Replace commas with dots
expression = comma2Dot(expression)
# Check if all characters in the expression are allowed
if all(character in allowedCharacters for character in expression):
# Replace variables in the expression with user-provided values
if "x" in expression:
x = float(comma2Dot(input("Enter value for x: ")))
expression = insertValueFor(expression, "x", str(x))
if "r" in expression:
r = float(comma2Dot(input("Enter value for r: ")))
expression = insertValueFor(expression, "r", str(r))
if "pi" in expression:
expression = insertValueFor(expression, "pi", "3.14")
try:
# Evaluate and print the result of the expression
print("\n" + expression)
print(round(eval(expression), 2))
except ZeroDivisionError:
# Handle division by zero errors
print("Error: Division by zero")
except:
# Handle other errors
print("Invalid expression")
else:
# Handle special commands
if expression in ["s", "stop"]:
exit()
elif expression in ["c", "cls"]:
clearConsole()
continue
else:
# Inform the user about disallowed characters
print("The expression contains disallowed characters")
print()
i can't not use eval it specifically said i have to use eval it my code works in the version i was learningIMHO, the issue is not with the Python version but with the incorrect used command syntax.
Do not use eval in that way!
- Learn Python the Hard Way: Avoiding the eval()
- Safe and Secure Eval() in Python: How to Minimize Security Risks
Check out this:
Python:while True: try: # Prompt the user to enter a number and convert the input to an integer squareNumber = int(input("Please enter a number: ")) # Calculate the square of the number and display the result print("The square of " + str(squareNumber) + " is " + str(squareNumber**2) + ".", sep=" ") # or # print(f"The square of {squareNumber} is {squareNumber**2}.") # Exit the loop if the input was successfully converted and processed break except ValueError: # Inform the user that the input was not a valid number and prompt to try again print("That's not a valid number. Please try again.") # Wait for the user to press ENTER before exiting input("Press ENTER to Exit")
[ working code on-line ]
Python:import os import re def clearConsole(): # Clear the console screen based on the operating system os.system('cls' if os.name in ('nt', 'dos') else 'clear') def comma2Dot(value): # Replace commas with dots in the value return value.replace(",", ".") def removeSpaces(value): # Remove all spaces from the value return re.sub(r"\s", "", value) def insertValueFor(expression, variable, value): # Replace variable placeholders in the expression with actual values return expression.replace(variable, value) # List of allowed characters in the expression allowedCharacters = [ ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/', '(', ')', '.', ',', 'p', 'i', 'x', 'r' ] while True: # Prompt the user to input an expression expression = input("Enter expression: ") # Remove spaces and convert to lowercase expression = removeSpaces(expression.lower()) if expression == "": continue # Replace commas with dots expression = comma2Dot(expression) # Check if all characters in the expression are allowed if all(character in allowedCharacters for character in expression): # Replace variables in the expression with user-provided values if "x" in expression: x = float(comma2Dot(input("Enter value for x: "))) expression = insertValueFor(expression, "x", str(x)) if "r" in expression: r = float(comma2Dot(input("Enter value for r: "))) expression = insertValueFor(expression, "r", str(r)) if "pi" in expression: expression = insertValueFor(expression, "pi", "3.14") try: # Evaluate and print the result of the expression print("\n" + expression) print(round(eval(expression), 2)) except ZeroDivisionError: # Handle division by zero errors print("Error: Division by zero") except: # Handle other errors print("Invalid expression") else: # Handle special commands if expression in ["s", "stop"]: exit() elif expression in ["c", "cls"]: clearConsole() continue else: # Inform the user about disallowed characters print("The expression contains disallowed characters") print()
View attachment 2858
Using eval in this manner is not consistent with good programming practices due to potential security risks. eval executes the code passed to it as a string, which can be dangerous if the user inputs malicious code.squareNum = eval(input("Enter a number: "))
print ("The square of " + squareNum + " is " + squareNum**2 + "." + sep=" ")
# Get a number from the user
number = int(input("Enter a number: "))
# Calculate the square of the number
squareNum = number ** 2
# Display the result
print("The square of", number, "is", squareNum, ".")
'''
In this example, the user can input an expression like abs(-5) + round(3.6),
and eval will safely evaluate it within a restricted context that
only allows the use of the abs and round functions.
Passing {"__builtins__": None} to eval removes access to Python's
built-in functions, which further secures the code.
'''
# Define a restricted dictionary with allowed functions and variables
allowed_names = {
'abs': abs,
'round': round
}
# Get an expression from the user
user_input = input("Enter an expression to evaluate (e.g., 'abs(-5) + round(3.6)'): ")
# Use eval with the restricted dictionary
result = eval(user_input, {"__builtins__": None}, allowed_names)
# Display the result
print("The result of the expression is:", result)
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.