{ "cells": [ { "cell_type": "markdown", "id": "6838b2de", "metadata": {}, "source": [ "# Hello" ] }, { "cell_type": "code", "execution_count": null, "id": "4200d243", "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", " Example of use of eval() function reading floats and complex.\n", " Thsi evaluated the string typed \n", " \n", " For float try\n", " 4*(3 -17) will give -56.0\n", " 1.3 + math.cos(math.radians(45)) = 2.007\n", " \n", " For complex try\n", " \n", " 3*(4 + 4j) will give (12+15j)\n", " cmath.exp(complex(0,math.pi)) will give -1 (with a bit of rounding error)\n", " \n", " In Python 2 this was the default operation of input() but this was changed\n", " in Python 3, so if you want this now you have to call it explicitely as shown\n", " in the code.\n", "\n", "\"\"\"\n", "\n", "import math\n", "import cmath\n", "\n", "def main():\n", " \n", " \n", " s = input(\"Give a float expression : \") # Read in a string\n", " x = float(eval(s)) # evaluate and return a float\n", " # Print out the result\n", " print(\"Expression typed : \" + str(s) + \" and value : \" + str(x))\n", " \n", " s = input(\"Give a complex expression : \") # Read in a string\n", " z = complex(eval(s)) # evaluate and return a complex\n", " # Print out the result\n", " print(\"Expression typed : \" + str(s) + \" and value : \" + str(z))\n", "\n", "\n", " \n", "# Execute the program\n", "main()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }