I am learning from and typed code exactly as instructed but it won't work will someone please help

Joined
Jul 25, 2024
Messages
18
Reaction score
1
squareNum = eval(input("Enter a number: "))
print ("The square of " + squareNum + " is " + squareNum**2 + "." + sep=" ")
 
Joined
Jul 25, 2024
Messages
18
Reaction score
1
I solved it I was wrong version of python
tip always know what python version your using and always know what version your learning
 
Joined
Jul 4, 2023
Messages
510
Reaction score
63
IMHO, the issue is not with the Python version but with the incorrect used command syntax.

squareNum = eval(input("Enter a number: "))
Do not use eval in that way!

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()

1722293806055.png
 
Last edited:
Joined
Jul 25, 2024
Messages
18
Reaction score
1
IMHO, the issue is not with the Python version but with the incorrect used command syntax.


Do not use eval in that way!

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
i can't not use eval it specifically said i have to use eval it my code works in the version i was learning
 
Joined
Jul 4, 2023
Messages
510
Reaction score
63
squareNum = eval(input("Enter a number: "))
print ("The square of " + squareNum + " is " + squareNum**2 + "." + sep=" ")
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.

Additionally, there is a syntax error in the print function call because the sep parameter is used incorrectly.

A better approach would be to use the int function to convert the input to an integer and correct the print function call. Here is the revised version of the code
Python:
# 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, ".")

Using eval can be safe if we limit the context in which eval operates to prevent the execution of malicious code. This can be done by defining a restricted dictionary containing only the functions and variables that are needed.
Python:
'''
 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)
 

Ask a Question

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.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,056
Messages
2,570,441
Members
47,125
Latest member
MDBT

Latest Threads

Top