{"id":20058605,"url":"https://github.com/abhay-kanwasi/basic-python-programs","last_synced_at":"2025-03-02T09:42:29.921Z","repository":{"id":135635990,"uuid":"453100801","full_name":"Abhay-Kanwasi/Basic-Python-Programs","owner":"Abhay-Kanwasi","description":"This is a simple challenge series for python beginners","archived":false,"fork":false,"pushed_at":"2022-02-11T15:07:12.000Z","size":276,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-12T22:07:49.343Z","etag":null,"topics":["basic-programming","basic-python-programming","python","python3"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Abhay-Kanwasi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-28T14:37:00.000Z","updated_at":"2023-07-11T19:50:19.000Z","dependencies_parsed_at":null,"dependency_job_id":"561b28ee-f9df-4576-9b7e-146290acb174","html_url":"https://github.com/Abhay-Kanwasi/Basic-Python-Programs","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Abhay-Kanwasi%2FBasic-Python-Programs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Abhay-Kanwasi%2FBasic-Python-Programs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Abhay-Kanwasi%2FBasic-Python-Programs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Abhay-Kanwasi%2FBasic-Python-Programs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Abhay-Kanwasi","download_url":"https://codeload.github.com/Abhay-Kanwasi/Basic-Python-Programs/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241488154,"owners_count":19970826,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["basic-programming","basic-python-programming","python","python3"],"created_at":"2024-11-13T13:02:13.679Z","updated_at":"2025-03-02T09:42:29.900Z","avatar_url":"https://github.com/Abhay-Kanwasi.png","language":"Python","readme":"# Python-Basic-Program-Challenge-Series\nIn this series i cover each topics with various easy examples for every concept i create seprate file \n\n## Note\n\n### Please use wrap text in all the .py files when you open it in VS Code if you want to avoid the unnecessary question following. \n\n### For 2D graphics or turle graphics use Spyder IDE\n\n# 1. Basics\nPython is case sensitive so it is important that you use the correct case, otherwise\nyour code will not work.\nText values need to appear in speech marks (\") but numbers do\nnot.\n\nWhen naming variables (i.e. values that you want to store\ndata in) you cannot use any dedicated words such as print,\ninput, etc. otherwise your code will not work.\nWhen saving your files do not save them with any\ndedicated words that Python already uses, such as print,\ninput, etc. If you do this it will not run and you will need to\nrename the file before it works.\nTo edit a program you have saved and closed, right-click on the\nfile and select Edit with IDLE. If you just double-click on\nthe file it will only try to run it and you will not be able to edit it.\n\n`basic things`\n\n`addition`\nanswer = num1 + num2\nAdds together num1 and num2 and stores the\nanswer in a variable called answer.\n\n`subtraction`\nanswer = num1 - num2\nSubtracts num2 from num1 and stores the\nanswer in a variable called answer.\n\n`multiplication`\nanswer = num1 * num2\nMultiplies num1 by num2 and stores the\nanswer in a variable called answer.\n\n`division`\nanswer = num1 / num2\nDivides num1 by num2 and stores the answer\nin a variable called answer.\n\n`whole number division`\nanswer = num1 // num2\nA whole number division (i.e. 9//4 = 2) and\nstores the answer in a variable called answer.\n\n`diaplay the message`\nprint (“This is a message”)\nDisplays the message in the brackets. As the value we want displayed is a text value it\nhas the speech marks, which will not be displayed in the output. If you wanted to display\na numerical value or the contents of a variable, the speech marks are not needed.\n\n`next line`\nprint (“First line\\nSecond line”)\n“\\n” is used as a line break.\n\n`take input`\ntextValue = input(“Enter a text value: ”)\nDisplays the question “Enter a text value: ” and stores the value the user enters in a\nvariable called textValue. The space after the colon allows a space to be added before\nthe user enters their answer, otherwise they appear squashed unattractively together.\n\n`answer`\nprint (“The answer is”, answer)\nDisplays the text “The answer is” and the value of the variable answer.\n\n`taking integer``\nnumValue = int(input(“Enter a number: ”))\nDisplays the question “Enter a number: ” and stores the value as an\ninteger (a whole number) in a variable called numValue Integers can be\nused in calculations but variables stored as text cannot.\n\n\n\n# 2. If and Else\n\nI created ' if_else.py ' \nIn this we see \"If statement allow your program to make decision and change the route that is taken through\nthe program\nIn this i also cover basic concept of #Comparison_Operators\n \u003eOperator   Description\n \u003e ==         Equal to\n \u003e!=         Not equal to\n \u003e \" \u003e, \u003c,\"      Greater than, Less then\n \u003e \u003e=,\u003c=      Greater than equals to, Less then equals to\n  \n **Logical_Operators**\n Operator            Description\n   and          Both conditions must be met\n   or          Either conditions must be met\n\n# 3. Strings\n\nI created 'Strings.py'\nString is the technical name for text. To define a block of code as a string, you need to\ninclude it in either double quotes (\") or single quotes ('). It doesn’t matter which you use so\nlong as you are consistent.\nThere are some characters you need to be particularly careful with when inputting them\ninto strings. These include:\n\" ' \\\nThat is because these symbols have special meanings in Python and it can get confusing if\nyou use them in a string.\n\nMultiple-Line Strings\nIf you want to input a string across multiple lines you can either use the line break (\\n) or\nyou can enclose the entire thing in triple quotes. This will preserve the formatting of the\ntext.\n  address = \"\"\"123\n  Oldtown\n  ABI 43BF\"\"\"\n  print(address)\n \n \n### I also introduce some functions\n\n`len(word)`\nFnds the length of the variable called word.\n\n`word.upper()` \nChanges the string into upper case\n\n`print(word.capitalize())`\nDisplays the variable so only the first word\nhas a capital letter at the beginning and\neverything else is in lower case.\n\n`word.title()'\nChanges a phrase so that every word\nhas a capital letter at the beginning\nwith the rest of the letters in the\nword in lower case (i.e.Title Case).\n\n`text = “ This is some text. ”\nprint(text.strip(“ ”))`\nRemoves extra characters (in this case spaces) from the start and end of a string.\n\n`print (“Hello world”[7:10])`\nEach letter is assigned an index number to\nidentify its position in the phrase, including\nthe space. Python starts counting from 0, not\n1.\nTherefore, in this example, it would display\nthe value of positions 7, 8 and 9 ,which is\n“orl”.\nname = firstname+surname\n\n\n# 4. Math\n###I created math.py\nPython can perform several mathematical functions, but these are only available when the\ndata is treated as either an integer (a whole number) or a floating-point (a\nnumber with a decimal place). If data is stored as a string, even if it only contains numeric\ncharacters, Python is unable to perform calculations with it (see page 24 for a fuller\nexplanation).\n\n`import math.py`\nIn order to use some of the mathematical functions (math.sqrt(num)\nand math.pi) you will need to import the maths\nlibrary at the start of your program. You do this by\ntyping import math as the first line of your\nprogram.\n\n`float`\nnum=float(input(“Enter number: “))\nAllows numbers with a decimal point dividing the integer and fraction part.\n\n`decimal places`\nprint(round(num,2))\nDisplays a number rounded to\ntwo decimal places.\n\n`square root`\n**\nTo the power of\n(e.g. 102 is 10**2).\nmath.sqrt(num)\nThe square root of a number, but you must have the line import\nmath at the top of your program for this to work.\n\n'pie`\nmath.pi\nGives you pi (π) to 15 decimal places,\nbut you must have the line import\nmath at the top of your program for\nthis to work.\n\n`whole number division`\nx // y\nWhole number division (e.g.15//2 gives\nthe answer 7).\n\n`x%y`\nx % y\nFinds the remainder (e.g. 15%2 gives\nthe answer 1).\n\n# 5. For loop\nI created loops.py\nA for loop allows Python to keep repeating code a set number of times. It is sometimes\nknown as a counting loop because you know the number of times the loop will run\nbefore it starts.\n\nThe range function is often used in for loops and lists the starting number, the ending\nnumber and can also include the steps (e.g. counting in 1s, 5s or any other value you wish).\n\n`about loop`\n\nfor i in range(1,10):\nprint(i)\nThis loop uses a variable called “i” to keep track of the number of times\nthe loop has been repeated. It will start i at 1 (as that is the starting\nvalue in the range function) and repeat the loop, adding 1 to i each time\nand displaying the value of i until it reaches 10 (as dictated by the range\nfunction), where it will stop. Therefore, it will not repeat the loop a tenth\ntime and will only have the following output:\n1, 2, 3, 4, 5, 6, 7, 8, 9\n\n`case1`\n\nfor i in range(1,10,2):\nprint(i)\nThis range function includes a third value\nwhich shows how much is added to i in\neach loop (in this case 2). The output will\ntherefore be: 1, 3, 5, 7, 9\n\n`case2`\n\nfor i in range(10,1,-3):\nprint(i)\nThis range will subtract 3 from i each\ntime. The output will be: 10, 7, 4\nfor i\n\n# 6 While loop\n\nA while loop allows code to be repeated an unknown number of times\nas long as a condition is being met. This may be 100 times, just the once or\neven never. In a while loop the condition is checked before the code is run,\nwhich means it could skip the loop altogether if the condition is not being\nmet to start with. It is important, therefore, to make sure the correct\nconditions are in place to run the loop before it starts.\n\nI created while_loop.py to cover it\n\n# 7. Random\n\nPython can generate random values. In reality, the values are not\ncompletely random as no computer can cope with that; instead it uses an\nincredibly complex algorithm that makes it virtually impossible to accurately\npredict its outcome so, in effect, it acts like a random function.\nThere are two types of random value that we will be looking at:\n\nRandom numbers within a specified range;\nA random choice from a range of items that are input.\n\nTo use these two options, you will need to import the random library. You do\nthis by typing import random at the start of your program\n\nFor this I created random.py \n\n### Some useful example of random which we use in random.py\n\n`import random`\nThis must appear at the start of your program otherwise the random function will not\nwork.\n\n`num = random.random()`\nSelects a random floating-point number between 0 and 1 and\nstores it in a variable called “num”. If you want to obtain a\nlarger number, you can multiply it as shown below:\nimport random\nnum = random.random()\nnum = num * 100\nprint(num)\n\n`num = random.randint(0,9)`\nSelects a random whole number\nbetween 0 and 9 (inclusive).\n\n`num1 = random.randint(0,1000)\nnum2 = random.randint(0,1000)\nnewrand = num1/num2\nprint(newrand)`\nCreates a random floating-point number by\ncreating two random integers within two\nlarge ranges (in this case between 0 and 1000) and dividing one by the other.\n\n`num = random.randrange(0,100,5)`\nPicks a random number between the\nnumbers 0 and 100 (inclusive) in steps of five,\ni.e. it will only pick from 0, 5, 10, 15, 20, etc.\n\n`colour = random.choice([“red”,“black”,“green”])`\nPicks a random value from the options “red”, “black” or “green” and stores it as the\nvariable “colour”. Remember: strings need to include speech marks but numeric data\ndoes not.\n\n# 8. Turtle Graphics\nFor this I created turtle.py\n\nIt is possible to draw using a turtle in Python. By typing in commands\nand using loops, you can create intricate patterns. Here is how it works.\nA turtle will travel along a path that you define, leaving a pen mark behind it. As you control\nthe turtle, the pattern that is left is revealed. To draw the pentagon shown below you would\ntype in the following code.\n\nimport turtle\n\nturtle.shape(\"turtle\")\nfor i in range(0,5):\n turtle.forward(100)\n turtle.right(72)\nturtle.exitonclick()\n\nBy combining these simple shapes and using nested loops (i.e. loops inside other loops)\nit is possible to create beautiful patterns very easily.\n\n`import turtle`\nThis line needs to be included\nat the beginning of your\nprogram to import the turtle\nlibrary into Python, allowing\nyou to use the turtle functions.\n\n`scr = turtle.Screen()`\nDefines the window as being\ncalled “scr”. This means we can\nuse the shorthand “scr”, rather\nthan having to refer to the window\nby its full name each time.\n\n`scr.bgcolor(“yellow”)`\nSets the screen background\ncolour to yellow. By default, the\nbackground colour will be\nwhite unless it is changed.\n\n`turtle.pensize(3)`\nChanges the turtle pen size\n(the thickness of the line that is\ndrawn) to 3. By default, this is 1\nunless it is changed.\n\n`turtle.penup()`\nRemoves the pen from\nthe page so that as the\nturtle moves it does not\nleave a trail behind it.\n\n`turtle.pendown()`\nPlaces the pen on the\npage so that when the\nturtle moves it will\nleave a trail behind it.\nBy default, the pen is\ndown unless specified\notherwise.\n\n`turtle.forward(50)`\nMoves the turtle forward 50\nsteps.\n\n`turtle.left(120)`\nTurns the turtle 120° to\nthe left (counter\nclockwise). turtle.right(90)\nTurns the turtle 90° to\nthe right (clockwise).\n\n`turtle.showturtle()`\nShows the turtle on the screen.\nBy default, the turtle is\nshowing unless specified\notherwise.\n\n`turtle.hideturtle()`\nHides the turtle so it is not\nshowing on the screen.\n\n`turtle.shape(“turtle”)`\nChanges the shape of the turtle to look like a turtle\n. By default, the turtle will look like a small arrow.\n\n`turtle.exitonclick()`\nWhen the user clicks on the\nturtle window it will\nautomatically close.\n\n`turtle.begin_fill()`\nEntered before the code that draws a shape so it\nknows to fill in the shape it is drawing.\n\n`turtle.end_fill()`\nEntered after the code that is drawing the shape to\ntell Python to stop filling in the shape.\n\n`turtle.color(“black”,“red”)`\nDefines the colours filling in the shape. This\nexample will make the shape have a black outline\nand a red fill. This needs to be entered before the\nshape is drawn.\n\n# 9. Dictionaries\n\nSo far, we have used variables that can store a single item of data in them. When you used\nthe random.choice([“red”,“blue”,“green”]) line of code you are picking a\nrandom item from a list of possible options. This demonstrates that one item can hold\nseveral pieces of separate data, in this case a collection of colours.\nThere are several ways that collections of data can be stored as a\nsingle item. Three of the simpler ones are:\n1. tuples\n2. lists\n3. dictionaries\n\n`Tuples`\n\nOnce a tuple is defined you cannot change what is stored in it. This means that when you\nwrite the program you must state what the data is that is being stored in the tuple and the\ndata cannot be altered while the program is running. Tuples are usually used for menu\nitems that would not need to be changed.\n\n`Lists`\n\nThe contents of a list can be changed while the program is running and lists are one of\nthe most common ways to store a collection of data under one variable name in Python. The\ndata in a list does not all have to be of the same data type. For example, the same list can\nstore both strings and integers; however, this can cause problems later and is therefore not\nrecommended.\n\n`Dictionaries`\n\nThe contents of a dictionary can also be changed while the program is running. Each\nvalue is given an index or key you can define to help identify each piece of data. This index\nwill not change if other rows of data are added or deleted, unlike lists where the position of\nthe items can change and therefore their index number will also change.\n\nSome things we used in dictionaries.py\n\n`fruit_tuple = (“apple”,“banana”,“strawberry”,“orange”)`\n\nCreates a variable name called “fruit_tuple” which stores four pieces of fruit within it. The\nround brackets define this group as a tuple and therefore the contents of this collection of\ndata cannot be altered while the program is running.\n\n`print(fruit_tuple.index(“strawberry”))`\n\nDisplays the index (i.e. the numeric key) of the item “strawberry”. In this example it\nwill return the number 2 as Python starts counting the items from 0, not 1.\n\n`print(fruit_tuple[2])`\n\nDisplays item 2 from\n“fruit_tuple”, in this case\n“strawberry”.\n\n`names_list = [“John”,“Tim”,“Sam”]`\n\nCreates a list of the names and stores them in the\nvariable “names_list”. The square brackets define\nthis group of data as a list and therefore the contents\ncan be altered while the program is running.\n\n`names_list.append(input(“Add a name: “))`\n\nAsks the user to enter a name and will add that to the end of\n“names_list”.\ndel names_list[1]\nDeletes item 1 from\n“names_list”. Remember\nit starts counting from 0\nand not 1. In this case it\nwill delete “Tim” from the\nlist.\n\n`print(sorted(names_list))`\n\nDisplays names_list in alphabetical\norder but does not change the order of\nthe original list, which is still saved in\nthe original order. This does not work\nif the list is storing data of different\ntypes, such as strings and numeric\ndata in the same list.\n\n`names_list.sort()`\n\nSorts name_list into\nalphabetical order and\nsaves the list in the new\norder. This does not work\nif the list is storing data of\ndifferent types, such as\nstrings and numeric data\nin the same list.\n\n`colours = {1:“red”,2:“blue”,3:“green”}`\n\nCreates a dictionary called “colours”, where each item is\nassigned an index of your choosing. The first item in each\nblock is the index, separated by a colon and then the\ncolour.\n\n`colours[2] = “yellow”`\n\nMakes a change to the data stored in position 2 of the colours dictionary. In this case it will\nchange “blue” to “yellow”.\n\n`x = [154,634,892,345,341,43]`\n\nHere we have created a list that contains\nnumbers. Please note: as it contains numeric\ndata, no speech marks are required.\n\n`print(x[1:4])`\n\nThis will display data in positions 1, 2 and 3. In\nthis case 634, 892 and 345. Remember, Python\nstarts counting from 0 and will stop when it gets\nto the last position, without showing the final\nvalue.\n\n`print(len(x))`\n\nDisplays the length of the list\n(i.e. how many items are in the\nlist).\nnum = int(input(“Enter number: ”))\nif num in x:\nprint(num,“is in the list”)\nelse:\nprint(“Not in the list”)\nAsks the user to enter a number and checks\nwhether the number is in the list and displays an\nappropriate message.\n\n`for i in x:\nprint(i)`\n\nUses the items in the list in a for\nloop, useful if you want to print\nthe items in a list on separate\nlines.\n\n`x.insert(2,420)`\n\nInserts the number\n420 into position 2 and\npushes everything\nelse along to make\nspace. This will\nchange the index\nnumbers of the items\nin the list.\n\n`x.remove(892)`\n\nDeletes an item from\nthe list. This is useful\nif you do not know the\nindex of that item. If\nthere is more than one\ninstance of the data it\nwill only delete the\nfirst instance.\n\n`x.append(993)`\n\nAdds the number 993 to the end of the list.\n\n\n# 10. String Manipulation\n\n**Explanation\n\nA string is the technical name for a group of characters that you do not need to perform\ncalculations with. “Hello” would be an example of a string, as would “7B”.\nHere we have a variable called name which is assigned the value “Simon”.\n\n### Example which we used in string2.py\n\nPlease note: in the examples below, “msg” is a variable name containing a string.\n\n`First one`\nif msg.isupper():\nprint(“Uppercase”)\nelse:\nprint(“This is not in uppercase”)\nIf the message is in uppercase it will display the message\n“Uppercase”, otherwise it will display the message “This\nis not in uppercase”.\n\n`Second one`\nmsg.islower()\nCan be used in place of\nthe isupper () function\nto check if the variable\ncontains lower case\nletters.\n\n`Third one`\nmsg=”Hello”\nfor letter in msg:\nprint(letter,end=”*”)\nDisplays the message, and between each character it will display a “*”.\nThe output in this example will be: H*e*l*l*o*\n\n\n# 11. Numeric Arrays\n\nLists can store a jumble of different types\nof data at the same time, including strings and numbers. Python arrays are similar to\nlists, but they are only used to store numbers. Numbers can have varying ranges, but\nin an array all pieces of data in that array must have the same data type.\n\n`Integer`\nWhole number between -32,768 and 32,767 \nsize = 2bytes\n\n`Long`\nWhole number between -2,147,483,648 and 2,147,483,647 \nsize = 4bytes\n\n`Floating-point`\nAllows decimal places with numbers ranging\nfrom -1038 to 1038 (i.e. allows up to 38 numeric\ncharacters including a single decimal point\nanywhere in that number and can be negative or\npositive value)\nsize = 4bytes\n\n`Double`\nAllows decimal places with numbers ranging\nfrom -10308 to 10308.\nsize = 8bytes\n\nWhen you create your array you need to define the type of data it will contain. You cannot\nalter or change this while the program is running. Therefore, if you define an array as an 'i'\ntype (this allows whole numbers between the values −32,768 and 32,767) you cannot add a\ndecimal point to a number in that array later as it will cause an error message and crash the\nprogram.\n\n### Please note:\nOther programming languages use the term array to\nallow the storage of any data type, but in Python arrays only store numbers whereas lists\nallow the storage of any data type. If you want to create a variable that stores multiple\nstrings, in Python you need to create a list rather than an array.\n\n`importing array`\n\nfrom array import *\nThis needs to be the first line of your program so that\nPython can use the array library.\n\n`for sorting`\n\nnums = sorted(nums)\nSorts the array into\nascending order.\n\n`new value`\n\nnewValue = int(input(“Enter number: “))\nnums.append(newValue)\nAsks the user to enter a new number which it will add to\nthe end of the existing array.\n\n`new array`\n\nnewArray = array(‘i’,[])\nmore = int(input(“How many items: ”))\nfor y in range(0,more):\nnewValue=int(input(“Enter num: ”))\nnewArray.append(newValue)\nnums.extend(newArray)\nCreates a blank array called “newArray” which uses the\ninteger data type. It asks the user how many items they\nwant to add and then appends these new items to\nnewArray. After all the items have been added it will join\ntogether the contents of newArray and the nums array.\n\n`display`\n\nfor x in nums:\nprint(x)\nDisplays the array with\neach item appearing on\na separate line.\n\n`number reverse`\n\nnums.reverse()\nReverses the order of\nthe array.\n\n`remove`\n\n1. getRid = int(input(“Enter item index: ”))\nnums.remove(getRid)\nAsks the user to enter the item they want to get rid of and then removes the first item\nthat matches that value from the array.\n\n2. nums.pop()\nThis will remove the last\nitem from the array.\n\n`count`\n\nprint(nums.count(45))\nThis will display how many times the value “45” appears in the array.\n\n# 12. 2D Lists and Dictionaries\n\nTechnically it is possible to create a two-dimensional array in Python, but as Python arrays\nare limited to storing numbers and most Python programmers feel more comfortable with\nworking with lists, 2D arrays are rarely used and 2D lists are far more common.\nImagine, for one terrifying moment, you are a teacher. Scary I know! Also\nimagine you have four students and you teach those same students across\nthree different subjects. You may, if you are a conscientious teacher, need to\nkeep records of those students’ grades for each of their subjects. It is possible to create a\nsimple chart on paper to do this as follows:\nMaths English French\nSusan 45 37 54\nPeter 62 58 59\nMark 49 47 60\nAndy 78 83 62\n\n### Logic we used in 2D_List_and_Dictionaries.py\n\n`simple_array = [[2,5,8],[3,7,4],[1,6,9]]`\n\nCreates a 2D list (as shown on the right) which uses\nstandard Python indexing for the rows and columns.\n\n`print(simple_array)`\n\nDisplays all the data in the 2D\nlist.\n\n`print(simple_array[1])`\n\nDisplays data from row 1, in this case\n[3, 7, 4].\n\n`print(simple_array[1][2])`\n\nDisplays data from row 1, column 2, in\nthis case 4.\n\n`simple_array[2][1]= 5`\n\nChanges the data in row 2,\ncolumn 1 to the value 5.\n\n`simple_array[1].append(3)`\n\nAdds the value 3 onto the end of the data in\nrow 1 so in this case it becomes [3, 7, 4, 3].\n\n`data_set = {“A”:{“x”:54,“y”:82,“z”:91},“B”:{“x”:75,“y”:29,“z”:80}}`\n\nCreates a 2D dictionary using user-defined labels for the rows and columns (as shown\nabove).\n\n`print(data_set[“A”])`\n\nDisplays data from data set “A”.\n\n`print(data_set[“B”][“y”])`\n\nDisplays data from row “B”, column “y”.\n\n`grades[name]={“Maths”:mscore,“English”:escore}`\n\nAdds another row of data to a 2D dictionary. In this case, name would be the row index\nand Maths and English would be the column indexes.\n\n`for name in grades:\nprint((name),grades[name][“English”])`\n\nDisplays only the name and the English grade for each\nstudent.\n\n`for i in data_set:\nprint(data_set [i][“y”])`\n\nDisplays the “y” column from each row.\ndel list[getRid]\nRemoves a selected\nitem.\n\n`data_set[“B”][“y”] = 53`\n\nChanges the data in “B”, “y”, to 53.\n\n\n# 13. Reading and Writing to a Text File\n\n### I create a seperate folder Textfile for storing this code and output text.\n\nIt is all very well being able to define a list, make changes and add new data, but if the next\ntime the program is run it returns to the original data and your changes are lost then it is\nnot a lot of use. Therefore, it is sometimes necessary to save data outside of the program\nand this way the data can be stored, along with any changes that are made.\nThe easiest place to start learning about writing and reading from an external\nfile is with a text file.\nWhen opening an external file you must specify how that file will be used within the\nprogram. The options are below.\n\n`Code - w`\n\nWrite mode: used to create a new file. Any existing files\nwith the same name will be erased and a new one\ncreated in its place.\n\n`Code - r`\n\nRead mode: used when an existing file is only being\nread and not being written to.\n\n`Code - a`\n\nAppend mode: used to add new data to the end of the\nfile.\n\nText files are only used to write, read and append data. By the very nature of how they work\nit is not easy to remove or alter individual elements of data once it is written to the file,\nunless you want to overwrite the entire file or create a new file to store the new\ndata. If you want to be able to alter the individual elements once the file has\nbeen created it is better to use a .csv file (see after some time) or an SQL database (see\nafter some time).\n\n## Code we use here\n\n`file = open(“Countries.txt”,“w”)\nfile.write(“Italy\\n”)\nfile.write(“Germany\\n”)\nfile.write(“Spain\\n”)\nfile.close()`\n\nCreates a file called “Countries.txt”. If one already exists then it will be overwritten with\na new blank file. It will add three lines of data to the file (the \\n forces a new line after\neach entry). It will then close the file, allowing the changes to the text file to be saved.\n\n`file = open(“Countries.txt”,“r”)\nprint(file.read())`\n\nThis will open the Countries.txt file in “read”\nmode and display the entire file.\n\n`file = open(“Countries.txt”,“a”)\nfile.write(“France\\n”)\nfile.close()`\n\nThis will open the Countries.txt file in “append”\nmode, add another line and then close the file.\nIf the file.close() line is not included, the\nchanges will not be saved to the text file.\n\n\n# 14. Reading and Writing to a .csv File\n\nCSV stands for Comma Separated Values and is a format usually associated with importing\nand exporting from spreadsheets and databases. It allows greater control over the data\nthan a simple text file, as each row is split up into identifiable columns. Below is an\nexample of data you may want to store.\n\nName   Age  Starsign\nBrian  73   Taurus\nSandra 48   Virgo\nZoe    25   Scorpio\n\n### When opening a .csv file to use, you must specify how that file will be used. The options are:\n\n`w`\n\nCreates a new file and writes to that file. If the file\nalready exists, a new file will be created, overwriting\nthe existing file.\n\n`x`\n\nCreates a new file and writes to that file. If the file\nalready exists, the program will crash rather than\noverwrite it.\n\n`r`\n\nOpens for reading only and will not allow you to make\nchanges.\n\n`a`\n\nOpens for writing, appending to the end of the file.\n\n### Code we use in Txtfile folder in  R_W_to_csv_file.py\n\n`import csv`\n\nThis must be at\nthe top of your\nprogram to allow\nPython to use the\n.csv library of\ncommands.\n\n\n\n`file = open (“Stars.csv”,“w”)\nnewRecord = “Brian,73,Taurus\\n”\nfile.write(str(newRecord))\nfile.close()`\n\nThis will create a new file called “Stars.csv”, overwriting any\nprevious files of the same name. It will add a new record and\nthen close and save the changes to the file.\n\n\n\n`file = open (“Stars.csv”,“a”)\nname = input(“Enter name: ”)\nage = input(“Enter age: ”)\nstar = input(“Enter star sign: ”)\nnewRecord = name + “,” + age + “,” + star + “\\n”\nfile.write(str(newRecord))\nfile.close()`\n\nThis will open the Stars.csv file, ask the user to enter the name, age\nand star sign, and will append this to the end of the file.\n\n\n\n`file = open(“Stars.csv”,“r”)\nfor row in file:\nprint(row)`\n\nThis will open the Stars.csv file in read\nmode and display the records one row at\na time.\n\n\n\n`file = open(“Stars.csv”,“r”)\nreader = csv.reader(file)\nrows = list(reader)\nprint(rows[1])`\n\nThis will open the Stars.csv file and\ndisplay only row 1. Remember, Python\nstarts counting from 0.\n\n\n\n`file = open (“Stars.csv”,“r”)\nsearch = input(“Enter the data you are searching for: ”)\nreader = csv.reader(file)\nfor row in file:\nif search in str(row):\nprint(row)`\n\nAsks the user to enter the data they are searching for. It will display all rows that contain\nthat data anywhere in that row.\n\n\n\n`import csv\nfile = list(csv.reader(open(“Stars.csv”)))\ntmp = []\nfor row in file:\ntmp.append(row)`\n\nA .csv file cannot be altered, only added to. If you need to alter the file you need to\nwrite it to a temporary list. This block of code will read the original .csv file and write it\nto a list called “tmp”. This can then be used and altered as a list.\n\n\n\n`file = open(“NewStars.csv”,“w”)\nx = 0\nfor row in tmp:\nnewRec = tmp[x][0] + ”,” + tmp[x][1] + ”,” + tmp[x][2] + ”\\n”\nfile.write(newRec)\nx = x + 1\nfile.close()`\n\nWrites from a list into a new .csv file called “NewStars.csv”.\n\n\n# 15. Subprograms\n\nSubprograms are blocks of code which perform specific\ntasks and can be called upon at any time in the program to\nrun that code.\n\n**Advantages\n\n1. You can write a block of code and it can be used and reused\nat different times during the program.\n\n2. It makes the program simpler to understand as the code\nis grouped together into chunks.\n\n\n**Defining a subprogram and passing variables between subprograms\n\nBelow is a simple program that we would normally create\nwithout subprograms but have written it with subprograms\nso you can see how they work:\n\n`def get_name():\n user_name = input(\"Enter your name :\")\n return user_name\n \ndef print_Msg(user_name) :\n print(\"Hello\", user_name)\n \ndef main()\n user_name = get_name()\n print_Msg(user_name)\n\nmain()`\n\n**Explanation of this whole program : \n\nThis program uses three subprograms get_name(), print_Msg() and main().\nThe get_name() subprogram will ask the user to input their name and then it will return\nthe value of the variable “user_name” so that it can be used in another subprogram. This is\nvery important. If you do not return the values, then the values of any variables that were\ncreated or altered in that subprogram cannot be used elsewhere in your program.\n\nThe variable “user_name” appears in the brackets as the current value of the variable is\nbeing imported into the subprogram so it can be used.\nThe main() subprogram will get the user_name from the get_name() subprogram\n(using the variable user_name) as this was returned from the get_name() subprogram. It\nwill then use that user_name variable in the print_Msg() subprogram.\nThe last line “main()” is the actual program itself. All this will do is start the main()\nsubprogram running.\nObviously, there is no need to create such a convoluted way of performing what is in fact a\nvery simple program, but this is only used as an example of how subprograms are laid out\nand variables can be used and passed between the subprograms.\n\n**Please note:**\n\nPython does not like surprises, so if you are going\nto use a subprogram in a program, Python must have read the\n“def subprogram_name()” line before so it knows where to\ngo to find it. If you try to refer to a subprogram before Python has\nread about it, it panics and will crash. When calling a\nsubprogram, the subprogram must be written above the section\nof code you use to call it. Python will read from the top down and run the first line it comes\nacross that has not been indented and does not start with the word def. In the program\nabove this would be main().\n\n## Code we used on subprogram.py with explanation.\n\n`Code 1`\n\ndef get_data():\nuser_name = input(“Enter your name: ”)\nuser_age = int(input(“Enter your age: ”))\ndata_tuple = (user_name, user_age)\nreturn data_tuple\n\n**Explanation**\n\nDefines a subprogram called “get_data()” which will ask the user for their name and\nage. As we want to send more than one piece of data back to the main program for other\nparts of the program to use, we have combined them together. The return line can only\nreturn a single value, which is why we combined the user_name and user_age variables\ninto a tuple (see page 58) called data_tuple.\n\n`Code 2`\n\ndef message(user_name,user_age):\nif user_age \u003c= 10:\nprint(“Hi”, user_name)\nelse:\nprint(“Hello”, user_name)\n\n**Explanation**\n\nDefines a subprogram called message() which uses two variables that have previously\nbeen defined (user_name and user_age).\n\n`Code 3`\n\ndef main():\nuser_name,user_age = get_data()\nmessage(user_name,user_age)\n\n**Explanation**\n\nDefines a subprogram called main() which obtains the\ntwo variables from the get_data() subprogram. These\nmust be labelled in the same order as they were\ndefined in the tuple. It then calls the message()\nsubprogram to run with the two variables.\n\n`Code 4`\n\nmain()\n\n**Explanation**\n\nRuns the main() subprogram.\n\n\n\n# 16. Tkinter GUI\n\n\nA GUI (graphical user interface) makes the program easier to use. It allows you, as the\nprogrammer, to create screens, text boxes and buttons to help the user navigate through\nthe program in a more user-friendly way. Tkinter is a library of features in Python that\nallows you to do this.\n\n### Code we used in tkinterGUI.py\n\n`Code 1`\n\nfrom tkinter import *\n\nThis line must go at the beginning of the program to import the Tkinter library.\n\n`Code 2`\n\nwindow = Tk()\nwindow.title(“Window Title”)\nwindow.geometry(“450x100”)\n\nCreates a window that will act as the\ndisplay, referred to as “window”, adds a title\nand defines the size of the window.\n\n`Code 3`\n\nlabel = Label(text = “Enter number:”)\n\nAdds text to the screen displaying the message\nshown.\n\n`Code 4`\n\nentry_box = Entry (text = 0)\n\nCreates a blank entry box. Entry boxes can be used by\nthe user to input data or used to display output.\n\n`Code 5`\n\noutput_box = Message(text = 0)\n\nCreates a message box which is used to display an\noutput.\n\n`Code 6`\n\nlist_box = Listbox()\n\nCreates a drop-down list box\nwhich can only contain strings.\n\n`Code 7`\n\nbutton1 = Button(text = “Click here”, command = click)\n\nCreates a button that will run the subprogram “click”.\n\n`Code 8`\n\noutput_box [“bg”] = “red”\n\nSpecifies the background colour of the\nobject.\n\n`Code 9`\n\noutput_box [“fg”] = “white”\n\nSpecifies the font colour of the object.\n\n`Code 10`\n\noutput_box [“relief”] = “sunken”\n\nSpecifies the style of the box. This can be flat,\nraised, sunken, grooved and ridged.\n\n`Code 11`\n\nentry_box [“justify”] = “center”\n\nSpecifies the justification of the text in an entry box,\nbut this does not work for message boxes.\n\n`Code 12`\n\nlabel.place(x = 50, y = 20, width = 100, height = 25)\n\nSpecifies the position in which the object will appear in the window. If the position is\nnot specified the item will not appear in the window.\n\n`Code 13`\n\nentry_box.delete(0, END)\n\nDeletes the contents of an entry or\nlist box.\n\n`Code 14`\n\nnum = entry_box.get()\n\nSaves the contents of an entry box and stores it\nin a variable called num. This does not work\nwith message boxes.\n\n`Code 15`\n\nanswer = output_txt[“text”]\n\nObtains the contents of a message box and\nstores it in a variable called answer. This does\nnot work with an entry box.\n\n`Code 16`\n\noutput_txt[“text”] = total\n\nChanges the content of a message box to\ndisplay the value of the variable total.\n\n`Code 17`\n\nwindow.mainloop()\n\nThis must be at the end of the program to make\nsure it keeps working.\n\n# 17. More Tkinter\n\nHere we will look at creating a GUI which includes more features and builds on the\nknowledge from the previous chapter.\n\nAll the code to create this window can be created using the code we looked at in the\nprevious section and the example code you will be looking at in this chapter.\nWhen using images in your program, it is easier if they are stored in the same folder as the\nprogram. Otherwise you need to include the entire dictionary location of the file.\n\n\n** Please note: **\n\nit is only possible to use GIF or PGM/PPM file types for images in Tkinter as\nother file types are not supported. Make sure your images are saved in a suitable format\nand with a suitable name in the correct location before you start creating the programs, if at\nall possible, to make your life simpler.\n\n### Code we used in tkinterGUI2.py\n\n`Code 1`\n\nwindow.wm_iconbitmap(“MyIcon.ico”)\n\nChanges the icon displayed in the title of the window.\n\n`Code 2`\n\nwindow.configure(background = “light green”)\n\nChanges the background colour of the window, in this case to light green.\n\n`Code 3`\n\nlogo = PhotoImage(file = “logo.gif”)\nlogoimage = Label(image = logo)\nlogoimage.place(x = 30, y = 20, width = 200, height = 120)\n\nDisplays an image in a label widget. This image will not change while the program is\nrunning.\n\n`Code 4`\n\nphoto = PhotoImage(file = “logo.gif”)\nphotobox = Label(window, image = photo)\nphotobox.image = photo\nphotobox.place(x = 30, y = 20, width = 200, height = 120)\n\nThis is similar to the block above but as we want the image to change as we update the\ndata we need to add the code photobox.image = photo, which makes it\nupdatable.\n\n`Code 5`\n\nselectName = StringVar(window)\nselectName.set(“Select Name”)\nnamesList = OptionMenu(window,selectName,“Bob”,“Sue”,“Tim”)\nnamesList.place(x = 30, y = 250)\n\nCreates a variable called selectName which will store a string where the original\nvalue of the variable is “Select Name”. It will then create a drop-down option menu\nwhich stores the value the user selects in the selectName variable and displays the\nvalues in the list: Bob, Sue and Tim.\n\n\n`Example :-`\n\ndef clicked():\nsel = selectName.get()\nmesg = “Hello “ + sel\nmlabel[“text”] = mesg\nif sel == “Bob”:\nphoto = PhotoImage(file = “Bob.gif”)\nphotobox.image = photo\nelif sel == “Sue”:\nphoto = PhotoImage(file = “Sue.gif”)\nphotobox.image = photo\nelif sel == “Tim”:\nphoto = PhotoImage(file = “Tim.gif”)\nphotobox.image = photo\nelse:\nphoto = PhotoImage(file = “logo.gif”)\nphotobox.image = photo\nphotobox[“image”] = photo\nphotobox.update()\n\n**Explanation**\n\nIn this example, when a button is clicked it will run the “clicked” subprogram. This will\nobtain the value from the selectName variable and create a message that will be\ndisplayed in a label. It will then check to see which option has been selected and\nchange the picture to the correct image, which is displayed in the photo variable. If no\nname is selected it will simply show the logo.\n\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fabhay-kanwasi%2Fbasic-python-programs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fabhay-kanwasi%2Fbasic-python-programs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fabhay-kanwasi%2Fbasic-python-programs/lists"}