{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python \n", "\n", "**Instructions:**\n", "- You will be using Python 3.\n", "- Do not modify; write your code in the specified section.\n", "\n", "**After this assignment you will:**\n", "- Be able to use the Python Keywords.\n", "\n", "Let's get started!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Value Keywords: True, False, None " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T10:03:58.048891Z", "start_time": "2020-08-02T10:03:58.042868Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "3\n", "1\n", "False\n" ] } ], "source": [ "print(False == 0)\n", "print(True == 1)\n", " \n", "print(True + True + True)\n", "print(True + False + False)\n", "\n", "print (None == 0) " ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T08:00:18.447086Z", "start_time": "2020-08-02T08:00:18.439073Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "x = None\n", "y = None\n", "print(x == y)" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2020-07-30T16:15:15.958585Z", "start_time": "2020-07-30T16:15:15.953679Z" } }, "source": [ "## Operator Keywords: and, or, not, in, is" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T08:00:34.075458Z", "start_time": "2020-08-02T08:00:34.070255Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "False\n" ] } ], "source": [ "a = True\n", "b = False\n", " \n", "print(a and b) \n", " \n", "print(a or b) \n", " \n", "print(not a) " ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n" ] } ], "source": [ "my_list = ['a', 'b', 'c', 'd']\n", "\n", "print('a' in my_list)\n", "print('z' not in my_list)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "var1 = 1234\n", "var2 = 1234\n", "\n", "# id(var1) == id(var2)\n", "print(var1 is var2)\n", "print(var1 is not var2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control Flow Keywords: if, elif, else" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q: Write an interactive program that takes values of length and breadth of a 2-dimensional shape from user and check if it is square or a rectangle." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:24:07.793163Z", "start_time": "2020-08-02T11:24:07.787937Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter length :10\n", "Enter breadth :12\n", "Rectangle\n" ] } ], "source": [ "length = int(input('Enter length :'))\n", "breadth = int(input('Enter breadth :'))\n", "\n", "### START CODE HERE ### \n", "if length == breadth:\n", " print(\"Square\")\n", "else: \n", " print(\"Rectangle\")" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2020-07-30T16:15:15.958585Z", "start_time": "2020-07-30T16:15:15.953679Z" } }, "source": [ "### Q : Write an interactive program that takes two int values from user and print greatest among them.\n", "\n", "**Hint**: Use intput() function once. Use map() to convert each value to integer." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:24:22.376200Z", "start_time": "2020-08-02T11:24:22.366888Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "enter two nums :10 20\n", "20\n" ] } ], "source": [ "### START CODE HERE ### \n", "num1, num2 = map(int, input(\"enter two nums :\").split())\n", "\n", "if num1 > num2:\n", " print(num1)\n", "elif num1 < num2:\n", " print(num2)\n", "else:\n", " print(\"Both are equal\")" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2020-07-30T16:15:15.958585Z", "start_time": "2020-07-30T16:15:15.953679Z" } }, "source": [ "### Q : A company decided to give bonus to employees if his/her based on their years of service such that if the employee has served for alteast 1 year then he/she will get a bonus of 5%, if for more than a year and less than 5 years then he/she will get a bonus of 10%, and if 5 years or above then he/she will get 20% bonus. \n", "\n", "### Write an interactive program that asks user for his/her salary and year of service and print the net bonus amount.\n", "\n", "\n", "**Hint**: Remember employees with years of service less than 1 year are excluded from the program. " ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:24:28.608273Z", "start_time": "2020-08-02T11:24:28.605258Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your salary :10000\n", "Years served :10\n", "Net bonus 2000.0\n" ] } ], "source": [ "### START CODE HERE ### \n", "\n", "salary = float(input(\"Enter your current salary :\"))\n", "yrs_served = float(input(\"Enter your years of service :\"))\n", "\n", "if yrs_served == 1:\n", " bonus = 0.05 * salary\n", "elif yrs_served > 1 and yrs_served < 5:\n", " bonus = 0.1 * salary\n", "elif yrs_served > 5:\n", " bonus = 0.2 * salary\n", "else:\n", " bonus = 0\n", " \n", "print(f\"Net bonus = {bonus}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Iteration Keywords: for, while, break, continue, else" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Given a list iterate it and display numbers which are divisible by 2 or 5 and if you find number greater than 150 stop the loop iteration.\n" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:24:39.901586Z", "start_time": "2020-08-02T11:24:39.891841Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "120\n", "15\n", "32\n", "40\n", "55\n", "75\n", "120\n", "150\n" ] } ], "source": [ "num_list1 = [120, 15, 32, 40, 55, 75, 120, 13, 150, 180, 20]\n", "### START CODE HERE ### \n", "\n", "for num in num_list1:\n", " if num > 150:\n", " break \n", " if num % 2 == 0 or num % 5 == 0:\n", " print(num)\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "itr = iter(num_list1)\n", "itr" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mitr\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m: " ] } ], "source": [ "next(itr)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Print the following pattern using for loop.\n", "\n", " 5 4 3 2 1 \n", "\n", " 4 3 2 1 \n", "\n", " 3 2 1 \n", "\n", " 2 1 \n", "\n", " 1\n", "\n", "**Hint**: Use negative steps in range(). For example try: `list(range(5, 0, -1))`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:24:44.604471Z", "start_time": "2020-08-02T11:24:44.596279Z" }, "scrolled": true }, "outputs": [], "source": [ "### START CODE HERE ### \n", "\n", "for i in range(5, 0, -1):\n", " for j in range(i, 0, -1):\n", " print(j, end = \" \")\n", " print(\"\\n\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Given a list iterate it and display numbers which are divisible by either 2 or 5 and if you find number greater than 150 stop the loop iteration. If any number is divisible by both 2 and 5, skip it." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:24:47.234968Z", "start_time": "2020-08-02T11:24:47.225620Z" } }, "outputs": [], "source": [ "num_list2 = [120, 15, 32, 40, 55, 75, 120, 132, 150, 180, 200]\n", "### START CODE HERE ### \n", "\n", "for num in num_list2:\n", " if num > 150:\n", " break\n", " if num % 10 == 0:\n", " continue\n", " if num % 2==0 or num % 5 == 0:\n", " print(num)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Write an interactive program that takes a number from user to calculate factorial of that number.\n", "\n", "**Hint**: Use conditional statements and while loop." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "### START CODE HERE ### \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Write an interactive program that takes integer inputs from user until he/she presses q ( Ask to press q to quit after every integer input ). Print average all numbers." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "### START CODE HERE ### \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Structure Keywords: def, class, with, as, pass, lambda" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Create a function that counts the number of elements that are greater than 50 in a list.\n", "\n", "**Hint**: Sort the list and use a for loop to iterate over the elements of the list.\n", "\n", "**Sample input1**: `[16, 55, 80, 3]`\n", "\n", "**Sample output1**: `2`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T12:46:45.768235Z", "start_time": "2020-08-02T12:46:45.762964Z" } }, "outputs": [], "source": [ "num_list = [120, 15, 32, 40, 55, 85, 120, 13, 150, 180, 20]\n", "\n", "### START CODE HERE ### \n", "\n", "def greater_than_50(l):\n", " count = 0\n", " for num in num_list:\n", " if num > 50:\n", " count = count +1\n", " return count\n", "\n", "greater_than_50(num_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Write a function that takes two integer parameters and returns a list of numbers between the two intergers that are exactly divisible by 5 and 7. If any of the inputs are nnegative then the function should return nothing.\n", "\n", "**Hint**: Use min() and max() functions to identify the minimum and maximum of the two arguments respectively. If any of the arguments are negative then pass.\n", "\n", "**Sample input1**: `get_nums(20, 40)`\n", "\n", "**Sample output1**: `[35]`\n", "\n", "**Sample input2**: `get_nums(80, 30)`\n", "\n", "**Sample output2**: `[35, 70]`" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:53:18.400788Z", "start_time": "2020-08-02T11:53:18.395534Z" } }, "source": [ "#### Additional Hints: \n", "To keep on adding elements to a list we need to use `append()`. For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T11:56:04.488526Z", "start_time": "2020-08-02T11:56:04.471007Z" } }, "outputs": [], "source": [ "nums = []\n", "nums.append(1)\n", "print(nums)\n", "\n", "nums.append(2)\n", "print(nums)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "### START CODE HERE ### \n", "\n", "def get_nums(num1, num2):\n", " if num1<0 or num2<0:\n", " return None\n", " start, end = min(num1, num2), max(num1, num2)\n", " #start, end = sorted([num1, num2]) # \n", " num_l =[]\n", " for num in range(start+1, end):\n", " if num % 35 == 0:\n", " print(num)\n", " num_l.append(num)\n", " return num_l\n", "\n", "get_nums(80, 30)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Create a function that takes an integer `n` as argument and return the `n-th` Fibonacci term. If `n` is negative then the function should return nothing.\n", "\n", "**Hint**:A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....\n", "The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms, i.e.\n", "\n", " nth term = (n-1)th +(n-2)th term\n", "\n", "**Sample input1**: `fibonacci(5)`\n", "\n", "**Sample output1**: `3`\n", "\n", "**Sample input2**: `fibonacci(10)`\n", "\n", "**Sample output2**: `34`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T12:25:11.061675Z", "start_time": "2020-08-02T12:25:11.054209Z" } }, "outputs": [], "source": [ "### START CODE HERE ### \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Write a Python program to create a lambda function that adds 15 to a given number provided by the user passed in as an argument." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T12:25:12.560703Z", "start_time": "2020-08-02T12:25:12.553277Z" } }, "outputs": [], "source": [ "### START CODE HERE ### \n", "\n", "add15 = lambda x : x + 15\n", "\n", "n = int(input(\"Enter your number : \"))\n", "\n", "add15(n)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Q : Write a Python program to sort a list of tuples containing students names and marks using Lambda first by their marks and then by their name any have scored same marks.\n", "\n", "**Sample input**: `[('Zaheer', 88), ('Bikas', 90), ('Zebwa', 82), ('Charlie', 97), ('Andrew', 82)]`\n", "\n", "**Sample output**: `[('Andrew', 82), ('Zebwa', 82), ('Zaheer', 88), ('Bikas', 90), ('Charlie', 97)]`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T13:05:15.184498Z", "start_time": "2020-08-02T13:05:15.170776Z" } }, "outputs": [], "source": [ "subject_marks = [('Zaheer', 88), ('Bikas', 90), ('Zebwa', 82), ('Charlie', 97), ('Andrew', 82)]\n", "### START CODE HERE ### \n", "\n", "subject_marks.sort(key = lambda x: (-x[1], x[0]))\n", "subject_marks" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exception-Handling Keywords: try, except, raise, finally, else, assert" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2020-07-30T16:15:15.958585Z", "start_time": "2020-07-30T16:15:15.953679Z" } }, "source": [ "### Q : Write a interactive program that takes an input from the user and tries to convert it to integer otherwise prints the exception.\n", "\n", "**Sample input1**: `abcde`\n", "\n", "**Sample output1**: `invalid literal for int() with base 10: 'abcde'`\n", "\n", "**Sample input2**: `23123`\n", "\n", "**Sample output2**: `23123`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "### START CODE HERE ### \n", "\n", "n = input(\"Enter a number :\")\n", "\n", "try:\n", " print(int(n))\n", "except Exception as e:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2020-07-30T16:15:15.958585Z", "start_time": "2020-07-30T16:15:15.953679Z" } }, "source": [ "### Q : Write a function that takes a numeric arguments provided by user and return True if the number is positive, else False. To make your function robust include an exception handling blocks so that your program does not fail if a string is passed.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T13:27:52.875634Z", "start_time": "2020-08-02T13:27:52.872142Z" } }, "outputs": [], "source": [ "### START CODE HERE ### \n", "\n", "val = input(\"Enter a number :\")\n", "\n", "def positive_num(n):\n", " try:\n", " if float(n) > 0:\n", " return True\n", " return False\n", " except ValueError:\n", " return None\n", " \n", "positive_num(val)\n" ] }, { "cell_type": "markdown", "metadata": { "ExecuteTime": { "end_time": "2020-08-02T13:52:18.845387Z", "start_time": "2020-08-02T13:52:18.836541Z" } }, "source": [ "### Q : Write an interactive program that takes marks obtained by a student in different subjects as input for enrollment. Your program should allow enrolling only those students whose average marks is greater than 60%. If average marks if greater than 90% then the student will be place in Group A, if between 75% and 90% then Group B, else Group C. Use assertion to reject the students with average marks below 60% and print the message `Rejected!`. Full marks in each subject is 100. \n", "\n", "\n", "**Hint:** Use the sum() and len() functions to get the average marks.\n", "\n", "**Sample input1**: `24 44 22 66 17`\n", "\n", "**Sample output1:** `AssertionError: Rejected`\n", "\n", "**Sample input1**: `74 84 67 56 87`\n", "\n", "**Sample output1:** `Group C`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "ExecuteTime": { "end_time": "2020-08-02T14:19:28.537165Z", "start_time": "2020-08-02T14:19:28.531108Z" } }, "outputs": [], "source": [ "### START CODE HERE ### \n", "\n", "marks = list(map(float, input(\"Enter you marks : \").split()))\n", "\n", "avg_marks = sum(marks)/(len(marks)*100)\n", "\n", "# try:\n", "assert avg_marks >= 0.6, \"Rejected\"\n", "if avg_marks >= 0.9:\n", " print(\"Your average marks is\", avg_marks)\n", " print(\"Placed in Group A.\")\n", "elif avg_marks >= 0.75:\n", " print(\"Your average marks is\", avg_marks)\n", " print(\"Placed in Group B.\")\n", "else:\n", " print(\"Placed in Group C.\")\n", "\n", "# except AssertionError as error:\n", "# print(error)" ] } ], "metadata": { "coursera": { "course_slug": "neural-networks-deep-learning", "graded_item_id": "XHpfv", "launcher_item_id": "Zh0CU" }, "hide_input": false, "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.8.3" } }, "nbformat": 4, "nbformat_minor": 2 }