{ "cells": [ { "cell_type": "markdown", "metadata": { "nbgrader": { "grade": false, "grade_id": "cell-9873288c26d190e4", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "# Sending data to Python \n", "\n", "```{admonition} Interactive page\n", ":class: warning, dropdown\n", "This is an interactive book page. Press the launch button at the top right side.\n", "```\n", "\n", "So far we have seen examples of **output**, i.e., Python telling us things like in the \"Hello world\" example. \n", "We have also seen examples of **code**, i.e., us giving instructions to Python in order for it to do things. \n", "\n", "In addition, we can also **send data to Python**. Often in science, we do this by having Python read data files (more on this in a [later chapter](../chapter9/data-files.ipynb)), but we can also send information to Python using `input()`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-output" ] }, "outputs": [], "source": [ "a = input()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can specify text for the label of the input box to clarify what kind of input you expect from the user:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "remove-output" ] }, "outputs": [], "source": [ "a = input(\"Enter a number:\")" ] }, { "cell_type": "markdown", "metadata": { "nbgrader": { "grade": false, "grade_id": "cell-84fd218d798174b7", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "Even if we type a number into the input box, it will **always return a variable of type string** `str`. If we want to subsequently use our input as a number, we have to **explicitly convert** it to a number (remember: which property of Python causes this?). For example, we can use the `float()` function:\n", "\n", "```\n", "a = input()\n", "a = float(a)\n", "print(\"The value of a is:\", a)\n", "print(\"a has the type:\", type(a))\n", "```\n", "\n", "Because `input` is buggy in the current version of the Jupyter book, try out this code in your local installation of VS Code.\n", "\n", "```{exercise}\n", ":class: dropdown\n", "Use the `input` function to get parameters of integer, float, and string types into the program. Do this in VS Code.\n", "```" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md" }, "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.11.4" } }, "nbformat": 4, "nbformat_minor": 4 }