{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Flow control - Exercises" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2.1.\n", "\n", "Write code which can give information about the century a given year is in. Given the year 1767, for instance, the application must be able to print the following sentence: “The year 1767 is in the eighteenth century”. Limit your algorithm to years in between 1500 and 2010. \n", "Note that it is possible to combine two different Boolean expressions using the word ‘and’.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "year = 1767\n", "\n", "print(\"the year \" + str(year) + \" is in: \" )\n", "\n", "if year >= 1500 and year < 1600:\n", " print(\"The sixteenth century\")\n", "elif year >= 1600 and year < 1700:\n", "\tprint(\"The seventeenth century\")\n", "elif year >= 1700 and year < 1800:\n", "\tprint(\"The eighteenth century\")\n", "elif year >= 1800 and year < 1900:\n", "\tprint(\"The nineteenth century\")\n", "else:\n", "\tprint(\"The twentienth century\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2.2.\n", "\n", "Create a variable and assign it an arbitrary integer (i.e. a rational number). Next, write some code which can print the multiplication table for this number." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "number = 7\n", "\n", "for i in range( 1, 11):\n", " print( \"{} times {} is {}.\".format( i , number , i*number ) )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 2.3.\n", "\n", "Using the keyword ‘for’ and the range() function, write code which generate the drawing below. N.B. The longest line in the pattern consists of seven stars.\n", "\n", "```\n", "*\n", "**\n", "***\n", "**** \n", "***** \n", "****** \n", "******* \n", "******\n", "*****\n", "****\n", "***\n", "**\n", "*\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "max = 7\n", "\n", "\n", "for i in range( 1, max*2):\n", " if i <= (max):\n", " print( i * '*' )\n", " else:\n", " print( (max*2-i) * '*' )" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.7.2" } }, "nbformat": 4, "nbformat_minor": 2 }