<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Simon Chalder</title>
    <description>The latest articles on Forem by Simon Chalder (@simonchalder).</description>
    <link>https://forem.com/simonchalder</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F407141%2F12d60056-56a6-4f69-9675-e4f25990276e.jpeg</url>
      <title>Forem: Simon Chalder</title>
      <link>https://forem.com/simonchalder</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/simonchalder"/>
    <language>en</language>
    <item>
      <title>Part Ten: PIP, External Modules and GitHub</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Tue, 13 Dec 2022 19:47:51 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-ten-pip-external-modules-and-github-2f22</link>
      <guid>https://forem.com/simonchalder/part-ten-pip-external-modules-and-github-2f22</guid>
      <description>&lt;p&gt;Welcome to part ten. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this final article we will look at how to install and use a package manager, import modules from an online repository, and take a look at some modules which may be of interest to land based workers and students.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"Most of you are familiar with the virtues of a programmer. There are three, of course: laziness, impatience, and hubris." - &lt;em&gt;Larry Wall&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;Sharing Is Caring&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;So, why would we want to use someone else's code? That's cheating isn't it? No, not at all! In fact, sharing our code encourages some rather fantastic things - the free sharing of experience and knowledge, and people coming together to collaborate on projects.&lt;/p&gt;

&lt;p&gt;People share their code online for a number of reasons. Firstly there is the bragging rights to say that 'x number of people have downloaded or subscribed to my project this month'. Others have taken existing projects and re-written them is a way that they feel is better and wish to share it with the world. Some use their code as a resume for coding jobs. &lt;/p&gt;

&lt;p&gt;Whatever the reason, sharing code online for free is a great thing to do and it's even become an &lt;a href="https://itsfoss.com/what-is-foss/"&gt;online movement&lt;/a&gt;. So how do we do it? There are several online repositories where we can upload and store our code for all to see and use. The largest and most well known is GitHub, now owned by Microsoft, but there are others such as GitLab etc. In order to upload code or use other people's modules we need to be part of the GitHub community. Unless you have ethical issues with Microsoft products (some people do), you can go to &lt;a href="https://github.com/signup"&gt;GitHub's signup page&lt;/a&gt; and create an account so do that first if you do not already have one.&lt;/p&gt;

&lt;p&gt;OK, now that's out of the way we can now take a look at the &lt;em&gt;millions&lt;/em&gt; of coding projects currently being hosted on the site. In the search bar type 'python' and hit enter to see what we can find. At the time of writing there are 2,725,251 code repositories with the tag 'python'. That's a lot of projects! Let's go back to the search bar and this time search for 'pandas'. At the top of the search results you should see 'pandas-dev/pandas', click on the link.&lt;/p&gt;

&lt;p&gt;What you are looking at is the GitHub repository page for the 'Pandas' project. Unfortunately 'pandas' has nothing to do with the clumsy black and white bears. Instead it is a powerful tool for data analysis.&lt;/p&gt;

&lt;p&gt;So let's say we have read the project introduction and we like what we read. How do we use this module with our code? If we scroll down the page we will eventually come to the 'Where to get it?' section. You won't see any installer files to download here, instead there are two options; one for 'conda' and one for 'pip'. Conda and pip are package managers for Python and we can use them to install, modify or uninstall packages found in online repositories.&lt;/p&gt;

&lt;p&gt;For this article, I am going to be using 'pip' (short for PIP Installs Packages) so we need to install that first. Take a look at &lt;a href="https://pip.pypa.io/en/stable/installation/"&gt;this page&lt;/a&gt; and look for installation instructions for your operating system. Open up a shell prompt on your device and copy and paste the commands shown on the pip website to install pip.&lt;/p&gt;

&lt;p&gt;To check if pip is installed correctly, open up a command prompt and type the following and press enter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip -V
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you see 'pip' followed by a version number, you are good to go.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Installing Packages With PIP&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Now that we have pip installed we can install our first online module. In your command prompt type the following and then press enter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install pandas
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see something similar to the image below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ISUSmJ6p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rro2pkk7kgzrijbt4vh1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ISUSmJ6p--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rro2pkk7kgzrijbt4vh1.jpg" alt="pandas install" width="853" height="259"&gt;&lt;/a&gt;&lt;br&gt;
We can check to see if the module installed properly as well as get a list of all installed modules with the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You may have noticed that pip also installed something called 'numpy'. This is another module which deals with mathematical operations and is required by pandas in order for it to function properly. This is known as a dependency and pip handles this automatically.&lt;/p&gt;

&lt;p&gt;To install any module with pip use the following syntax &lt;code&gt;pip install [module]&lt;/code&gt;. If you are unsure of the module name you can look for it in pip with the following command &lt;code&gt;pip search [module]&lt;/code&gt;. We can also remove installed modules with &lt;code&gt;pip uninstall [module]&lt;/code&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Importing Installed Modules&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;If we go back to our IDE and open a new project, we should now be able to import 'pandas' as though it was a built in module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import pandas
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can confirm this is working with the &lt;code&gt;dir()&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(dir(pandas))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All being well we should get the following output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['ArrowDtype', 'BooleanDtype', 'Categorical', 'CategoricalDtype', 'CategoricalIndex', 'DataFrame', 'DateOffset', 'DatetimeIndex', 'DatetimeTZDtype', 'ExcelFile', 'ExcelWriter', 'Flags', 'Float32Dtype', 'Float64Dtype', 'Float64Index', 'Grouper', 'HDFStore', 'Index', 'IndexSlice', 'Int16Dtype', 'Int32Dtype', 'Int64Dtype', 'Int64Index', 'Int8Dtype', 'Interval', 'IntervalDtype', 'IntervalIndex', 'MultiIndex', 'NA', 'NaT', 'NamedAgg', 'Period', 'PeriodDtype', 'PeriodIndex', 'RangeIndex', 'Series', 'SparseDtype', 'StringDtype', 'Timedelta', 'TimedeltaIndex', 'Timestamp', 'UInt16Dtype', 'UInt32Dtype', 'UInt64Dtype', 'UInt64Index', 'UInt8Dtype', '__all__', '__builtins__', '__cached__', '__deprecated_num_index_names', '__dir__', '__doc__', '__docformat__', '__file__', '__getattr__', '__git_version__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_config', '_is_numpy_dev', '_libs', '_testing', '_typing', '_version', 'annotations', 'api', 'array', 'arrays', 'bdate_range', 'compat', 'concat', 'core', 
'crosstab', 'cut', 'date_range', 'describe_option', 'errors', 'eval', 'factorize', 'from_dummies', 'get_dummies', 'get_option', 'infer_freq', 'interval_range', 'io', 'isna', 'isnull', 'json_normalize', 'lreshape', 'melt', 'merge', 'merge_asof', 'merge_ordered', 'notna', 'notnull', 'offsets', 'option_context', 'options', 'pandas', 'period_range', 'pivot', 'pivot_table', 'plotting', 'qcut', 'read_clipboard', 'read_csv', 'read_excel', 'read_feather', 'read_fwf', 'read_gbq', 'read_hdf', 'read_html', 'read_json', 'read_orc', 'read_parquet', 'read_pickle', 'read_sas', 'read_spss', 'read_sql', 'read_sql_query', 'read_sql_table', 'read_stata', 'read_table', 'read_xml', 'reset_option', 'set_eng_float_format', 'set_option', 'show_versions', 'test', 'testing', 'timedelta_range', 'to_datetime', 'to_numeric', 'to_pickle', 'to_timedelta', 'tseries', 'unique', 'util', 'value_counts', 'wide_to_long']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's a lot of methods! Pandas is a very large project with over 2750 people contributing to the code! This brings me to my next point - there is nothing to stop you being one of those people. Collaborating with others on projects and contributing your time and skills can be immensely rewarding. Even as a beginner, many projects will have tasks that you will be able to complete. If you have the time and want to try it out, look for a project you are interested (probably a large project to begin with) and get in touch!&lt;/p&gt;

&lt;p&gt;So how do we use pandas for data analysis or numpy for some mathematical operations? What about all of those other modules?&lt;/p&gt;

&lt;p&gt;This is where the step by step tutorials end and the free learning begins. At this point you are now capable of finding, installing and using any number of online modules and projects. However, each of these modules has methods which do different things and expect different input from the developer. To learn how to use them you need to do two things - read the documentation, and experiment. Never be afraid to simply install a module and have a play around to see what it can do. &lt;/p&gt;

&lt;p&gt;From here you can choose to take your coding journey in any number of directions; want to study data science for ecology - no problem, guess wildlife populations in the future with machine learning - go for it! The only limit now is your imagination and the time you wish to devote to coding.&lt;/p&gt;

&lt;p&gt;If you would prefer to work on your own projects but would like to upload your code and store it in GitHub then follow &lt;a href="https://docs.github.com/en/get-started/using-git/about-git"&gt;this link&lt;/a&gt; for a guide of how to do it.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"I have run into many coders, photographers, writers, who don't think of themselves as makers. But, I submit that making is any time you use your point of view to make something from nothing" - &lt;em&gt;Adam Savage&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;GitHub Safari&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;To end the series, I am going to take a stroll through the GitHub repositories and highlight a few repositories that may be of interest in the land and wildlife field. If any of these spark your interest, install them with pip and try them out. Maybe you could even become one of their contributors!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;1. Numpy&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/numpy/numpy"&gt;GitHub Page&lt;/a&gt;&lt;br&gt;
&lt;a href="https://numpy.org/doc/"&gt;Official Documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is it?&lt;/p&gt;

&lt;p&gt;Numpy is a Python module which allows you to perform scientific computing and numeric operations in your project.&lt;/p&gt;

&lt;p&gt;Why is it interesting?&lt;/p&gt;

&lt;p&gt;Aside from providing methods for various types of scientific calculations, one of numpy's big draws is it allows us to create three dimensional arrays (lists). What this means is lists within lists which allow us to make data structures similar to spreadsheets which can be very useful when working with actual spreadsheet or comma separated value datasets.&lt;/p&gt;

&lt;p&gt;If you have an interest in scientific computing or just like the numpy project they are actively looking for contributors! Follow &lt;a href="https://numpy.org/contribute/"&gt;this link&lt;/a&gt; to offer your services for everything from writing code, administration and even graphic design.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Pandas&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/pandas-dev/pandas"&gt;GitHub Page&lt;/a&gt;&lt;br&gt;
&lt;a href="http://pandas.pydata.org/pandas-docs/stable/"&gt;Official Documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is it?&lt;/p&gt;

&lt;p&gt;Pandas is a powerful module for data analysis in Python. It allows us to work easily with large datasets with features for things like handling missing data, grouping and modifying data, and merging multiple data sets together. It requires numpy to work but as a result it works seamlessly with numpy's arrays.&lt;/p&gt;

&lt;p&gt;Why is it interesting?&lt;/p&gt;

&lt;p&gt;Pandas is an essential tool in data sciences and is used extensively in fields such as ecology. It is also used for processing data for use in machine learning / A.I. Pandas can be useful for anyone who wants to analyse any kind of dataset.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Matplotlib&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/matplotlib/matplotlib"&gt;GitHub Page&lt;/a&gt;&lt;br&gt;
&lt;a href="https://matplotlib.org/stable/users/index.html"&gt;Official Documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is it?&lt;/p&gt;

&lt;p&gt;Matplotlib is an extensive module for visualising data in Python. It allows for the creation and display of many types of static and animated graphs.&lt;/p&gt;

&lt;p&gt;Why is it interesting?&lt;/p&gt;

&lt;p&gt;Graphs can be useful for all manner of professions and projects as a way of conveying data quickly and easily. Instead of exporting your data to something like Excel or another graphing software, simply do it all in Python.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Tkinter Designer and Custom Tkinter&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/ParthJadhav/Tkinter-Designer"&gt;GitHub Page&lt;/a&gt; - Tkinter Designer&lt;br&gt;
&lt;a href="https://github.com/TomSchimansky/CustomTkinter/wiki"&gt;GitHub Page&lt;/a&gt; - Custom Tkinter&lt;/p&gt;

&lt;p&gt;What is it?&lt;/p&gt;

&lt;p&gt;Tkinter is a Python framework for creating graphical user interfaces (GUI) for your applications. If you want to make a project which has user input boxes, buttons, labels, drop-down menus etc. Tkinter can make that happen. Tkinter designer and Custom Tkinter are two modules which allow you to easily create your own GUI.&lt;/p&gt;

&lt;p&gt;Why is it interesting?&lt;/p&gt;

&lt;p&gt;A GUI can be a lot more enticing for a user to engage with over using a command line app. Tkinter Designer makes it possible to design your GUI using only drag and drop components (you still have to code functionality into those buttons and other stuff). If you want more granular control, Custom Tkinter allows you to code your own GUI from scratch which is not nearly as hard as it sounds.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;GeoPandas&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/geopandas/geopandas"&gt;GitHub Page&lt;/a&gt;&lt;br&gt;
&lt;a href="https://geopandas.org/en/latest/"&gt;Official Documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is it?&lt;/p&gt;

&lt;p&gt;GeoPandas enables the working of geospacial data in Python and also allows for the plotting of that data in a similar fashion to using GIS software.&lt;/p&gt;

&lt;p&gt;Why is it interesting?&lt;/p&gt;

&lt;p&gt;Similar to pandas, geopandas has its own special data structures for dealing with geospacial data such as coordinates and geometry data. This means you can get up and running much quicker and utilising geopandas suite of methods will allow you to manipulate and plot your data to your hearts content.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Google Maps API&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/googlemaps/google-maps-services-python"&gt;GitHub Page&lt;/a&gt;&lt;br&gt;
&lt;a href="https://developers.google.com/maps/get-started"&gt;Official Documentation&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What is it?&lt;/p&gt;

&lt;p&gt;Simply put, this is Google's official Maps API (Application Programming Interface). Think of it just like a module which provides pre-made methods which enable you to interact with Google Maps in your application. In order to use the API you do need to sign up for a Google account if you don't already have one and then generate an API key (a unique ID so Google knows who is using its servers).&lt;/p&gt;

&lt;p&gt;Why is it interesting?&lt;/p&gt;

&lt;p&gt;The API allows you to access all data found in Google Maps. That includes location lookup, directions, distance measurements, elevation data, and more. You can run a query through the API with as little as 4 lines of code, so why not give it a go?&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Well that's it. The end. &lt;/p&gt;

&lt;p&gt;If you have read all of the series, all the way to the end, you have my undying gratitude and thanks. If you only read some of it, then you still have my thanks and I hope you were able to take something away from it.&lt;/p&gt;

&lt;p&gt;Here is a quick recap of what we covered:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Variables - what they are and how to use them&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Data Types - what common kinds of data does Python support&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Data Structures - lists, tuples and dictionaries and how we can store multiple pieces of data in a single variable&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Flow Control - how we can use logic to let our code perform some decision making for us&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Loops - making our code work hard for us to perform repetitive tasks quickly and easily&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Functions - chunks of code we can write once and recall whenever we need them&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Error Handling - dealing with those tricky and unpredictable users&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Classes and Objects - creating blueprints for our objects and then generating objects from the blueprints in true OOP style&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Files and Modules - how we can create our own reusable modules for use in the future to save us a lot of time&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;GitHub and External Modules - how we can use code written by others in our projects and how we can get involved by contributing to those projects&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;My intention with this series was not to get you to a professional developer level (although with further study, why not?), more I wanted to introduce the world of coding to those who maybe never saw a need for it or who thought it was beyond their reach. &lt;/p&gt;

&lt;p&gt;If the series helped you at all, please consider telling a friend. Any comments and constructive feedback are always appreciated.&lt;/p&gt;

&lt;p&gt;Thank you.&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>coding</category>
      <category>python</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Part Nine: Python Files and Modules</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Sat, 10 Dec 2022 18:24:29 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-nine-python-files-and-modules-1m51</link>
      <guid>https://forem.com/simonchalder/part-nine-python-files-and-modules-1m51</guid>
      <description>&lt;p&gt;Welcome to part nine. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at the basics of importing and using modules in our code.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"But while you can always write 'spaghetti code' in a procedural language, object-oriented languages used poorly can add meatballs to your spaghetti." - &lt;em&gt;Andrew Hunt&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;Modules&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Simply put, a module is a Python file containing classes, methods, or functions we would like to use in our code.&lt;/p&gt;

&lt;p&gt;Why is that useful?&lt;/p&gt;

&lt;p&gt;If we have written projects using classes or functions which handle a particular thing such as displaying graphs, performing calculations, getting user input etc, we can save that code in its own Python file and keep it in our own code library for use in the future. Think back to &lt;a href="https://dev.to/simonchalder/part-six-functions-2bm8"&gt;article six&lt;/a&gt; where we made some basic calculator functions. They looked like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add(num1, num2):
    print(num1 + num2)

def sub(num1, num2):
    print(num1 - num2)

def div(num1, num2):
    print(num1 / num2)

def mul(num1, num2):
    print(num1 * num2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, perhaps we think we may write another project in the future which requires a calculator, instead of writing out all of our functions again we can save this code in its own module.&lt;/p&gt;

&lt;p&gt;We save this code in a new file as 'calc.py' and place it in the same folder as our new project file. We can name our modules anything we like as long as we remember to give it the '.py' extension at the end.&lt;/p&gt;

&lt;p&gt;We can now start our new project as normal. To import the module we first place the module file in the same folder as our new project file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;├── project_folder
│   ├── new_project.py
│   ├── calc.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we write the following at the beginning of the new project file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import calc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now to access our functions in our new project we simply use the &lt;code&gt;[modulename].[functionname]&lt;/code&gt;. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import calc

print(calc.add(14, 28))

# Output
42
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that for example, if we only needed access to the division method for our project we can import only what we need:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from calc import div
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, when we call a function this way, we omit the name of the module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add(14, 28)

# Output
42
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Classes in Modules&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Let's now place our calculator in its own class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class calculator:
    def add(num1, num2):
        return num1 + num2

    def sub(num1, num2):
        return num1 - num2

    def div(num1, num2):
        return num1 / num2

    def mul(num1, num2):
        return num1 * num2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To access the methods in our class, we need to include the class name in our method call so the syntax would be &lt;code&gt;[modulename].[classname].[methodname]&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import calc

print(calc.calculator.sub(29, 6))

# Output
3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Module Aliases&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Some module names can be quite long or complicated. To make things easier to read we can import a module under a different name or alias. Say we had named our calculator module 'calculator.py', we can give it an alias when importing it to make it easier to work with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import calculator as cal
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now whenever we need to refer to the calculator module, we simply use 'cal' instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(cal.add(12,8)

# Output
20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Module Attributes&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;As well as classes, methods and functions, modules can also be used to store variables and data structures:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# calc.py

num1 = 10
num2 = 18
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To access these variables we simply use &lt;code&gt;[modulename].[variable]&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# project.py

result = calc.num1 + calc.num2
print(result)

# Output
28
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lists, tuples and dictionaries can be accessed in the same manner:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# calc.py

my_list = [12, 33, 109, 45]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# project.py

print(calc.my_list[2])

# Output
109
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Viewing the contents of a module&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Python has a built in function called &lt;code&gt;dir()&lt;/code&gt; which allows us to view the contents of a module or object. This can be useful when we are unsure if a particular object or module contains the data we require. The &lt;code&gt;dir()&lt;/code&gt; function will return the contents as a list and so to see it we must either print to the screen or use the returned data in a function.&lt;/p&gt;

&lt;p&gt;Let's use our calc module to test this. We can add a couple of variables to our 'calc.py' file as well:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;num1 = 10
num2 = 18

def add(num1, num2):
        return num1 + num2

def sub(num1, num2):
    return num1 - num2

def div(num1, num2):
    return num1 / num2

def mul(num1, num2):
    return num1 * num2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now print the returned results of our &lt;code&gt;dir()&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(dir(calc))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We get the following output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'div', 'mul', 'num1', 'num2', 'sub']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we have is a list of everything available to our module. Ignore everything with '__' either side and we can see the names of our functions as well as our 2 variables there too.&lt;/p&gt;

&lt;p&gt;No great surprise right? I mean, we created the module so we know what's in it. However, where this becomes useful is when we deal with modules we did not create. This can be Python's built in modules and those written by other people.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Python's Built In Modules&lt;/strong&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"One man’s crappy software is another man’s full time job." - &lt;em&gt;Jessica Gaston&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Python ships with all manner of built in, handy modules. Here is &lt;a href="https://docs.python.org/3/py-modindex.html" rel="noopener noreferrer"&gt;a list&lt;/a&gt; if you would like to have a read through some of them.&lt;/p&gt;

&lt;p&gt;We will cover a couple of them here so you can see how to use them but I encourage you to read around and try out as many as you can. &lt;/p&gt;

&lt;p&gt;To begin let's look at the &lt;code&gt;math&lt;/code&gt; module (boooooo maths!). Now, maybe your saying to yourself 'but I hate maths, what would I want to use that for?'. Well, the answer is quite simply that it does all of the hard work for you so you don't need to be a maths genius to work with numbers. &lt;/p&gt;

&lt;p&gt;Firstly, go to the page linked above and scroll down to the 'math' module and click the link. What you will see is a list of all of the methods which are part of the 'math' module.&lt;/p&gt;

&lt;p&gt;Let's import the math module to get started:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import math
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simple enough. Scrolling down the methods page, I can see the &lt;code&gt;pow()&lt;/code&gt; method. This method accepts 2 arguments, the first is our number, and the second is the power we wish to raise our number to. To call the method we simply use &lt;code&gt;[modulename].[methodname]&lt;/code&gt;. So for example 3 to the power of 3 (3x3x3) is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = math.pow(3, 3)
print(result)

# Output
27
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next let's try the square root method - &lt;code&gt;sqrt()&lt;/code&gt;. Looking at the documentation, this method accepts a single argument and returns the square root of that argument:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = math.sqrt(64)
print(result)

# Output
8
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Other methods of note in the &lt;code&gt;math&lt;/code&gt; module are conversions for degree to radians and visa versa, trigonometric methods for calculating angles such as tree heights, and a method for returning pi for circumference and other circular calculations. &lt;/p&gt;

&lt;p&gt;We can see the other methods which form the math module by using our &lt;code&gt;dir()&lt;/code&gt; built in function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(dir(math))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We get the following list as output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 
'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Looking through the list we can see the 'pow' and 'sqrt' methods we used as well as all of the others.&lt;/p&gt;




&lt;p&gt;For our second example, we will take a look at the &lt;code&gt;random&lt;/code&gt; module. You may recall way back in my &lt;a href="https://dev.to/simonchalder/part-five-loops-4jpj"&gt;loops article&lt;/a&gt; that for the challenge, I generated some random numbers. Well, here is how we can do that.&lt;/p&gt;

&lt;p&gt;Again we begin by importing the random module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import random
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we look through the methods available in the random module we will see &lt;code&gt;randrange()&lt;/code&gt;. This method returns a random number between a set range. It accepts 2 arguments, the first is the lowest possible random number, the second is the highest. So for example if we want a random number between 1 and 100 we could do the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = random.randrange(1, 100)
print(result)

# Output
23
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, let's take a look at the random choice method - &lt;code&gt;choice()&lt;/code&gt;. This method accepts a single argument which can be a list or tuple. The method will then randomly select one of the list items and return it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_list = [1,22,57,86,12]

result = random.choice(my_list)
print(result)

# Output
57
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again let's take a look at this module with our &lt;code&gt;dir()&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(dir(random))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We get this list as an output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_ONE', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_index', '_inst', '_isfinite', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 
'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Hopefully this has started to demonstrate that many common things we may need for our projects are already contained in Python's built in modules which saves us the time of having to code this ourselves every time. By using our own modules, we can re-use our code in future projects to save us some time there too. In addition, we can now start to break up our code into separate files with each module having a particular purpose. We then simply import those files into our main project file to use their code. This has the advantage of making the code modular so that we know exactly where to look to work on a specific part of the application even if our project becomes very large overall.&lt;/p&gt;

&lt;p&gt;In the next and final article, I want to demonstrate how you can import other people's modules into your code from the internet as well as taking a look at some modules which are likely to be of use to the land based sector.&lt;/p&gt;

&lt;p&gt;As always, thank you for reading and I look forward to seeing you next time.&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>Part Eight: Classes and Objects</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Thu, 08 Dec 2022 15:35:18 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-eight-classes-and-objects-4806</link>
      <guid>https://forem.com/simonchalder/part-eight-classes-and-objects-4806</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"I used to be enamoured of object-oriented programming. I'm now finding myself leaning toward believing that it is a plot designed to destroy joy." — &lt;em&gt;Eric Allman&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Welcome to part eight. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at the basics of using classes and objects to make modular code which is easier to work with.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Classes, Objects, and this thing called 'Object Orientated Programming'&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;If you have been reading around the subject matter, or maybe just browsing coding sites online, you may have come across the term 'object orientated programming' being thrown around. So what is it and why should you care?&lt;/p&gt;

&lt;p&gt;Up to now we have been writing what might be termed 'procedural' or 'functional' code where the interpreter starts at the top and works down line by line in a single Python file. Now don't get me wrong, you can accomplish a lot with this style of coding, and many times this may be all we need to accomplish our goals. However, the downside of this kind of coding rears its head when our applications start to get bigger and more complex. Simple applications or 'scripts' as they are often referred to, tend to set out to accomplish a single task. But what if we want our application to do several things? Using procedural coding we would end up with 'monolithic code' which means just a single, giant file with hundreds or even thousands of lines of code. When our code files get too big they become difficult to keep track of and when we have problems it makes it much harder to determine where the problem is arising from. &lt;/p&gt;

&lt;p&gt;Into the breach steps object orientated programming (from here on out I will refer to it as 'OOP' as it takes a long time to type!). In OOP, as the name suggests, we use objects in our code. We will come onto what objects are and how to make them shortly. However, using objects and their associated classes (more on this in a little while), we can break our code down into more manageable chunks and make it all more modular.&lt;/p&gt;

&lt;p&gt;Classes and objects allow us to group together related variables and functions into specialist tools which we can use to accomplish a task. &lt;/p&gt;

&lt;p&gt;Let's say we decide to write an application which does the following things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Connect to the internet and navigate to a web page or database which hosts wildlife datasets&lt;/li&gt;
&lt;li&gt;Download the required dataset&lt;/li&gt;
&lt;li&gt;Open or read the data file&lt;/li&gt;
&lt;li&gt;Perform some calculations with the data&lt;/li&gt;
&lt;li&gt;Display the result in the form of a graph&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Writing this in a single file with all of the associated variables and functions required might make for a pretty large file which is then difficult to work with. However, we could use classes and objects to break this application down into its component parts to make it easier to work with. We could have a class that deals with connecting to the internet, another which deals with downloading a file, and so on. This means if there is an issue in the code we know exactly where to look for the problem.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Classes and Objects&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;There is no discussion about OOP unless we talk about the objects and classes themselves. What are they? What do they do? OOP requires some different thinking and can be hard to understand at first. Try to understand on a conceptual level what is happening first and worry about the syntax after. &lt;/p&gt;

&lt;p&gt;OK here goes. &lt;/p&gt;

&lt;p&gt;Imagine we want to create a paper form so that we can record details about a company vehicle. We want a standardised form so we pay a printing company to make up a pad full of the uncompleted forms we have designed. In coding terms, a class is like the pad of printed forms, it is a template from which we will make all of our objects. Every form has fields such as the name of the person completing the form, the date, vehicle registration, mileage etc. When we fill out all of the fields on the form and tear it off the pad we now have an object - a completed version of the paper form which contains unique information about that vehicle.&lt;/p&gt;

&lt;p&gt;Here is an example of the form (class):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_vehicle_form:
    make = 
    model = 
    mileage = 
    doors = 
    colour = 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we fill it in, we now have a a completed version of the form with all of its associated fields but this one also has values for the fields making it a unique copy based on the form template which looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;land_rover:
    make = land rover
    model = defender
    mileage = 88625
    doors = 5
    colour = green
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By doing this we have taken the form template (the class) and made an object from it which contains the details above. We could also make another object from the same class template:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pickup:
    make = Ford
    model = ranger
    mileage = 12688
    doors = 3
    colour = blue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have 2 objects created from the same class. The class always remains the way we have created it, it is the template all objects of that class will be cast from just like a mould or rubber stamp. We can go on to make any number of objects from a class. We can also have as many classes as we like for lots of different purposes.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Creating a Class&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Creating a class in Python is not that different from the example above. We simply use the keyword &lt;code&gt;class&lt;/code&gt; followed by the name of the class we want to make and then a ':'.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class my_first_class:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we move to the next line down and indent to write code inside the class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class my_first_class:
    # write code here
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So what goes inside our classes? Classes can have their own variables known predictably as 'class variables' or 'attributes', as well as their own functions known as 'methods'.&lt;/p&gt;

&lt;p&gt;Let's look at creating some attributes first. We will use our vehicle example from above. First, we create our class and then we add attributes in our indented code in the same way as we create a normal variable. Note that here we are giving the class predetermined attributes that will apply to all objects made from it, in other words all objects made from our vehicle class will be blue and have 5 doors. We will cover giving new objects their own attributes later on.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class vehicle:
    colour = "blue"
    doors = 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our class template is now ready to be used to create an object, so lets do that. &lt;/p&gt;

&lt;p&gt;To create an object from a class we name our object and then assign it to the class using &lt;code&gt;[object name] = [class name]&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_truck = vehicle
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have now created a new object named &lt;code&gt;my_truck&lt;/code&gt; from the &lt;code&gt;vehicle&lt;/code&gt; class.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Let's talk about inheritance&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Here is the whistle-stop explanation of inheritance, a subject which could be the topic of a series of articles itself.&lt;/p&gt;

&lt;p&gt;By 'inheritance' I'm not referring to that rich uncle you're hoping will leave his fortune to you. In coding, inheritance refers to the way that objects 'inherit' attributes and methods from their class template.&lt;/p&gt;

&lt;p&gt;Whichever attributes and methods are written in the class are passed down to an object when it is created. If those attributes have values assigned to them, the values are also passed down. Keep this concept in mind as we move forward.&lt;/p&gt;




&lt;p&gt;We have now created our object which we named &lt;code&gt;my_truck&lt;/code&gt; from the &lt;code&gt;vehicle&lt;/code&gt; class. Our object inherits all of the attributes its template class had so our object also has 'colour' and 'doors' attributes. Because our class had values assigned to those attributes, our newly created object will also have its &lt;code&gt;colour&lt;/code&gt; attribute set to a value of 'blue' and a &lt;code&gt;doors&lt;/code&gt; attribute of '5'. &lt;/p&gt;

&lt;p&gt;To access an attribute, we use the name of the object followed by a '.' and then the name of the attribute:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(my_truck.colour)

# Output
'blue'

print(my_truck.doors)

# Output
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that if our class attributes have values we can also access them directly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(vehicle.colour)

# Output
'blue'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can create classes with pre-assigned values to act as a kind of reference but most of the time this is not what we want (more on this later). In the above example, every object we create from the 'vehicle' class will be the same - it will have a colour set to 'blue' and doors set to '5'. What if our next vehicle is red and has 3 doors? &lt;/p&gt;

&lt;p&gt;What we need is a way to pass data to an object as we are creating it so the object is unique and not a simple clone of the class template.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;'self' and &lt;code&gt;__init__()&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;No, those aren't typos in the title. They are concepts we need to understand in order to work with classes and objects effectively. At this point I'm not going to lie, this may require reading through a few times and probably using some other sources to understand. So buckle up kids, here we go!&lt;/p&gt;

&lt;p&gt;Let's tackle &lt;code&gt;__init__()&lt;/code&gt; first. When we want to create an object that is unique, we need a way to give it unique values for its attributes at the time of its creation. To do this we use what is known as a 'constructor'. In Python &lt;code&gt;__init__()&lt;/code&gt; is the constructor and is simply a function which runs when an object is created. Don't be put off by those weird '__' lines either side of the name, this is just how Python recognises what it does. Just like the functions we have already come across, it accepts arguments. Those arguments are then used to give values to the object's attributes. &lt;/p&gt;

&lt;p&gt;With me so far?&lt;/p&gt;

&lt;p&gt;OK, this brings us to 'self'. Consider the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_name = "Harry"

class my_class:
   my_name = "Helen"

my_object = my_class
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we have an object &lt;code&gt;my_object&lt;/code&gt; which is created from the &lt;code&gt;my_class&lt;/code&gt; class and as such inherits its attributes. We also have an unrelated variable &lt;code&gt;my_name&lt;/code&gt;. This means in this code we have 3 variables named &lt;code&gt;my_name&lt;/code&gt;. One is the standard variable, another is in the class attribute, and another in the object's attribute. As you can imagine this gets confusing and when we try to access &lt;code&gt;my_name&lt;/code&gt;, Python is not sure which of the 3 possible versions we are referring to. To solve this we use 'self' to indicate we are referring to the attribute in the object and not the class or some other variable with the same name.&lt;/p&gt;

&lt;p&gt;Let's put this all together to try and demonstrate this a little better. First let's create our class using a constructor like we discussed above. We can also name a couple of attributes. Note that we can leave the attribute values blank to create empty attributes we can then fill with a constructor.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class my_class:
   def __init__():
       name = 
       age = 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now need to give our constructor some arguments which will be used to assign values to the attributes when our object is created. If we simply put 2 arguments in the brackets of &lt;code&gt;__init__()&lt;/code&gt;, Python will not know if we wish to change the value of the object's attribute or some other with the same name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class my_class:
   def __init__(name, age):
       name = name
       age = age
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Therefore we must use 'self' to indicate we are dealing with the created object and not another part of the code. For this purpose, 'self' must always be the first argument we give to our constructor, even if no other arguments are given. Let's now add 'self.' before the attribute names. In this manner, 'self' is basically a place holder for the name of the object, whatever that might be when we create it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class my_class:
   def __init__(self, name, age):
       self.name = name
       self.age = age
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we come to create our object we now pass our arguments but we ignore 'self', we do not need to pass a value for that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_object = my_class("Jack", 34)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our object &lt;code&gt;my_object&lt;/code&gt; has now been created from the &lt;code&gt;my_class&lt;/code&gt; template and it has been assigned the name attribute equal to 'Jack' and an age attribute equal to '34'.&lt;/p&gt;

&lt;p&gt;At this point, you may have a headache and be questioning why you decided to try this coding nonsense to begin with. It can be difficult to understand at first, but the best way to gain an understanding is to practice examples of creating classes and objects, so let's do that now.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;A Practice Example&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Here is an example to help reinforce the OOP principles we have covered so far.&lt;/p&gt;

&lt;p&gt;Let's create a new class called 'mammal'. Inside the class, we define our constructor and give it the argument 'self':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class mammal:
    def __init__(self):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's choose some attributes for our mammals:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class mammal:
    def __init__(self, colour, diet, habitat, offspring):
        self.colour = colour
        self.diet = diet
        self.habitat = habitat
        self.offspring = offspring
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have our class set up let's make some objects from the class. Each argument is used to assign a value to the relevant attribute. When we create the fox object, the first argument we pass - 'red-brown' is assigned to fox.colour, 'carnivore' is assigned to fox.diet and so on. Remember in the class template, 'self' is just a placeholder for the names of the objects we will create:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fox = mammal('red-brown', 'carnivore', 'farmland', 2)

rabbit = mammal('grey-brown', 'herbivore', grassland', 10)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now have 2 unique objects created from the &lt;code&gt;mammal&lt;/code&gt; class which each have their own values for their attributes. Let's test it to make sure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(fox.colour)

# Output
'red-brown'

print(rabbit.diet)
'herbivore'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the visual learners amongst us, here is a visual example to try to show things more clearly.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fappx74t7m4f7wap58e2i.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fappx74t7m4f7wap58e2i.jpg" alt="mammal" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The whole 'self' thing can take a bit of getting used to but hopefully you are beginning to see how we create classes and then objects from those classes.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Methods&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;A method is simply a function which belongs to a class. Class methods are inherited by any object that is made from them just like attributes. To create a method we write it just like a normal function except indented in the class. Here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class say_something:
    def speak_word(word):
        print(word + "!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To call a class method we use the following syntax - &lt;code&gt;[class/object].[method]()&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;So to call our method from the example above we would use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;speak = say_something

speak.speak_word("Hello")

# Output
'Hello!'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Methods, just like normal functions, accept arguments. In the example above we pass the argument 'word' when calling the method.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Class Methods vs Object Methods&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Methods can be called both from the original class and from objects made from that class. For example we can create the following class and object from the class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class greeting:
    def __init__(self, greeting):
        self.greeting = greeting

    def say_greeting(self):
        print(self.greeting)

my_object = greeting("Hello!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now call 2 versions of the &lt;code&gt;say_greeting()&lt;/code&gt; method - 1 from the class and 1 from the method. Remember class methods can be called directly but are also inherited by all objects made from that class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;greeting.say_greeting()

# Output
'' # the greeting class has no pre-coded value for the 'greeting' attribute

my_object.say_greeting()

# Output
'Hello!'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So why is this important? We can use classes in different ways. We can use them in the normal fashion as we have seen above, as templates from which to create objects. However, we can also use 'static classes' to create a kind of reference or toolkit.&lt;/p&gt;

&lt;p&gt;Static classes are not used to create objects and as such do not pass on inherited attributes or methods. &lt;/p&gt;

&lt;p&gt;So what's the point of them?&lt;/p&gt;

&lt;p&gt;Well, remember the calculator application we made in the &lt;a href="https://dev.to/simonchalder/part-six-functions-2bm8"&gt;function article&lt;/a&gt;? We could make a class which holds our calculation methods and then simply call them when required.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class calculator:
    def add(num1, num2):
        return num1 + num2

    def sub(num1, num2):
        return num1 - num2

    def div(num1, num2):
        return num1 / num2

    def mul(num1, num2):
        return num1 * num2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Effectively what we have done here is to make our own built in function like &lt;code&gt;print()&lt;/code&gt;, or &lt;code&gt;float()&lt;/code&gt;, which we can use any time we need it. We do not need to create an object from the &lt;code&gt;calculator&lt;/code&gt; class in order to access its methods. However, we must ensure we use the name of the class when calling it e.g. &lt;code&gt;calculator.add()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result = calculator.add(23, 5)
print(result)

# Output
28
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In addition, we can save this class in its own Python file to be imported and used in any future projects which might require it. I will cover how to do this in a future article.&lt;/p&gt;

&lt;p&gt;As you have probably figured out, there is a lot to learn with classes and objects. The good news is if you can understand the basics, you can do an incredible amount with that level of knowledge. Remember you don't need to know everything and you don't need to be at the standard of a professional developer to write great applications.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;I know your head is probably hurting at this point but the best way to understand this stuff is through practice. I'm going to set a challenge to test your use of classes and objects. Hopefully nothing too intense. Take your time and think it through. Unlike other challenges, I will place one possible solution after the challenge in this article so that if you get completely stuck you can go through it step by step. However, I strongly encourage you to try and work it out yourself first.&lt;/p&gt;

&lt;p&gt;Let's write an application to put some of this into practice. We will write code that will take input about the details of a piece of land, perform some analysis and then output some (hopefully) useful data.&lt;/p&gt;

&lt;p&gt;Here is what the code must do:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a class for a piece of farmland called 'farmland'&lt;/li&gt;
&lt;li&gt;Inside your new class create some attributes with short but appropriate names for:

&lt;ul&gt;
&lt;li&gt;Total area&lt;/li&gt;
&lt;li&gt;Unharvested cereal headland&lt;/li&gt;
&lt;li&gt;Winter bird food&lt;/li&gt;
&lt;li&gt;Flower rich field margins&lt;/li&gt;
&lt;li&gt;Winter stubble&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Define 4 class methods to calculate each payment type. Each method should accept the size in hectares of that land type and the current payment rate from the Countryside Stewardship scheme. Current rates can be found &lt;a href="https://www.gov.uk/government/publications/countryside-stewardship-revenue-payment-rates-from-1-january-2022/countryside-stewardship-payment-rates-for-revenue-options-from-1-january-2022" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Create an object from your class and pass as arguments the total area of the land (hectares) as well as the size of any areas of cereal headland, winter bird food etc. You can simply enter these values when you create the object or get them through user input, your choice.&lt;/li&gt;
&lt;li&gt;Calculate the relevant totals and print out the results for that piece of land.&lt;/li&gt;
&lt;li&gt;BONUS - make the application run on a loop so that multiple pieces of land can be analysed until the user decides they have done enough.&lt;/li&gt;
&lt;li&gt;BONUS - make another class based on another land type such as wetland, woodland etc and incorporate this into your application.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Here is one possible solution to the challenge above. Remember, there are usually several different ways of tackling problems in programming. If your answer is different, but it works, then well done!&lt;/p&gt;

&lt;p&gt;We begin by creating the farmland class, defining the constructor, and setting attributes. It is certainly valid to create an argument for each payment rate, but I have combined them into a single argument which will be a list. The benefit of this is if I want to change the rates in the future they are all together rather than spread out amongst the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class farmland:
        def __init__(self, total_area, cereal, birds, margins, stubble, rates):
            self.total_area = total_area
            self.cereal = cereal
            self.birds = birds
            self.margins = margins
            self.stubble = stubble
            self.rates = rates
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we define class methods for each payment type. Each method calculates the total of the relevant payment rate multiplied by the area of that land type. Remember I have used a list for the rates, hence rates[0], rates[1] etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def cereal_headland_calc(self):
            return self.rates[0] * self.cereal

        def winter_bird_food_calc(self):
            return self.rates[1] * self.birds

        def flower_rich_margins_calc(self):
            return self.rates[2] * self.margins

        def winter_stubble_calc(self):
            return self.rates[3] * self.stubble
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also remember to include 'self' as an argument here as we will be calling this method from the object and not the class. Next, we create another method to display the results. Each of the above calculation methods is called and the result stored in a variable which is then printed to the screen as a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def show_results(self):
            cereal_calc = self.cereal_headland_calc()
            bird_calc = self.winter_bird_food_calc()
            margins_calc = self.flower_rich_margins_calc()
            stubble_calc = self.winter_stubble_calc()

            print("Results for Farmland Analysis:\n")
            print("Total Area: " + str(self.total_area))
            print("Potential Unharvested Cereal Headland Payment    - £" + str(cereal_calc))
            print("Potential Winter Bird Food Payment               - £" + str(bird_calc))
            print("Potential Flower Rich Field Margin Payment       - £" + str(margins_calc))
            print("Potential Winter Stubble Payment                 - £" + str(stubble_calc))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are now done with our class. Outside of our class, we can now create a function to get data from the user:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_input():
        area_input = float(input("Enter Total Area (ha): "))
        cereals_input = float(input("Enter Unharvested Cereal Headland Area (ha): "))
        birds_input = float(input("Enter Winter Bird Food Area (ha): "))
        margins_input = float(input("Enter Flower Rich Field Margin Area (ha): "))
        stubble_input = float(input("Enter Overwinter Stubble Are (ha): "))
        return area_input, cereals_input, birds_input, margins_input, stubble_input
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before we call our &lt;code&gt;get_input()&lt;/code&gt; function, we need to set the rates for the potential payments:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cs_farm_rates = [640, 640, 628, 493]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To get our user input, we call &lt;code&gt;get_input()&lt;/code&gt; and assign the returned values to some variables:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;area_input, cereals_input, birds_input, margins_input, stubble_input = get_input()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now create an object from our class we can call the &lt;code&gt;show_results()&lt;/code&gt; method from that object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new_land = farmland(area_input, cereals_input, birds_input, margins_input, stubble_input, cs_farm_rates)

new_land.show_results()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Up to now the full application looks like this. Make a note of the indentation to ensure the correct code is included or excluded from our class and function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class farmland:
        def __init__(self, total_area, cereal, birds, margins, stubble, rates):
            self.total_area = total_area
            self.cereal = cereal
            self.birds = birds
            self.margins = margins
            self.stubble = stubble
            self.rates = rates

        def cereal_headland_calc(self):
            return self.rates[0] * self.cereal

        def winter_bird_food_calc(self):
            return self.rates[1] * self.birds

        def flower_rich_margins_calc(self):
            return self.rates[2] * self.margins

        def winter_stubble_calc(self):
            return self.rates[3] * self.stubble

        def show_results(self):
            cereal_calc = self.cereal_headland_calc()
            bird_calc = self.winter_bird_food_calc()
            margins_calc = self.flower_rich_margins_calc()
            stubble_calc = self.winter_stubble_calc()

            print("Results for Farmland Analysis:\n")
            print("Total Area: " + str(self.total_area))
            print("Potential Unharvested Cereal Headland Payment    - £" + str(cereal_calc))
            print("Potential Winter Bird Food Payment               - £" + str(bird_calc))
            print("Potential Flower Rich Field Margin Payment       - £" + str(margins_calc))
            print("Potential Winter Stubble Payment                 - £" + str(stubble_calc))

    def get_input():
        area_input = float(input("Enter Total Area (ha): "))
        cereals_input = float(input("Enter Unharvested Cereal Headland Area (ha): "))
        birds_input = float(input("Enter Winter Bird Food Area (ha): "))
        margins_input = float(input("Enter Flower Rich Field Margin Area (ha): "))
        stubble_input = float(input("Enter Overwinter Stubble Are (ha): "))
        return area_input, cereals_input, birds_input, margins_input, stubble_input

    cs_farm_rates = [640, 640, 628, 493]

    area_input, cereals_input, birds_input, margins_input, stubble_input = get_input()

    new_land = farmland(area_input, cereals_input, birds_input, margins_input, stubble_input, cs_farm_rates)

    new_land.show_results()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now run this code and enter some values we are presented with output similar to the image below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8afassvkefe8zxsxjmkq.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8afassvkefe8zxsxjmkq.jpg" alt="Output" width="499" height="207"&gt;&lt;/a&gt;&lt;br&gt;
That last result shows we need to round the total to 2 decimal places. We can do this in the following way by altering our code with the &lt;code&gt;round()&lt;/code&gt; built in function. The number after the comma represents the number of decimal places:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def cereal_headland_calc(self):
        return round(self.rates[0] * self.cereal, 2)

    def winter_bird_food_calc(self):
        return round(self.rates[1] * self.birds, 2)

    def flower_rich_margins_calc(self):
        return round(self.rates[2] * self.margins, 2)

    def winter_stubble_calc(self):
        return round(self.rates[3] * self.stubble, 2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The final part of the challenge is to make the app loop until the user decides to quit. To do this, we simply indent the entire code inside of a while loop with some flow control at the end. The finished application should now look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;run = True
while run == True:    
    class farmland:
        def __init__(self, total_area, cereal, birds, margins, stubble, rates):
            self.total_area = total_area
            self.cereal = cereal
            self.birds = birds
            self.margins = margins
            self.stubble = stubble
            self.rates = rates

        def cereal_headland_calc(self):
            return round(self.rates[0] * self.cereal, 2)

        def winter_bird_food_calc(self):
            return round(self.rates[1] * self.birds, 2)

        def flower_rich_margins_calc(self):
            return round(self.rates[2] * self.margins, 2)

        def winter_stubble_calc(self):
            return round(self.rates[3] * self.stubble, 2)

        def show_results(self):
            cereal_calc = self.cereal_headland_calc()
            bird_calc = self.winter_bird_food_calc()
            margins_calc = self.flower_rich_margins_calc()
            stubble_calc = self.winter_stubble_calc()

            print("Results for Farmland Analysis:\n")
            print("Total Area: " + str(self.total_area))
            print("Potential Unharvested Cereal Headland Payment    - £" + str(cereal_calc))
            print("Potential Winter Bird Food Payment               - £" + str(bird_calc))
            print("Potential Flower Rich Field Margin Payment       - £" + str(margins_calc))
            print("Potential Winter Stubble Payment                 - £" + str(stubble_calc))

    def get_input():
        area_input = float(input("Enter Total Area (ha): "))
        cereals_input = float(input("Enter Unharvested Cereal Headland Area (ha): "))
        birds_input = float(input("Enter Winter Bird Food Area (ha): "))
        margins_input = float(input("Enter Flower Rich Field Margin Area (ha): "))
        stubble_input = float(input("Enter Overwinter Stubble Are (ha): "))
        return area_input, cereals_input, birds_input, margins_input, stubble_input

    cs_farm_rates = [640, 640, 628, 493]

    area_input, cereals_input, birds_input, margins_input, stubble_input = get_input()

    new_land = farmland(area_input, cereals_input, birds_input, margins_input, stubble_input, cs_farm_rates)

    new_land.show_results()

    run_again = input("Perform another analysis 'y' or 'n'?")
    if run_again.upper() == 'Y':
        run = True
    else:
        run = False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to add analysis for a different land type, you simply need to create another class with appropriate methods and rates. This is one of the advantages of OOP, we can create modular classes and objects where all of the related code is together in one place.&lt;/p&gt;

&lt;p&gt;I hope all of this made sense and you are starting to see things more clearly. If not, please use as many online sources as you can until you find one which explains it best. If you are lucky enough to know someone with experience of OOP you may benefit from them going through it with you. As I have mentioned, these can be tricky concepts to grasp at first and they can also be difficult to express in a way which is easy for the learner. Hang in there though and practice as much as you need. Take your time and consult as many sources and learning materials as necessary.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;That was a tough one to get through but we are nearly a the end of the series. In the next article I am going to talk about importing your own (and other people's) files and modules into your projects.&lt;/p&gt;

&lt;p&gt;Thank you as always for reading and I look forward to any constructive feedback you may have on this article or the series as a whole. Keep practising and I look forward to seeing you next time.&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>frontend</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Part Seven: Error Handling</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Mon, 05 Dec 2022 09:00:00 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-seven-error-handling-1j07</link>
      <guid>https://forem.com/simonchalder/part-seven-error-handling-1j07</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"There are two ways to write error-free programs; only the third one works." - &lt;em&gt;Alan Perlis&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Welcome to part seven. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at writing code once but being able to use it as many times as we like without writing it out every time, but first let's take a look at the solution for the challenge set in part six.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Solution to part six's challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Here are a couple ways this could be accomplished. If your method was different but still worked - congratulations! If you struggled, have a look at the examples below and if you have time, have another go at it.&lt;/p&gt;

&lt;p&gt;Example 1 - putting the whole thing inside a while loop&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;run = True

while run == True:

    def add(num1, num2):
        result = num1 + num2
        print(result)

    def sub(num1, num2):
        result = num1 - num2
        print(result)

    def div(num1, num2):
        result = num1 / num2
        print(result)

    def mul(num1, num2):
        result = num1 * num2
        print(result)

    choice = input("Enter 'add', 'sub', 'div' or 'mul'")

    number1 = input("Enter first number: ")
    number1 = int(number1)
    number2 = input("Enter second number: ")
    number2 = int(number2)

    if choice == 'add':    
        add(number1, number2)
    elif choice == 'sub':
        sub(number1, number2)
    elif choice == 'div':
        div(number1, number2)
    elif choice == 'mul':
        mul(number1, number2)
    else:
        print("Choice not recognised, please run application again")

    run_again = input("Perform another calculation? ")
    if run_again == 'y' or run_again == 'Y':
        run = True
    else:
        run = False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example 2 - using recursion&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def calculator():
    def add(num1, num2):
        result = num1 + num2
        print(result)

    def sub(num1, num2):
        result = num1 - num2
        print(result)

    def div(num1, num2):
        result = num1 / num2
        print(result)

    def mul(num1, num2):
        result = num1 * num2
        print(result)

    choice = input("Enter 'add', 'sub', 'div' or 'mul'")

    number1 = input("Enter first number: ")
    number1 = int(number1)
    number2 = input("Enter second number: ")
    number2 = int(number2)

    if choice == 'add':    
        add(number1, number2)
    elif choice == 'sub':
        sub(number1, number2)
    elif choice == 'div':
        div(number1, number2)
    elif choice == 'mul':
        mul(number1, number2)
    else:
        print("Choice not recognised, please run application again")

    run_again = input("Perform another calculation? ")
    if run_again == 'y' or run_again == 'Y':
        calculator()
    else:
        pass

calculator()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;blockquote&gt;
&lt;p&gt;"Any fool can use a computer. Many do." - &lt;em&gt;Ted Nelson&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;User Input Problems&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;All being well, you should have an application which can take input from a user, perform simple calculations, and run multiple times as needed.&lt;/p&gt;

&lt;p&gt;Perhaps you came across this issue when you were writing your code but if not consider the following situation. Where we ask for user input, for example, the first and second numbers, what if the user didn't enter a number but a string instead? What if they inputted a boolean value or maybe no value at all and simply pressed enter.&lt;/p&gt;

&lt;p&gt;Unfortunately, whether accidentally or intentionally, users won't always do what we think they will. Therefore, we need to try and anticipate potential pitfalls and put code in place to avoid crashing our applications.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Error Handling - reducing the chance of an incorrect input&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Let's work through our calculator example and see where we can anticipate users causing problems. For the remainder of this article I will be referring to my first example but feel free to adapt this to your own solutions.&lt;/p&gt;

&lt;p&gt;We will start at line number 21 in my example where we ask the user to choose a type of calculation to perform:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;choice = input("Enter 'add', 'sub', 'div' or 'mul'")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will work well as long as the user types exactly what we have asked for. However, a user wanting to perform addition may type 'Add', 'ADD', or make a typo such as 'ads'. This input is stored in a variable which is compared in an if / else statement starting on line 28. Anything other than 'add' here will throw an error.&lt;/p&gt;

&lt;p&gt;So how can we overcome this? The first possible step would be change what we are asking for. Instead of asking the user to type a string of 3 characters which they may misspell, we could simply ask for a number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;choice = input("Enter 1 to add, 2 to subtract, 3 to divide or 4 to multiply")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the user only has to enter one character which reduced the chances of errors. &lt;/p&gt;

&lt;p&gt;We could also use a letter instead of a number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;choice = input("Enter 'A' to add, 'S' to subtract, 'D' to divide or 'M' to multiply")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, this raises the issue of did the user use upper or lower case? To solve this, we can convert any letter the user gives us to upper case, before the if statement looks at it, to ensure no matter what is typed it will be upper case. To do this we use a built in Python function - &lt;code&gt;upper()&lt;/code&gt;. The upper method is technically a method and not a function but we will get into methods in another article. Here's how we use it, we can call upper.() on a variable by using it after a '.' at the end of the variable name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;string_variable = "goose"
string_variable.upper()
print(string_variable)

# Output
'GOOSE'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in our calculator example, we simply add &lt;code&gt;upper()&lt;/code&gt; to the end of our choice input line to convert the input to upper case:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;choice = input("Enter 'A' to add, 'S' to subtract, 'D' to divide or 'M' to multiply").upper()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Converting Data Types&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Moving on to line 23, we already have some error handling in place here. Because the input() function returns a string it means that we cannot take number inputs from it directly. When the user gives the input - 23 as a number, the input function records this as the string "23". This is no good for performing calculations as we can only do this with integers or floats.&lt;/p&gt;

&lt;p&gt;To solve this, we used the &lt;code&gt;int()&lt;/code&gt; function to convert the string from the user input into an actual integer we can use in calculations:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number1 = input("Enter first number: ")
number1 = int(number1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, what if the user wanted to calculate decimal numbers? Inputting a decimal number currently will throw a value error as we are trying to convert a float to an integer. &lt;/p&gt;

&lt;p&gt;While we could examine the float to try and see if it contains a '.' and then use flow control to then convert to an integer or a float depending on the result.....it's just easier to convert everything to a float and work solely in decimal numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number1 = input("Enter first number: ")
number1 = float(number1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now decimal numbers can be handled without issue and any integers can still be used but will just be displayed with '.0' after them.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Using Functions and Flow Control&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The final method for error handling I am going to look at here is using functions and flow control to account for anything the user throws at you which you did not account for.&lt;/p&gt;

&lt;p&gt;In our example, we have some flow control which checks the &lt;code&gt;choice&lt;/code&gt; variable against some criteria to determine the calculation type to be performed. We check for predetermined answers but if anything else is found, we exit the flow control and proceed to ask if the user wishes to run the application again. In addition, regardless of what the user enters, it is not validated until after they have entered their 2 numbers.&lt;/p&gt;

&lt;p&gt;One way of solving this is to re-write our code into functions and then call them as needed. This will require us to re-arrange or 're-factor' our code so take your time and go through line by line if you have any issues understanding what is happening. &lt;/p&gt;

&lt;p&gt;First we take our code which asks the user for 2 numbers and make it into a function which returns those numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_nums():
        number1 = input("Enter first number: ")
        number1 = int(number1)
        number2 = input("Enter second number: ")
        number2 = int(number2)
        return number1, number2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we take the flow control code which assesses which calculation we wish to perform and make another function which can call itself if we cannot validate the user's input. We can cut and paste our user input line from above and put it at the start of this function. Now the calculation choice input is validated before we get the user's numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def calc_choice():
        choice = input("Enter 'A' to add, 'S' to subtract, 'D' to divide or 'M' to multiply").upper()
        if choice == 'A':
            num1, num2 = get_nums()    
            add(num1, num2)
        elif choice == 'S':
            num1, num2 = get_nums()    
            sub(num1, num2)
        elif choice == 'D':
            num1, num2 = get_nums()    
            div(num1, num2)
        elif choice == 'M':
            num1, num2 = get_nums()    
            mul(num1, num2)
        else:
            print("Choice not recognised, please run application again")
            calc_choice()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, now that all of our functions have been defined, we need to call our &lt;code&gt;calc_choice()&lt;/code&gt; function to get things started. We must remember that a function must be defined before it can be called so we must make sure our code is arranged appropriately.&lt;/p&gt;

&lt;p&gt;Here is what this would look like all together. We will go through it to explain how it works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;run = True

while run == True:

    def add(num1, num2):
        result = num1 + num2
        print(result)

    def sub(num1, num2):
        result = num1 - num2
        print(result)

    def div(num1, num2):
        result = num1 / num2
        print(result)

    def mul(num1, num2):
        result = num1 * num2
        print(result)

    def get_nums():
        number1 = input("Enter first number: ")
        number1 = float(number1)
        number2 = input("Enter second number: ")
        number2 = float(number2)
        return number1, number2

    def calc_choice():
        choice = input("Enter 'A' to add, 'S' to subtract, 'D' to divide or 'M' to multiply").upper()
        if choice == 'A':
            num1, num2 = get_nums()    
            add(num1, num2)
        elif choice == 'S':
            num1, num2 = get_nums()    
            sub(num1, num2)
        elif choice == 'D':
            num1, num2 = get_nums()    
            div(num1, num2)
        elif choice == 'M':
            num1, num2 = get_nums()    
            mul(num1, num2)
        else:
            print("Choice not recognised, please run application again")
            calc_choice()

    calc_choice()

    run_again = input("Perform another calculation? ")
    if run_again == 'y' or run_again == 'Y':
        run = True
    else:
        run = False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is how this application will run:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Line 1: The variable &lt;code&gt;run&lt;/code&gt; is created and set to True&lt;/li&gt;
&lt;li&gt;Line 3: A while loop looks at &lt;code&gt;run&lt;/code&gt; and if it is True runs its indented code&lt;/li&gt;
&lt;li&gt;Lines 5-44: 5 functions are defined&lt;/li&gt;
&lt;li&gt;Line 46: The &lt;code&gt;calc_choice()&lt;/code&gt; function is called and runs its code&lt;/li&gt;
&lt;li&gt;The user is asked for input 'A','S','D' or 'M' and this is stored in the variable &lt;code&gt;choice&lt;/code&gt; after being converted to upper case&lt;/li&gt;
&lt;li&gt;Flow control looks at the value of &lt;code&gt;choice&lt;/code&gt; and if it matches one of the set conditions &lt;code&gt;get_nums()&lt;/code&gt; is called and the returned values stored in variables called &lt;code&gt;num1&lt;/code&gt; and &lt;code&gt;num2&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;The appropriate calculation function is called using &lt;code&gt;num1&lt;/code&gt; and &lt;code&gt;num2&lt;/code&gt; as arguments&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;choice&lt;/code&gt; does not meet any of the set conditions, the else statement runs and calls &lt;code&gt;calc_choice()&lt;/code&gt; again. Go back to step 5&lt;/li&gt;
&lt;li&gt;If a calculation has been performed we move to line 48 where the user is asked if they want to go again&lt;/li&gt;
&lt;li&gt;Flow control compares the user's answer to step 9. If the answer is 'y' or 'Y' then the while loop from step 2 runs again. If the answer is ANYTHING else, &lt;code&gt;run&lt;/code&gt; from step 1 is set to False and the loop will not run again causing the application to exit&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;&lt;strong&gt;Final Tweaks&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The only other thing we could do with this code is to shorten the final bit of flow control using the &lt;code&gt;upper()&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;run_again = input("Perform another calculation? ").upper()
    if run_again == 'Y':
        run = True
    else:
        run = False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All together, this would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;run = True

while run == True:

    def add(num1, num2):
        result = num1 + num2
        print(result)

    def sub(num1, num2):
        result = num1 - num2
        print(result)

    def div(num1, num2):
        result = num1 / num2
        print(result)

    def mul(num1, num2):
        result = num1 * num2
        print(result)

    def get_nums():
        number1 = input("Enter first number: ")
        number1 = float(number1)
        number2 = input("Enter second number: ")
        number2 = float(number2)
        return number1, number2

    def calc_choice():
        choice = input("Enter 'A' to add, 'S' to subtract, 'D' to divide or 'M' to multiply").upper()
        if choice == 'A':
            num1, num2 = get_nums()    
            add(num1, num2)
        elif choice == 'S':
            num1, num2 = get_nums()    
            sub(num1, num2)
        elif choice == 'D':
            num1, num2 = get_nums()    
            div(num1, num2)
        elif choice == 'M':
            num1, num2 = get_nums()    
            mul(num1, num2)
        else:
            print("Choice not recognised, please run application again")
            calc_choice()

    calc_choice()

    run_again = input("Perform another calculation? ").upper()
    if run_again == 'Y':
        run = True
    else:
        run = False
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the second example I gave at the start we could also solve this with recursion:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def calc_app():

    def add(num1, num2):
        result = num1 + num2
        print(result)

    def sub(num1, num2):
        result = num1 - num2
        print(result)

    def div(num1, num2):
        result = num1 / num2
        print(result)

    def mul(num1, num2):
        result = num1 * num2
        print(result)

    def get_nums():
        number1 = input("Enter first number: ")
        number1 = float(number1)
        number2 = input("Enter second number: ")
        number2 = float(number2)
        return number1, number2

    def calc_choice():
        choice = input("Enter 'A' to add, 'S' to subtract, 'D' to divide or 'M' to multiply").upper()
        if choice == 'A':
            num1, num2 = get_nums()    
            add(num1, num2)
        elif choice == 'S':
            num1, num2 = get_nums()    
            sub(num1, num2)
        elif choice == 'D':
            num1, num2 = get_nums()    
            div(num1, num2)
        elif choice == 'M':
            num1, num2 = get_nums()    
            mul(num1, num2)
        else:
            print("Choice not recognised, please run application again")
            calc_choice()

    calc_choice()

    run_again = input("Perform another calculation? ").upper()
    if run_again == 'Y':
        calc_app()
    else:
        pass

calc_app()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again, take your time here and go through line by line until you have a good handle on what is happening. If your solution to the challenge was significantly different from mine, try applying error handling to your own code to see how you can avoid users catching you out.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The challenge this time is not really a challenge. We have come a long way since part one, you have learned data types, data structures, flow control, loops, functions, and now error handling. My hope is that you are now starting to think of your own projects and maybe you have already started some of them. For now I would like you to consolidate your coding knowledge and go back through everything you have learned. If you have the time, try a simple project or 2 to help you understand all of the concepts and how they work together. If you have come this far, you have gone from crawl to walk and now you are starting to run. Remember what sparked your interest in coding to begin with and keep it fun.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;We have covered some difficult subject matter so far. Some of these concepts can be difficult for a beginner to understand (I know some are definitely hard to explain). I hope if you have struggled or are struggling, that you persist and stick with it as the rewards will be numerous when you have that 'eureka!' moment.&lt;/p&gt;

&lt;p&gt;What I am building towards with this series is to get you to a point where you can write modular, object orientated code which will enable you to contribute to your field and community or write useful software for your daily life. You won't be a professional developer by the end, but you don't need to be, you work in land based industry not Facebook. &lt;/p&gt;

&lt;p&gt;The concepts get harder as we go from here and I will do my best to explain them as clearly as I can. However, if it doesn't click right away do not be disheartened, it's perfectly normal. Keep referring to as many sources as needed until you find the one that explains it in the right terms, we all learn differently.&lt;/p&gt;

&lt;p&gt;The next article will look at classes and objects, and then on to some object orientated programming principles. This marks the end of what could be considered 'beginner' coding so if you have got this far give yourself a well deserved pat on the back!&lt;/p&gt;

&lt;p&gt;Thank you for reading, constructive criticism is always welcome. I look forward to seeing you next time.&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>Part Six: Functions</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Sat, 03 Dec 2022 15:27:34 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-six-functions-2bm8</link>
      <guid>https://forem.com/simonchalder/part-six-functions-2bm8</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"Measuring programming progress by lines of code is like measuring aircraft building progress by weight." - &lt;em&gt;Bill Gates&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Welcome to part six. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at writing code once but being able to use it as many times as we like without writing it out every time, but first let's take a look at the solution for the challenge set in part five.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Solution to part five's challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;In this challenge we have a list of integers named &lt;code&gt;code_list&lt;/code&gt; and we need to loop through this list comparing each list item to the secret code.&lt;/p&gt;

&lt;p&gt;To do this we need to use a loop which will iterate through each item and then a nested if / else statement to do the comparing. We could use a while loop as we know we have 1000 codes to loop through but an easier way is to use a for loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for code in code_list:
    if code == safe_code:
        print("Safe cracked, code was: ")
        print(code)
    else:
        pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also print our output on a single line by converting our integer into a string:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for code in code_list:
    if code == safe_code:
        print("Safe cracked, code was: " + str(code))
    else:
        pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What is &lt;code&gt;str()&lt;/code&gt;? Well, I'm glad you asked, it's a method and those are the topic of this article.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Functions&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Up to this point I have mentioned functions in passing, but what are they exactly?&lt;/p&gt;

&lt;p&gt;I want to introduce you to an important concept in programming which is &lt;strong&gt;D.R.Y.&lt;/strong&gt; or &lt;strong&gt;'Don't Repeat Yourself'&lt;/strong&gt;. What this means is that we should never be writing the same piece of code over and over in our applications - it looks messy, makes the code more difficult to read, and uses more memory when the application is ran. However, there are many times when we need our code to do something multiple times. Consider the following example which does not adhere to the DRY principle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print("Instructions for fitting wall shelves")
print("Fit 8mm drill bit into drill")
print("Drill 4 x 25mm holes in wall")
print("Insert rawl plugs into holes")
print("open bag of screws")
print("Screw item to wall")

print("Instructions for fitting medicine cabinet")
print("Fit 8mm drill bit into drill")
print("Drill 4 x 25mm holes in wall")
print("Insert rawl plugs into holes")
print("open bag of screws")
print("Screw item to wall")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;OK, it's a bit of a silly example, but we can see our application needs to use 2 sets of almost identical instructions. To improve on this we can use a function to make most of the instructions repeatable and then simply recall our function each time we need it rather than typing out everything multiple times. Python comes with some built in functions and we have used some of them already. However, we will be writing our own functions from scratch to improve our code.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Creating a Function&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;First we must define (create) our function. We define a function with the following syntax:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fllssm8lxta8ft1tgecaz.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fllssm8lxta8ft1tgecaz.jpg" alt="function syntax" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this case we will name it 'instructions' so as to give an idea of what it will do. Once we have defined our function and given it a name, we then move to the next line down, indent, and then write the code we want to run when the function is called.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def instructions():
    print("Fit 8mm drill bit into drill")
    print("Drill 4 x 25mm holes in wall")
    print("Insert rawl plugs into holes")
    print("open bag of screws")
    print("Screw item to wall")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now instead of typing all of the instructions for each task we simply use (call) our function. To call a function, simply write its name followed by brackets '()':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print("Instructions for fitting wall shelves")
instructions()

print("Instructions for fitting medicine cabinet")
instructions()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each time we call our &lt;code&gt;instructions()&lt;/code&gt;, it runs the code we wrote inside the function when we defined it. So now writing this...&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;instructions()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;...is the equivalent of writing this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print("Fit 8mm drill bit into drill")
print("Drill 4 x 25mm holes in wall")
print("Insert rawl plugs into holes")
print("open bag of screws")
print("Screw item to wall")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Giving our functions some input&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Using functions allows us to avoid writing the same lines of code over and over which helps us adhere to DRY coding. However, functions can be even more useful when we give them some input so work with.&lt;/p&gt;

&lt;p&gt;Consider the following function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_name():
    print("Sarah")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function will print the name 'Sarah' any time we call it. This means we don't have to repeat this line in our code, but it also means we can only print 'Sarah' using this function. What if we wanted to print another name? We could make a new function for each name and call them individually when we need them. Or, we can create a function which accepts input known as 'arguments' so that the function knows which name we want it to print.&lt;/p&gt;

&lt;p&gt;What is an argument?&lt;/p&gt;

&lt;p&gt;By argument, I don't mean shouting at your code (we've all been there though, no judgement). In coding terms, arguments are pieces of input which we feed into a function to allow it to process that input and provide a useful output. Going back to our name printing function, we can modify it to accept an argument which we will call 'name'. We place our arguments in between the brackets when we define our function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_name(name):
    print(name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our name argument is effectively like a variable, a placeholder with a title for whatever we assign to it. The function above will now expect a single input (also known as a 'parameter' - don't get bogged down by the terminology) called 'name' when we call it. Whatever we pass to the function will be stored under 'name' inside the function. In this case the function will print whatever we pass to it as 'name'. Arguments work with any data type.&lt;/p&gt;

&lt;p&gt;To pass an argument to a function, we add it between the brackets when calling it. To print a name we could pass a string or the contents of a variable:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Define the function
def print_name(name):
    print(name)

# Call the function
print_name("Floyd")

# Output
'Floyd'

# Using the same function as above

my_name = "Tina"

print_name(my_name)

# Output
'Tina'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; - once we have defined a function with an argument, it will expect an argument to be given when we call it. Calling the function with no argument will result in an error but there are some ways around this which I will discuss near the end of this article.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;A quick note about scope&lt;/strong&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"A good programmer is someone who always looks both ways before crossing a one-way street." - &lt;em&gt;Doug Linder&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Functions can do all manner of things instead of printing names to the screen. That includes creating and modifying variables and data structures. These operate in the same way as normal except that they exist only inside the function when it is called. Consider the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_func():
    name = "Joe"
    print(name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When this function is called it creates a variable called 'name'. This variable exists only for the time this function is running and the indented code is not accessible outside of the function. For example, if we tried to run the following we would receive an error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_func():
    name = "Joe"
    print(name)

print(name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is because our print statement is trying to access a variable called 'name', however, the error is telling us that there is no variable of that name defined as it exists only inside the function.&lt;/p&gt;

&lt;p&gt;This is an example of something called scope and it comes into play a lot in more advanced topics. However, for now all we need to know is that scope is a one way street. We can go with the flow but we cannot go against it. &lt;/p&gt;

&lt;p&gt;Scope is an important subject, particularly as your applications become more complex and ambitious. For more information on scope follow &lt;a href="https://www.askpython.com/python/variable-scopes-in-python" rel="noopener noreferrer"&gt;this link&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Passing more than one argument&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;As you may have guessed, functions can have more than a single argument. In fact, they can have any number of arguments but we must ensure we pass them the same number of inputs when we call them.&lt;/p&gt;

&lt;p&gt;Here is an example of a function which takes 2 arguments to join 2 strings - note the arguments are separated by a comma ',':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def full_name(first, last):
    print(first + " " + last)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when we call this function, we must ensure we pass 2 pieces of input:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;full_name("Bill", "Smith")

# Output
'Bill Smith'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that the order of the arguments matters here. Passing the arguments in a different order when calling the function would alter the output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;full_name("Smith", "Bill")

# Output
'Smith Bill'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Time for a practice example&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Let's make a simple calculator application using functions to reinforce how they work.&lt;/p&gt;

&lt;p&gt;We will define 4 separate function for addition, subtraction, division and multiplication which will each accept 2 numbers as arguments. Each function will then print the result of that operation between the 2 numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def add(num1, num2):
    print(num1 + num2)

def sub(num1, num2):
    print(num1 - num2)

def div(num1, num2):
    print(num1 / num2)

def mul(num1, num2):
    print(num1 * num2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's test out the addition function by calling it and passing any 2 numbers as arguments:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;add(43, 65)

# Output
108
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make sure your output performs as expected and play around with the other functions to test their outputs too. If you are mathematically inclined you could try creating some more complicated functions.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;It's time we talked about recursion&lt;/strong&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"To understand recursion, you must first understand recursion" - &lt;em&gt;old nerd joke&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Recursion, recursion, recursion, recursion... where to start? OK, enough bad jokes, recursion is where a function calls itself. Remember when we discussed loops and we looked at infinite loops - a loop with no way to break the cycle which will go on forever. Recursion can be kind of the same thing with functions. Consider the following function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_func(count):   
    if count &amp;gt; 0 :       
        print(count)
        my_func(count)

my_func(10)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Passing any argument greater than 0 would produce an infinite cycle of function calls as there is no way to break out of the loop and &lt;code&gt;my_func()&lt;/code&gt; will keep calling itself. &lt;/p&gt;

&lt;p&gt;Just like loops, we need a way to break the cycle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def my_func(count):   
    if count &amp;gt; 0 :       
        print(count)
        my_func(count -1)

my_func(10)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Recursion can be used as a tool for accomplishing some tasks, but unless you are confident it is the only way to go and you can create functions capable of  breaking the cycle, it is best avoided.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Arbitrary and Default Arguments&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;I want to touch briefly on how we address not knowing how many arguments our function will receive or when at least 1 of the function's arguments will be the same every time it is called.&lt;/p&gt;

&lt;p&gt;It is always best to plan our functions so that we know what they will receive as arguments each time. However, there may come a time when this is not possible. For example, with our name printing function, some people use middle names and some do not so our function as written above would not be able to deal with that.&lt;/p&gt;

&lt;p&gt;To overcome this we use what are known as 'arbitrary arguments' or &lt;code&gt;*args&lt;/code&gt; for short. When we define our function we tell it we do not know how many arguments to expect by writing a '*' before the argument name. For our name printing function, it would look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_name(*name):
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we use arbitrary arguments, the input given to our function is converted to a tuple (remember those?). We can then use the entire tuple, or slice it to get just the parts we want:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Using the entire tuple

def print_name(*name):
    print(name)

print_name("Billy", "Ray", "Smith")

# Output
('Billy', 'Ray', 'Smith')

# Slicing just what we want - the middle name

def print_name(*name):
    print(name[1])

print_name("Billy", "Ray", "Smith")

# Output
'Ray'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the case where a function will always accept the same argument we can use what are called 'default arguments'. Again going back to our name printing function, perhaps the last name of everyone will be the same. In this case rather than type out the last name as an argument each time we can set it as a default when defining the function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_name(first, middle, last="Smith"):
    print(first + " " + middle + " " + last)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we now call our function we only need to pass 2 arguments instead of 3 as the last name is already set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print_name("Billy", "Ray")

# Output
Billy Ray Smith
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Uh oh! A friend of the family has arrived who has a different last name to everyone else, what do we do? Easy! We can override the default by simply passing a new argument when calling the function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_name(first, middle, last="Smith"):
    print(first + " " + middle + " " + last)

print_name("Peggy", "Sue", "Jones")

# Output
Peggy Sue Jones
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Python's built in functions&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;As I mentioned at the start of the article, Python comes with some built in functions to handle common tasks for us. We have already used one of them a lot - the print() function. The print function, prints to the screen or terminal whatever we pass it as an argument in the brackets. Now that you know a little about functions, this should make a little more sense. Other built in functions work in a similar way - we call the function name and then pass arguments in the brackets. For an idea of how a built in function works, you can't beat the official Python documentation. Here are some examples of some other built in Python functions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;bin() - accepts an integer argument and returns it in binary&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;float() - accepts an integer or string and converts it to a float&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;int() - similar to float() but returns an integer&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;len() - returns the length (number of items) of a list or tuple&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Returning Values&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The final topic for this article is about functions returning values. So far we have been getting our functions to print their results to the screen as this is the simplest way to show they are working as expected. However, what if we wanted to actually use the output of a function for something else? Maybe we want to store the result in a variable to use later, or perhaps use it as the input for another function? To do this we use a new key word &lt;code&gt;return&lt;/code&gt;. Returning a value from a function changes its scope and makes it available to use outside of the function.&lt;/p&gt;

&lt;p&gt;We will stick to the name printing function for simplicity but now instead of printing a name we will return it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_name(name):
    return name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we call the function as before:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print_name("John")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nothing happened right? What is happening behind the scenes is that the function ran and sent back the value of &lt;code&gt;name&lt;/code&gt; but nobody was listening - we had not written any code to do anything with it. Let's store that returned value in a variable so we can see it and use it. To do that we assign the value of a variable to our function call:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_name = print_name("John")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now whatever is returned by calling this function is stored in our variable. You can verify it has worked by printing your variable if you like.&lt;/p&gt;

&lt;p&gt;We can return multiple values from a function and store them in multiple variables. Values will be assigned to the variables in the same order they are returned:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def print_name(first, last):
    return first, last

first_name, last_name = print_name("John", "Smith")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;OK, let's take it up a notch. We will define one function which will get a name from a user, and another which will take the returned value and print the name to the screen. First we define our 2 functions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_name():
    name = input("What is your name? ")
    return name

def print_name(name):
    print(name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we simply need to call the print function to make it all work. We can now store the value of &lt;code&gt;get_name&lt;/code&gt; in a variable and then pass it on to &lt;code&gt;print_name&lt;/code&gt; as an argument:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_name = get_name()

print_name(my_name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now get any name from a user and then print whatever that name happens to be. We can also shorten this code even further by removing &lt;code&gt;my_name&lt;/code&gt; all together. Remember that calling a function will run that code at that point. Well, that includes inside the argument brackets of a function call! We can achieve the same result as before by instead using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print_name(get_name())
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When print name is called it looks for an argument to be passed. Instead of a variable, there is a function call instead. It will run that function there and then and whatever result is returned that is what it will use as the argument.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;For this challenge, all I want you to do is use what you have learned about flow control, loops and functions to improve on the calculator application we made earlier. In its current state, the calculator is pre-written and uses only arguments we have written into the code. It also completes only one calculation before exiting.&lt;/p&gt;

&lt;p&gt;To improve the calculator application have a go at the following tasks:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Take input from the user about what kind of calculation they would like to do&lt;/li&gt;
&lt;li&gt;Ask for 2 numbers from the user and then pass these as arguments to the relevant function. Hint - you may need to convert the data you receive to something more usable using a built in Python function.&lt;/li&gt;
&lt;li&gt;Display the results and then ask the user if they would like to perform another calculation&lt;/li&gt;
&lt;li&gt;If the user answers 'yes', loop back to the start of the application and run it again. If they answer 'no', exit the application.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By now I hope that you are starting to get a better feel for the concepts that we have covered so far and that you are using other resources online to improve your learning. As such I will not be walking you through this challenge's answer step by step but rather I will simply post 1 possible solution you could use. Remember, there is nearly always multiple ways of accomplishing your goal in coding. Good luck, I know you can do it!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;We have now covered 3 important concepts in programming - flow control, loops, and functions. By using these building blocks you can now write some pretty sophisticated applications. There is another level though, something which many modern programmers aspire to do efficiently and elegantly - Object Orientated Programming (OOP).&lt;/p&gt;

&lt;p&gt;I will be getting into the basics of OOP in a future article. However, before that I want to discuss some other topics which I hope will help you learn and overcome some difficulties. The next article will be discussing the subject of error handling. So, please keep your solution to the calculator challenge as we will be using it to demonstrate error handling next time.&lt;/p&gt;

&lt;p&gt;Once again, thank you for reading, constructive feedback is always appreciated and I look forward to seeing you next time!&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>sql</category>
      <category>discuss</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Part Five: Loops</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Sun, 27 Nov 2022 20:37:16 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-five-loops-4jpj</link>
      <guid>https://forem.com/simonchalder/part-five-loops-4jpj</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"The definition of insanity is doing the same thing over and over and expecting different results." - &lt;em&gt;Albert Einstein&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Welcome to part five. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at some of the ways we can design code which will make repetitive tasks quick and easy, but first let's take a look at the solution for the challenge set in part four.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Solution to part four's challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;To solve the challenge, we need to use what we have learned about flow control, taking user input, and concatenation. The first task is to collect 3 pieces of information from the user - a first name, last name and their age. We will store each of these pieces of data in it's own variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;first_name = input("First Name: ")
last_name = input("Last Name: ")
age = input("Age: ")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now have first name, last name and age stored in separate variables. We are now asked to make some decisions based on their age to determine if they are old enough to do a certain activity. Our decision making will need something to compare the user's age to, so we make a fourth variable and assign the minimum age for our activity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;min_age = 18
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, to make our decision, we use an 'if / else' statement using our variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if age &amp;gt;= min_age:
    print("Hello " + first_name + " " + last_name + ", you are " 
    age + " and therefore old enough to vote in the UK where the 
    minimum age is " + min_age)
else:
    print("Sorry " + first_name + " " + last_name + ", you are " 
    age + " and therefore NOT old enough to vote in the UK where 
    the minimum age is " + min_age)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Loops&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Loops as their name implies, are a way of running a piece of code again and again without the need to type everything out each time. For example, say I have a list of 100 animals and I want to print out each animal on the list. I could do it with a print statement for each item on the list:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_list = ["badger", "woodcock", "pheasant", "pinemarten"...etc..]
print(my_list[0])
print(my_list[1])
print(my_list[2])
# ... and so on.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, that's over 100 lines of code just to print a list! Apart from being time consuming to write, this would not be very fast or efficient from a software writing perspective.&lt;/p&gt;

&lt;p&gt;A better way is to use a loop. Loops are a standard thing across programming languages and Python sports the usual two forms - 'while loops' and 'for loops'. &lt;/p&gt;




&lt;p&gt;&lt;strong&gt;While Loops&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Let's look at while loops first. Going back to our list printing problem, we can use a while loop to do the hard work for us. While loops work like this:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Do something for as long as a condition is valid&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Let's put this into practice so it makes more sense. Our while loop will keep doing something (in this case printing out list items) until our condition is no longer met. &lt;/p&gt;

&lt;p&gt;Here is the loop we will use. Have a read line by line and see if you can get a feel for how this is going to work. If not, don't worry I am going to go through each part below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 0
while i &amp;lt; 100:
    print(my_list[i])
    i += 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When this code runs the following happens:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The loop checks the value of &lt;code&gt;i&lt;/code&gt; which starts at '0' and compares it to our condition which is &lt;code&gt;i&lt;/code&gt; must be less than 100. As long as we meet this condition (i = 0 so is less than 100) we run the indented code below.&lt;/li&gt;
&lt;li&gt;The code then prints the item in my_list with an index equal to &lt;code&gt;i&lt;/code&gt; which is 0, so we print the first list item.&lt;/li&gt;
&lt;li&gt;We then add 1 to &lt;code&gt;i&lt;/code&gt; so it changes from 0 to 1.&lt;/li&gt;
&lt;li&gt;The loop then runs again but this time &lt;code&gt;i&lt;/code&gt; is equal to 1 which is still less than 100 so we run the indented code again.&lt;/li&gt;
&lt;li&gt;The code prints the list item with the index of &lt;code&gt;i&lt;/code&gt; which is now 1 and so we print the 2nd list item&lt;/li&gt;
&lt;li&gt;We add 1 to &lt;code&gt;i&lt;/code&gt; making it now 2&lt;/li&gt;
&lt;li&gt;The loop runs again with &lt;code&gt;i&lt;/code&gt; now equal to 2 and so on....&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's go through it line by line.&lt;/p&gt;

&lt;p&gt;Our variable &lt;code&gt;i&lt;/code&gt; is effectively a counter to keep track of how many times we have run through the loop. You will often see this variable named 'i' or 'x' but in theory you can use any name you like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 0 # remember the first index of a list is 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;OK, we have set our index variable to 0. Now we form our loop and set our condition to keep running through the loop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while i &amp;lt; 100:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Starting with the keyword &lt;code&gt;while&lt;/code&gt; we say that while the value of &lt;code&gt;i&lt;/code&gt; is less than 100 - keep running the indented code below the loop statement. Instead of 'i &amp;lt; 100' we could also use our other operators such as greater than (&amp;gt;), equal to (==), greater than or equal to (&amp;gt;=) etc.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    print(my_list[i])
    i += 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this  example our code prints a list item with an index equal to &lt;code&gt;i&lt;/code&gt; which starts at 0. After the print statement, we increase &lt;code&gt;i&lt;/code&gt; by adding 1 to it. The code &lt;code&gt;+=&lt;/code&gt; is a short hand for adding 1 to something and is short for &lt;code&gt;i = i + 1&lt;/code&gt;. We could increase our variable by any amount such as &lt;code&gt;i +=5&lt;/code&gt; to increase in increments of 5. We can also count backwards using &lt;code&gt;-=&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The whole thing would look like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_list = ["badger", "woodcock", "pheasant", "pinemarten"...etc..]

i = 0
while i &amp;lt; 100:
    print(my_list[i])
    i += 1

# Output
'badger'
'woodcock'
'pheasant'
'pinemarten'
# etc etc.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While loops are excellent for using where we must keep something going until a condition changes but there is a better way to loop through data structures such as lists and tuples - the 'for loop'.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;For Loops&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;A for loop will automatically loop through a string, list, tuple etc even if we do not know how many items it contains. Whereas using a while loop requires us to set a condition for how many times we want to run the loop, the for loop does this for us. For loops effectively work in the following way:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;For each item in this string/list/tuple etc - do something&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Let's go back to our animal list and take a look at using a for loop. Again, take a look at it first and see if you can see how it will work.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_list = ["badger", "woodcock", "pheasant", "pinemarten"...etc..]

for x in my_list:
    print(x)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A lot more compact isn't it? We do not need to create a counter variable or set the number of times to run through the loop, the for loop handles this for us. Each time the loop runs the following is happening:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The for loop automatically starts with the first list item at index 0 and stores the value of this item ('badger') in the variable &lt;code&gt;x&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The loop then prints the value of &lt;code&gt;x&lt;/code&gt; which is 'badger' to the screen.&lt;/li&gt;
&lt;li&gt;The for loop now automatically moves to the next list item at index 1 and stores this item value in &lt;code&gt;x&lt;/code&gt; ('woodcock').&lt;/li&gt;
&lt;li&gt;The loop prints the value of &lt;code&gt;x&lt;/code&gt; which is now 'woodcock' and so on....&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let's run through line by line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for x in my_list:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We start with the keyword &lt;code&gt;for&lt;/code&gt;. Next &lt;code&gt;x&lt;/code&gt; is the name of a variable that exists only inside of the for loop. This variable could equally have been named &lt;code&gt;animal&lt;/code&gt;, &lt;code&gt;species&lt;/code&gt; or anything else we wanted. Each time the loop runs, the value of the item in my_list is stored in &lt;code&gt;x&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(x)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For each time through the loop, it prints the value of &lt;code&gt;x&lt;/code&gt; which will be equal to the next list item each time through the list.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;A Note on infinite loops and the 'Do While' loop&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Whenever we use loops in our code we must be careful not to use loops which cannot satisfy the condition we set and therefore cannot end because we have not given a way to meet the condition. Consider the following loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;i = 0
while i &amp;lt; 10:
    print(i)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This looks harmless enough right? Look closer, how will this loop end? We have not included a way to increment our index variable and so it's value will always be 0. Our condition states that while i is less than 10 the loop will continue to run. What we have created here is an 'infinite loop'. While in this example, we can simply press CTRL + C to exit out of the application, in more complex applications this can lead to all available memory being used up and the device will crash or freeze. Always make sure your loop is able to reach it's exit condition.&lt;/p&gt;

&lt;p&gt;If you go on to code using other programming languages, you may come across another type of loop which is not natively part of Python - the do while loop. The do while loop is the same as a while loop with one key difference. A normal while loop has a condition which is checked at the start of the loop meaning if that condition is not met, the loop will never run. However, the do while loop puts this condition check at the end of the loop meaning the code contained in the loop will always run at least once. &lt;/p&gt;

&lt;p&gt;Do while loops can be approximated with workarounds in Python but for now I wouldn't worry about them, I just wanted to make you aware of what they are and how they work.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Exercise&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Let's try putting loops into practice to show what they can do. Remember when we discussed slicing strings? I gave the example of writing code which would sort through livestock ID codes to give us data about the kinds of animals we had and their numbers. Well, let's write it now! Not only will this task use what we have learned using loops but it also introduces a new concept - using if / else statements with loops.&lt;/p&gt;

&lt;p&gt;In this task you should imagine yourself in the role of a farmer or livestock manager taking inventory of their stock. You are presented with a list of ID tags which give each animal a letter determining their type and a unique ID number. The letters tell us the animal type as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;'B' - Bull&lt;/li&gt;
&lt;li&gt;'H' - Heffer&lt;/li&gt;
&lt;li&gt;'P' - Boar&lt;/li&gt;
&lt;li&gt;'S' - Sow&lt;/li&gt;
&lt;li&gt;'R' - Ram&lt;/li&gt;
&lt;li&gt;'E' - Ewe&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We need to write code which will analyse the list and determine 3 things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;How many animals of all types do we have?&lt;/li&gt;
&lt;li&gt;How many of each type do we have?&lt;/li&gt;
&lt;li&gt;How many total males and females of all species do we have?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In order to get you started I am going to generate the list for you. Delete any unwanted code from your IDE or create a new file. Copy and paste the following into the file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import random

letters = ['B', 'H', 'P', 'S', 'R', 'Y']
stock = []
i = 0
while  i &amp;lt; 1000:
    letter = random.choice(letters)
    num = random.randint(100, 1000)
    stock.append(letter + str(num))
    i +=1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Don't worry how this works for now, just know that it is using a loop to generate a random list of codes for us to work with. As such, each time you run the code the list will be different so just bear that in mind if you get differing results.&lt;/p&gt;

&lt;p&gt;So, we have our livestock list. Now we need to sort through it to determine what we have. If you feel confident then by all means have a go at solving this yourself using what you have learned. If not, or you want to follow along instead then read on.&lt;/p&gt;

&lt;p&gt;Let's look at the problem first. We have a list of ID tags, each tag is comprised of a letter and a series of numbers. The numbers don't concern us, we are more interested in the letters as they denote the type of animal with that ID. We need to therefore loop through the list looking at the letter at the start of each item and then count the number of times each letter appears. To start, let's create variables to count each animal type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bull = 0
heffer = 0
boar = 0
sow = 0
ram = 0
ewe = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we will create our loop which will do all of the hard work for us. This list is relatively small but in real life scenarios we could be dealing with lists with tens or even hundreds of thousands of items and making loops is a big time saver!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for count in stock:
    if count[0] == 'B':
        bull += 1
    elif count[0] == 'H':
        heffer += 1
    elif count[0] == 'P':
        boar += 1
    elif count[0] == 'S':
        sow += 1
    elif count[0] == 'R':
        ram += 1
    elif count[0] == 'E':
        ewe +=1
    else:
        pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Yikes, that's a big loop! Well, yes but break it down line by line to simplify it. We have created a for loop and every time this loop runs we ask the question - is the first character (count[0]) of each list item equal to 'B'. If the answer is yes then we add 1 to our &lt;code&gt;bull&lt;/code&gt; total. If the answer is no, we move to the next else / if statement which asks - is the first character of the list item equal to 'H'? Again, if the answer is yes we add 1 to our &lt;code&gt;heffer&lt;/code&gt; total. If not we move onto the next option and so on. If we get all of the way through the loop and the list item has not been equal to any of our questions we reach the else statement and we move onto the next item.&lt;/p&gt;

&lt;p&gt;Now to check if this has worked, we can print out our totals.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print("Total Bulls")
print(bull)
print("Total Heffers")
print(heffer)
print("Total Boars")
print(boar)
print("Total Sows")
print(sow)
print("Total Rams")
print(ram)
print("Total Ewes")
print(ewe)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All being well, you should see something like this in your output (remember each list is randomised so the numbers will be different):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw299m5ho2ny5n6lttl9x.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw299m5ho2ny5n6lttl9x.jpg" alt="Stock" width="135" height="210"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For an additional challenge, see if you can find a way to print the above figures in a more concise way like 'Total Bulls: 176'.&lt;/p&gt;

&lt;p&gt;Next let's get a grand total for the number of animals we have and print this out below. This one should be easy for you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;grand_total = bull + heffer + boar + sow + ram + ewe
print("Total animals")
print(grand_total)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;HINT: Maybe there is a way to create a line break between our species totals and grand total?&lt;/p&gt;

&lt;p&gt;Finally, lets get our total males / females. Again, this should be fairly straight forward.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;males = bull + boar + ram
females = heffer + sow + ewe
print("Total Males")
print(males)
print("Total Females")
print(females)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If your code is right you should have something like this in your output at the end (I included line breaks in mine):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6kc6wo1si52x37xmcjnw.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6kc6wo1si52x37xmcjnw.jpg" alt="Stock totals" width="168" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Umm, guys... we just wrote an application which could have been useful for something and accomplished a real world task! We are past the boring beginner stuff and we are now moving into subjects which enable us to deliver real solutions to real problems. With a bit of practice and imagination, we can begin to write software which can actually help ourselves and others. Getting totals for each animal type is just the tip of the iceberg of what we can do with out data now we have the ability to loop through it (known in programming as 'iterating'). If you are so inclined then I would encourage you to continue to add functionality to our code in order to manipulate the data in new and interesting ways.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The challenge for next time is to write some code which will crack the code for an imaginary safe - all perfectly legal I assure you! I will give you a list of possible codes. All you need to do is run through the list until you find the right code to unlock the safe.&lt;/p&gt;

&lt;p&gt;Here is the list of codes to get you started:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import random

code_list = []
i = 0
while i &amp;lt; 1000:
    num = random.randint(10000, 99999)
    code_list.append(num)
    i += 1
safe_code = random.choice(code_list)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code generates a list of 1000 possible codes to try and also picks one of those codes to be the actual safe code so you can't see it and cheat!&lt;/p&gt;

&lt;p&gt;So, in summary write code which does the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Combs through the list of possible codes and tries to match each one to the actual safe code.&lt;/li&gt;
&lt;li&gt;If the code matches print out something like "Safe cracked - code was 35865".&lt;/li&gt;
&lt;li&gt;If the safe code does not match then the code should do nothing and run the loop again until the correct code is found.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;&lt;strong&gt;A Note On Password Cracking In Real Life&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Although we are just having fun here, this is basically a simplified version of brute force password cracking used by hackers to get into accounts. If you would like to check if the password you use for your online accounts is likely to be on a list of compromised passwords then you can create a similar application to the challenge above which does just that. Simply Google 'RockYou password list' and download this list or any other similar list. You can then import the file using Python (I will leave that up to you to discover how) and then check your password string against those in the list. If it's on the list, it's probably time to change it!&lt;/p&gt;

&lt;p&gt;In case you are wondering, these password lists are used by penetration testers to make sure software and websites are secure and they are perfectly legal to download and use. However, if you are unsure then please check all applicable laws where you live before downloading anything.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Now we have begun to add flow control and loops to our code, I hope you are now starting to see that we are able to create useful applications that actually do something! I also hope that this is beginning to open your eyes to the possibilities when making your own projects. Take some time to become familiar with flow control and loops and then start to think of how they could be utilised in your own work or study to create applications to save time and work. In the next article, I will be discussing functions and methods which enable us to create re-usable chunks of code which can be inserted into our applications without needing to re-write everything each time.&lt;/p&gt;

&lt;p&gt;Thank you for reading. As always, constructive feedback is always appreciated and I look forward to seeing you in part six.&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>help</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Part Four: Flow Control</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Wed, 23 Nov 2022 17:46:45 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-four-flow-control-460o</link>
      <guid>https://forem.com/simonchalder/part-four-flow-control-460o</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"Nothing is more difficult, and therefore more precious, than to be able to decide." - &lt;em&gt;Napoleon Bonaparte&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Welcome to part four. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at some of the ways we can use logical states to allow our code to make decisions in Python, but first let's take a look at the solution for the challenges set in part three.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Solutions to part three's challenges&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Task 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a list and name it my_list
my_list = ["leaf", 98, False, "red kite", 4.68]
# Append your name as a string to the end of the list
my_list.append("Simon")
# Delete the 3rd item in your list
del my_list[2]
# Substitute the 1st and 2nd items in your list with different 
# items
my_list[0:2] = ["flower", 26]
# Delete the entire list
del my_list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Task 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a tuple and name it my_tuple
my_tuple = (1, 2, 3, 4, 5)
# Try to append, delete or change values in my_tuple and note any # errors or messages Python gives you
"TypeError: 'tuple' object does not support item assignment"
# Tuples cannot be changed once they are created!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Task 3&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#Create a dictionary and name it my_dict. In it, create the keys 
# "genus", "species", "habitat" and "diet" and give them some 
# appropriate values
my_dict = {'genus' : "Cervus", 'species' : "elaphus", 'habitat' : "woodland", 'diet' : "herbivore"}
# Add a new key "Lifespan" and give it an appropriate value
my_dict['Lifespan' : 20]
# Delete the genus key and value
del my_dict[genus]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Time for a new toy!&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Up to this point we have been using IDLE to run and test our code. IDLE comes bundled with Python and is a great way to test lines of code and to try things out. So far, we have been running our code one line at a time and seeing what will happen. As we move now into slightly more advanced topics, we will be writing multiple lines of code before running the whole thing. While IDLE is capable of doing this, I feel it is beneficial for the learner to see everything laid out in the proper format. In addition, setting out our code in the proper way is essential for making the code human readable and in some instances it is also necessary for Python to understand our code. To this end we are now going to use a new tool - the IDE or 'Integrated Development Environment'. The IDE will allow us to write multiple lines of code, save our code in a Python file and then run the file. Many IDEs also come with handy features such as syntax highlighting and auto-completion but more on those shortly. &lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Choosing an IDE&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;There are many IDEs out there which will allow you to write and run Python applications. Some are free, some you have to paid for (just use a free one!), but they all work in a similar way. Developers are fussy creatures and everyone has their individual preferences. In time you can experiment with several and choose the one you like best but for now I am going to give you a choice of two:&lt;/p&gt;

&lt;p&gt;First off, we have &lt;strong&gt;Visual Studio Code&lt;/strong&gt; by Microsoft. Visual Studio Code is a desktop application (they are working on an online version) which works with basically any programming language and has the ability the download plugins in order to make it look and run exactly how you want. To download VS Code follow &lt;a href="https://code.visualstudio.com/Download" rel="noopener noreferrer"&gt;this link&lt;/a&gt; to download and install from the official site. There are downloads for Windows, Mac and Linux and it is also available through many Linux package managers. After installing and opening VS Code you should be presented with something similar to the following image:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftgvavfxt7f1dizbippu0.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftgvavfxt7f1dizbippu0.jpg" alt="VS Code" width="800" height="494"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To begin, either click 'New File' on the welcome screen or open the 'File' menu in the top left and select 'New File'. A small dialog window should now open asking you to name your file. Whatever name you choose make sure the file has the extension '.py' at the end so VS Code knows it is a Python file. Make a note of where you save your file, it may be a good idea to create a new folder to keep your code files separate.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmg31lal3o0n6lp5w7r4r.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmg31lal3o0n6lp5w7r4r.jpg" alt="New File Popup" width="620" height="96"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once your new Python file is created you should be presented with a blank page and a flashing cursor all ready to go. &lt;/p&gt;

&lt;p&gt;Before we do anything look for the 'Extensions' icon on the left side of the window and click it or press &lt;code&gt;Ctrl + Shift + X&lt;/code&gt; to open the Extensions pane. In the search bar at the top of the pane type 'python' which should show all of the available Python plugins available. Near the top of the list should be a plugin named 'Python' with the subtitle 'IntelliSense (Pylance)' by Microsoft. Click the little blue 'Install' button to add this plugin to VS Code. This plugin is gives us features such as syntax highlighting and autocompletion. &lt;/p&gt;

&lt;p&gt;Some other optional plugins you can search for and install would be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Pylance&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Rust Syntax Highlighting&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The second IDE option I am going to suggest is &lt;a href="https://replit.com/" rel="noopener noreferrer"&gt;replit.com&lt;/a&gt;. Replit is an IDE for writing Python (and other languages) but it is entirely online based with nothing to download or install. Simply go to the link above and create a free account to get started. You will then be taken to the dashboard screen which will look something like the following:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvjls8m71oeqi4v3aump2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvjls8m71oeqi4v3aump2.jpg" alt="Replit" width="800" height="407"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click the '+ Create' button in the top left to get started and you will be greeted with 'Create a Repl' popup. Select 'Python' from the available templates and then give your project a name before clicking 'Create Repl'. You should then see a screen similar to the following:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fami9hvyw9mnweuitclr2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fami9hvyw9mnweuitclr2.jpg" alt="repl" width="800" height="405"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The screen is divided into two panes, our code writing pane on the left and the terminal or output on the right. On the left of the screen you will see some file names. Ignore all of the packager files, we won't be touching them. Instead note 'main.py', this is the current open file and the one we will using to write our code.&lt;/p&gt;

&lt;p&gt;Phew! IDEs are an entire topic in of themselves but we should hopefully be at a point where we can start coding in this new environment.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Taking it for a spin&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Let's try out our new IDE to get a feel for how it works. &lt;/p&gt;

&lt;p&gt;In your open Python file type the following using your own name. Press enter at the end of each line to start another:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name = "Simon"
print(name)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So...nothing happened, not yet anyway. In order to run our file we need to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In VS Code either locate the small forward arrow icon in the top right and click the button or press Ctrl + F5.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In Replit simply press the green 'Run' button at the top of the screen&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You should now see your name printed to the screen. In VS Code the terminal will appear at the bottom of the screen and with Replit it will be in the right side pane.&lt;/p&gt;




&lt;p&gt;So what exactly is happening when we press 'Run' in the IDE? Python is known as an 'interpreted language' which is a fancy way of saying it runs code line by line. Python comes bundled with an interpreter that allows Python files to be run on your device. When we run the file, the interpreter starts at line 1 and reads left to right. If no errors are found then that line is stored to memory or the code executed and the interpreter moves on the the next line. This process repeats until all lines of code have been ran and the programme will end. For this reason in long Python files the interpreter may get most of the way through the code, running as it goes, before finding an error near the end and failing. &lt;/p&gt;

&lt;p&gt;The other type of language available are the 'compiled languages' such as C, C++ and Java. Compiled languages use a separate piece of software known as a compiler to go through the entire file, converting everything into machine readable code before attempting to run the file. &lt;/p&gt;

&lt;p&gt;Generally speaking, interpreted languages such as Python tend to make it easier to create smaller scripts or applications and their development time is often quicker as you do not need to wait for a compiler to convert the whole file to run it. However, once compiled language files are compiled they are generally faster to run and are used in cases where speed is a key factor.&lt;/p&gt;

&lt;p&gt;For more information on interpreted vs compiled languages follow &lt;a href="https://www.freecodecamp.org/news/compiled-versus-interpreted-languages/" rel="noopener noreferrer"&gt;this link&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;A quick note on Python files&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Python files can also be ran outside of the IDE in a couple of different ways. &lt;/p&gt;

&lt;p&gt;Firstly, locate the folder where your Python file is stored in your device's file explorer. We can simply double click on them like any other executable file. However, what you may find with this is that a window appears on the screen and then immediately disappears. This is because our code has nothing to stop it running to the end and it is not waiting for anything to happen so it closes down. &lt;/p&gt;

&lt;p&gt;A better way, particularly if our file will produce output to the terminal is to actually open the file in our device's terminal. In windows click the Windows / Start Menu and type 'cmd' and hit enter. On Mac or Linux search for 'Terminal' and open. Navigate to the folder containing your Python file and type the following depending on your devices operating system:&lt;/p&gt;

&lt;p&gt;Windows - &lt;code&gt;python .\python_file_name.py&lt;/code&gt;&lt;br&gt;
Mac / Linux - &lt;code&gt;python ./python_file_name.py&lt;/code&gt;&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;Flow Control - Is it this or that?&lt;/strong&gt;&lt;/p&gt;



&lt;p&gt;Finally, we get to the subject of this article's discussion. There comes a time in every coder's journey where we need our code to make some decisions for itself. In order to do this we need to have some kind of control state. The control state may be a variable or the output from another piece of code and it could represent boolean values, a number, a string or pretty much anything we can check to determine if it is one thing or another. We then look at that state and depending on what we see at that time we go in one direction or another. Essentially, we ask a multi choice question in our code - does the value of this thing we have selected match one of these values? If the answer is yes then we will run a piece of code associated with that value. If not, we can run code in the event that none of our answers match.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuo28daaq48h60xnr161d.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuo28daaq48h60xnr161d.jpg" alt="flow diagram" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In coding, to make these decisions we use the 'If / Else Statement'. Consider the following example where we have a variable - &lt;code&gt;state&lt;/code&gt;, which contains boolean data (True or False). We use an if statement to check the value of &lt;code&gt;state&lt;/code&gt; and then run some code depending on the outcome.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;state = True

if state == True:
    # run this code if the answer is yes
else:
    # otherwise run this instead if the answer is no
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;state&lt;/code&gt; is equal to 'True' then the answer to our question is yes (True) and the first indented code block will run&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;state&lt;/code&gt; is equal to anything else then the result will be no (False) and the second code block will run&lt;/p&gt;

&lt;p&gt;In the above example, &lt;code&gt;state&lt;/code&gt; is equal to 'True' so the value of the &lt;code&gt;state&lt;/code&gt; variable matches our question - does &lt;code&gt;state&lt;/code&gt; have the booelan value 'True'? - yes it does! Had &lt;code&gt;state&lt;/code&gt; had the value 12, 4.6, "otter", False, or anything other than 'True' the answer to our question would be no, our if statement code would not run and we would default to our wrong answer code instead.&lt;/p&gt;

&lt;p&gt;There are some key points to go through here so let's break the if statement down line by line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if state == True:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our statement begins with the keyword &lt;code&gt;if&lt;/code&gt;. Remember those protected keywords used by Python, this is another one of them and it can't be used for variables names or similar. We then say which control state we are going to be checking, in this case a variable named &lt;code&gt;state&lt;/code&gt;. What follows are 2 '==' signs which in code mean 'equal to'. Finally, we say what we are comparing our control statement to, in this case the value 'True'. We then end the line with a colon ':' to let Python know to look for indented code below. In English what this line says is:&lt;/p&gt;

&lt;p&gt;if my variable named 'state' has a value equal to 'True' then do what comes next&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    #run this code if the answer is yes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If our if statement is true, that is &lt;code&gt;state&lt;/code&gt; is indeed equal to True then we run the code found indented from the if statement. Indentation or offsetting code from the margins is a frequently used formatting convention in coding and the subject of a &lt;a href="https://www.alpharithms.com/tabs-vs-spaces-the-timeless-debate-581511/" rel="noopener noreferrer"&gt;furious debate&lt;/a&gt; which I won't get into here. Suffice to say we can either indent our code using the Tab key or using 4 spaces. Any indented code immediately following the if statement line will be ran ONLY if the if statement is true.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;else:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So what if the if statement is not True? In that case we move down to the 'else statement'. The else statement is not compared to anything because it is our default and covers any outcome other than that tested in the if statement. So again, in plain English we can see the if / else statement as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if this value is equal to this value then run the indented code that comes next:
    #Some code here
Else, for any other outcome run this indented code instead:
    #Some other code here
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The indented code in the else statement will always run unless the if statement turns out to be true. &lt;/p&gt;




&lt;p&gt;Time for a hands on example. In your chosen IDE delete any code you already have and create a variable called &lt;code&gt;chance&lt;/code&gt; and set it equal to 'True' (capital 'T' and no quotation marks).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chance = True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Underneath on the next line write the following if statement and press enter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if chance == True:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have now created our if statement to check if &lt;code&gt;chance&lt;/code&gt; is equal to 'True'. On the line under the if statement indent your cursor using either the tab key or 4 spaces and write the following and hit enter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    print("It's True!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On the next line write our else statement and press enter. Make sure the else statement is not indented and is all the way to the left:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;else:
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, on the last line write the code to run if the else statement comes into play, again indent this line with tab or 4 spaces:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    print("It's False!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All together we should have the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chance = True
if chance == True:
    print("It's True!")
else:
    print("It's False!"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the code, what output do you get? Hopefully you should see "It's True!" printed to the console. If not, double check for typos and make sure you are indented correctly.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"There are two ways to write error-free programs; only the third one works." - &lt;em&gt;Alan Perlis&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;So at this point, our code is making decisions based on the state of a value. So what? Well, being able to make decisions means we can write software which can alter how it works based on the outcome of certain factors which means we can anticipate different use cases to make sure our application can handle anything we throw at it.&lt;/p&gt;

&lt;p&gt;Now let's take a look at what happens if &lt;code&gt;state&lt;/code&gt; is not True, what happens then? Go back into your code and change the value of &lt;code&gt;state&lt;/code&gt; to 'False' or anything other than 'True'. Run the code again and check the output. If all is working properly you should see "It's False" displayed in the terminal.&lt;/p&gt;

&lt;p&gt;Hopefully this is making sense, so let's try a more useful example. Clear your code from your IDE window and start with the following line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;guess = input("Guess a number between 1 and 5: ")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This line uses another inbuilt Python method to get input from the user of the application and store it in a variable named &lt;code&gt;guess&lt;/code&gt;. We can also use this to print some text on the screen to tell the user what we want from them. So we will get a number entered by the user, now to check if they have guessed our secret number correctly. Under the first line write the following if statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if guess == 3:
    print("Correct! You Win!")
else:
    print("Incorrect, you lose!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the code and try it out, enter a number and see if the code behaves as expected.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2u0j27wrarq7mj9r4nuf.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2u0j27wrarq7mj9r4nuf.jpg" alt="guessing game" width="256" height="35"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Variations of the If Statement&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;We can alter the way our if statements work with a few tweaks.&lt;/p&gt;

&lt;p&gt;First lets look at some of the other operators we can use instead of '==' equals to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Not equal to - !=&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Greater than - &amp;gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Less than - &amp;lt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Greater than or equal to - &amp;gt;=&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Less than or equal to - &amp;lt;=&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if 12 != 6:
    print("True!")
else:
    print("False!")
# Output
True! # 12 is not equal to 6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if 64 &amp;lt; 32:
    print("True!")
else:
    print("False!")
# Output
False! # 64 is is not less than 32
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example 3&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if 128 &amp;lt;= 128:
    print("True!")
else:
    print("False!")
# Output
True # 12 is equal to or less than 128
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Multiple Operators&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;As well as the operators we have already looked at such as '==' '!=', '&amp;gt;' etc we can also combine multiple operators to get more specific about what we are looking for. To combine operators we use the keywords &lt;code&gt;and&lt;/code&gt; / &lt;code&gt;or&lt;/code&gt;. When using &lt;code&gt;and&lt;/code&gt; both if statements must be True for the result to be True. When using &lt;code&gt;or&lt;/code&gt; only one needs to be True.&lt;/p&gt;

&lt;p&gt;Example using &lt;code&gt;and&lt;/code&gt; - 12 is both greater than 10 and less than 15&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number = 12
if number &amp;gt; 10 and &amp;lt; 15:
    print("Maybe it's 12")
else:
    print("Could be anything!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example using &lt;code&gt;or&lt;/code&gt; - 64 is not less than 10 but is greater than 60&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;number = 64
if number &amp;lt; 10 or &amp;gt; 60:
    print("Looks good")
else:
    print("Could be anything!")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Else If&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;A final addition to the way we can make decisions with if statements is with the use of the 'Else If' statement. Essentially this allows us to add more than 2 outcomes for our decision making. If the if statement is False then Python will check each else if statement for a True outcome before finally defaulting to the else statement. The syntax for an else if statement is &lt;code&gt;elif&lt;/code&gt; followed by the condition to be met:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;animal = "sheep"

if animal == "cow":
    print("It's a cow!")
elif animal = "sheep":
    print("It's a sheep!")
else:
    print("I don't know what it is!")

# Output
"It's a sheep!"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, Python checks our if statement to see if &lt;code&gt;animal&lt;/code&gt; is equal to "cow" but this returns false so it moves down to the else if statement and checks &lt;code&gt;animal&lt;/code&gt; to see if it is equal to "sheep' which it is and so returns True. As Python has found a True statement, the indented code under the 'elif' statement is run. The rest of the if / else statement is not run and the code will continue under the if / else statement.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Pass and Break&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The final thing I want to discuss in this article is the use of &lt;code&gt;pass&lt;/code&gt; or &lt;code&gt;break&lt;/code&gt;. Sometimes in our if / else statements there can be an outcome where we do not want anything to happen if a statement is true.&lt;/p&gt;

&lt;p&gt;Firstly, using the &lt;code&gt;pass&lt;/code&gt; statement will move down to the next part of the if / else statement without doing anything&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;state = "Undecided"

if state = True:
    print("True")
elif state = "Undecided":
    pass
else:
   print("Not sure")
# Output
"Not sure"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example when &lt;code&gt;state&lt;/code&gt; is found to be equal to "Undecided" the indented code is run. However, the pass statement moves Python on to the next part of the statement which is the else statement.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;break&lt;/code&gt; keyword is similar to the pass keyword except using break will cause Python to jump out of the if / else statement all together and continue on from the next line.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;state = "Undecided"

if state = True:
    print("True")
elif state = "Undecided":
    break
else:
   print("Not sure")

print("must have used the break statement")
# Output
"must have used the break statement"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;So why do we care about all this if / else stuff?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The ability to check values and act upon them is fundamental to software development. Consider the following uses for if / else statements in applications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Checking the input a user gives us to make sure it is the right data type and matches our requirements. For example, if we ask for a user's name we want to ensure they have actually typed something and not just pressed Enter with a blank name. We can also check they have not entered numbers, inappropriate words etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When using datasets we can go through all of the values in a large spreadsheet or file and check that each value is formatted properly, is the correct data type and if we find missing values we can flag these or enter replacement values automatically.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When sending data or files over the internet we can check a variable containing an http response status code which tells us if the data or file has been received correctly.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The use cases of 'check if this is a certain way and then do something if it is' are almost endless. I definitely recommend spending some time with this topic to get to grips with it fully.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Task&lt;/p&gt;

&lt;p&gt;For this task I am going to set you a challenge but I am not going to give step by step points to accomplish it. &lt;/p&gt;

&lt;p&gt;My challenge is to create a Python application using everything you have learned so far which is able to do the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Ask the user for first and last name as well as their age&lt;/li&gt;
&lt;li&gt;Look at the age given by the user and perform some decision making to decide if they are old enough to do something where you live - vote, drink, drive etc.&lt;/li&gt;
&lt;li&gt;Print out to the terminal a sentence along the lines of "Hello  , you are  and you [can/cannot] do [activity]!"&lt;/li&gt;
&lt;li&gt;For an extra challenge, give yourself more decisions to make so check if the person is eligible to do several activities which require them to be a certain age.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Take your time and go back over the article if you get stuck. You can do it!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;With the addition of 'Else If' statements we can begin to make quite complex decision making which can account for a variety of possible outcomes. Along with our new found ability to take user input we can now start to make applications that can actually do something useful. Flow control marks the point where we move from total beginner subject matter to things which get a little more complicated. All this means is that you may need to spend a little more time with things and do some extra practice to get a good understanding of things. Learning to code is not about memorising syntax it is about learning how things work on a conceptual level and then putting all of the pieces together to create something amazing. Keep going and make the most of all of those great coding resources online if you are struggling. &lt;/p&gt;

&lt;p&gt;So far we have made code that will run and then stop when it is done. What if we could make an app which would be able to run again and again if needed until we are finished with it or maybe it could do something really repetitive many times really quickly? Well, good news that is the subject of the next article - loops! Thank you for reading and I look forward to seeing you in part five.&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>Part Three: Data Structures</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Sun, 20 Nov 2022 11:54:45 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-three-data-structures-4jj1</link>
      <guid>https://forem.com/simonchalder/part-three-data-structures-4jj1</guid>
      <description>&lt;p&gt;Welcome to part three. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at some of the ways we can store multiple values in a single variable in Python, but first let's take a look at the solution for the challenges set in part two.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;“Failure is the condiment that gives success its flavour.” – &lt;em&gt;Truman Capote&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;Solution to part two's challenges&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Task 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1. 40
2. 336
3. -84
4. 15
5. # Python knows BIDMAS rules so we can solve this with either:
num2 + num1 * num3 / (num1 - num2)

# Or we can use brackets to seperate the multiplication and division from the addition and subtraction
num2 + (num1 * num3) / (num1 - num2)

Answer: 30.25 (result is a float)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Task 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;animal = "Crayfish"
plant = "Honeysuckle"
habitat = "woodland"

1. answer = animal[0]
'C'
2. answer = habitat[-1]
't'
3. answer = animal[4:8] OR animal[4:] OR animal[-4:]
'fish'
4. answer = plant[0:5] OR plant[:5]
5. answer = habitat[-4:8] OR habitat[-4:]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Data Structures&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Why do we care about data structures?&lt;/p&gt;

&lt;p&gt;Data structures allow us to store data in an organised manner so that it can later be retrieved easily. Examples of data structures in coding projects include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The basket containing order items in an online store&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Creating a list of customers and performing an action for each customer such as sending an email&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Collect survey or study results in a list so as to be able to easily visualise or export your results&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;So far we have looked at using variables to contain a single value. However, we are also able to store multiple values in a single variable. Python offers 3 flavours for this, the first of which is the list. Lists can store any number of items and accept all data types so mixed type lists are possible.&lt;/p&gt;




&lt;p&gt;Lists&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"I love the way a list makes a big hodgepodge of things simmer down and behave." - &lt;em&gt;Blue Balliett&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;A list is a way to store multiple values in a single variable. Theoretically there is a limit to the number of values or items we can store in a Python list, &lt;a href="https://stackoverflow.com/questions/855191/how-big-can-a-python-list-get"&gt;this source&lt;/a&gt; suggests 536,870,912 but in practical terms, let's just say they can hold more items than you will ever reasonably need to worry about. So what can we put in our lists? Well for starters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Integers&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Strings&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Floats&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Boolean&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Other lists (yes lists within lists!)&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can mix and match our data types to create lists with all manner of items together in the same variable.&lt;/p&gt;

&lt;p&gt;We can create a list by giving it a name just like a variable and then after our '=' sign we tell Python this is a list using '[]' square brackets. We can create an empty list by just using empty square brackets or we can add items when we create the list. Our list items go between the square brackets and are separated by a comma.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_empty_list = []

list_of_biomes = ["tundra", "arctic", "jungle", "desert"]

random_list = ["orange", 33, "blue", False, 6.85]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lists operate in much the same way as strings. Whereas strings assign an index to each character, a list assigns an index to each list item. In the following example we create a list in IDLE named &lt;code&gt;mammals&lt;/code&gt; and use it to store some string values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now access values in the list in the same way we sliced characters in a string using the index number. Just like strings, items in a list start at index 0.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;animal = mammals[1]
print(animal)
Hare
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each of these items in our list is a string and as such we can delve deeper into the list, extracting string characters from list items. To do this we use 2 sets of square brackets, the first determining the list item and the second the character in the string&lt;/p&gt;

&lt;p&gt;In this example we slice the 4th character of the first string item.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
letter = mammals[0][4]
S
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lists can also contain other lists. In this next example, the 4th item in &lt;code&gt;my_list&lt;/code&gt; is another list of integers. Placing lists within lists is known as 'nesting'.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_list = [2, 4, 6, [3, 5, 7,], 8]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To access a value in the nested list we once again use 2 sets of square brackets. Just like with getting individual characters from list items, the first bracket contains the index of the list item. The second brackets contain the index of the nested list's item.&lt;br&gt;
For example, if we wanted the 2nd character of the nested list (located at item 4 in &lt;code&gt;my_list&lt;/code&gt;) we would use the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nested_character = my_list[3, 1]
print(nested_character)
5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;OK, great but what if we want to change our list by changing, adding or removing items?&lt;/p&gt;

&lt;p&gt;To change an item in a list, we assign a value in much the same way as declaring a variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
mammals[1] = "Osprey"
print(mammals)
['Red Squirrel', 'Osprey', 'Barn Owl', 'Pine Marten']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the 2nd item in the list is changed from "Hare" to "Osprey".&lt;/p&gt;

&lt;p&gt;We can also change several items at once. In this next example we change the 3rd and 4th items to different items.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
mammals[2:4] = ["Elephant", "Tiger"]
print(mammals)
['Red Squirrel', 'Osprey', 'Elephant', 'Tiger']

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;A brief and passing introduction to methods&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Whoa, hang on there! What's this method thing you're trying to sneak in? &lt;/p&gt;

&lt;p&gt;We will get into functions and methods in the future but for now just know that a method is a chunk of pre-written code built into Python that performs a certain repeatable action. We have actually already been using one of Python's built in methods. Remember the print() code we wrote to show the contents of our variable? The print method came with Python so we did not have to figure out how to get our output onto the screen from scratch. Methods are huge time savers and as we go on you will see a lot more of what they can do. Anyway, back to lists...&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;append()&lt;/code&gt; method allows us to add items to the end of a list easily. The syntax for using this is &lt;code&gt;list_name.append(thing we want to append)&lt;/code&gt;. The next example shows how we would add an item to a list in this manner&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
new_item = "Badger"
mammals.append(new_item)
print(mammals)
["Red Squirrel", "Hare", "Barn Owl", "Pine Marten", "Badger"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As well as appending a variable to a list such as &lt;code&gt;mammals.append(new_item)&lt;/code&gt; we can also append the value directly &lt;code&gt;mammals.append("Badger")&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We can remove items from a list or delete an entire list using the &lt;code&gt;delete.()&lt;/code&gt; method. Again the index value works in the same manner as slicing and we can give a range of index numbers or count backwards.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mammals = ["Red Squirrel", "Hare", "Barn Owl", "Pine Marten"]
del mammals[2]
print(mammals)
["Red Squirrel", "Hare", "Pine Marten"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Tuples&lt;/p&gt;




&lt;p&gt;Tuples are very similar to lists, except once it is created we cannot alter the items it contains. tuples are created much like lists but using round brackets rather than square brackets. Tuples, like lists can contain any data type including other lists and tuples.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_tuple = (12, 4.2, "Giraffe", False)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can access tuple items using index numbers in the same way as lists.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_tuple = (12, 4.2, "Giraffe", False)
my_tuple[0]
12
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, unlike lists we cannot modify the contents of a tuple using methods.&lt;/p&gt;




&lt;p&gt;Dictionaries&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"Baldrick, believe me, eternity in the company of Beelzebub and all his hellish instruments of death will be a picnic compared to five minutes with me and this pencil if we can't replace this dictionary." - &lt;em&gt;Blackadder&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;In Python, dictionaries are collections of data organised into &lt;code&gt;key : value&lt;/code&gt; pairs. This allows us to retrieve values by referencing the key to which that value is assigned. Dictionaries are created using curly brackets '{}'.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Accessing values in dictionaries is accomplished by using the key rather than an index number. In the above example if we wanted to access the value associated with the '2' key we would use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(my_dictionary[2])
Fox
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Keys do not have to be numbered or have any relation to one another at all&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {'name': "Simon", 17: 4.67, 'pig': True}
print(my_dictionary['name')
Simon
print(my_dictionary[17)
4.67
print(my_dictionary['pig')
True
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dictionary values can be modified in much the same fashion as lists using the key for reference&lt;/p&gt;

&lt;p&gt;Example 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
my_dictionary[2] = "Cow"
print(my_dictionary)
{1: "Rabbit", 2: "Cow", 3: "Sheep"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {'name': "Simon", 17: 4.67, 'pig': True}
my_dictionary['name'] = "Percy"
print(my_dictionary)
{'name': "Percy", 17: 4.67, 'pig': True}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To add key : value pairs to a dictionary we use the same method as changing an item. If the key does not already exist then it will be created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
my_dictionary[4] = "Badger"
print(my_dictionary)
{1: "Rabbit", 2: "Fox", 3: "Sheep", 4: "Badger"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also remove items using the &lt;code&gt;del()&lt;/code&gt; method in the same way as with a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {1: "Rabbit", 2: "Fox", 3: "Sheep"}
del my_dictionary[1]
print(my_dictionary)
{2: "Fox", 3: "Sheep", 4: "Badger"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, just like lists and tuples, dictionaries can have nested items including other dictionaries&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {1: 'One', 2: 'Two', 3: {'a': 'A', 'b': 'B'}, 4: 'four'}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Accessing nested dictionary items is done in the same way as nested lists except we use the keys instead of index numbers for the parent dictionary and the nested item. In the following example we want the nested dictionary from key '3' and the item value from key 'b' in the nested dictionary.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my_dictionary = {1: 'One', 2: 'Two', 3: {'a': 'A', 'b': 'B'}, 4: 'four'}
nested_item = my_dictionary[3]['b']
print(nested_item)
'B'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Take some time to make sure this all makes sense and practice creating and manipulating your own lists, tuples and dictionaries.&lt;br&gt;
Python data structures and their associated methods are a topic well worth taking the time to learn. I have only briefly touched on what is possible here. To learn more follow &lt;a href="https://www.programiz.com/python-programming/list"&gt;this link&lt;/a&gt; and see if you can solve the following problem:&lt;/p&gt;

&lt;p&gt;Task 1&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a list and name it &lt;code&gt;my_list&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Give your list several items of different data types e.g. strings, integers, floats etc.&lt;/li&gt;
&lt;li&gt;Append your name as a string to the end of the list&lt;/li&gt;
&lt;li&gt;Delete the 3rd item in your list&lt;/li&gt;
&lt;li&gt;Substitute the 1st and 2nd items in your list with different items&lt;/li&gt;
&lt;li&gt;Delete the entire list&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Task 2&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a tuple and name it &lt;code&gt;my_tuple&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Try to append, delete or change values in &lt;code&gt;my_tuple&lt;/code&gt; and note any errors or messages Python gives you&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Task 3&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a dictionary and name it &lt;code&gt;my_dict&lt;/code&gt;. In it, create the keys "genus", "species", "habitat" and "diet" and give them some appropriate values&lt;/li&gt;
&lt;li&gt;Add a new key "Lifespan" and give it an appropriate value&lt;/li&gt;
&lt;li&gt;Delete the "genus key and value&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Hopefully, you are starting to see potential uses for data structures in your own projects. If not, don't worry you will get plenty of practice using them in the future. In the next article I am going to discuss flow control which enables our code to make decisions based on logical states. We will also be moving away from IDLE and using a new  - tool the developers IDE! Exciting times ahead. I look forward to seeing you in part four. As always, constructive feedback is always appreciated. Thanks.&lt;/p&gt;

&lt;p&gt;Simon.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>python</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Part Two: Data Types</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Sat, 19 Nov 2022 18:34:03 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-two-data-types-5fpj</link>
      <guid>https://forem.com/simonchalder/part-two-data-types-5fpj</guid>
      <description>&lt;p&gt;Welcome to part two. In this series I hope to introduce the basics of coding in Python for absolute beginners in an easy to follow and hopefully fun way. In this article we will look at some of the types of data we can use in Python, but first let's take a look at the solution for the challenge set in part one.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"In the spirit of science, there really is no such thing as a ‘failed experiment.’ Any test that yields valid data is a valid test." –  &lt;em&gt;Adam Savage&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;Solution to part one's challenge&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The way we can put 2 variables together and print them on the same line is through something called 'concatenation'. This fancy sounding term simply means to stick 2 things together and we do it with the '+' sign. Like many tasks in coding there are several different ways of doing the same thing so here are a few ways of accomplishing this task&lt;/p&gt;

&lt;p&gt;Option 1&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;genus = "Pinus" 
species = "sylvestris"
solution = genus + species
print(solution)
# Output
Pinussylvestris
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Option 2&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;genus = "Pinus" 
species = "sylvestris"
print(genus + species)
# Output
Pinussylvestris
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Option 3 including ways to add a space&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;genus = "Pinus" #we could add a space here - "Pinus "
species = "sylvestris" #We could add it here " sylvestris"
solution = genus + " " + species # Or here
print(genus + " " + species)#Or here
# Output
Pinus sylvestris
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Concatenation is a useful tool for formatting output or just for combining more than one value. Consider the following example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sci_name = "Ursus arctos horribilis"
location = "Northern America"
colour = "Brown"
age = 20
sentence = "Grizzly bears, also known as " + sci_name + " are found in " + location + ". They are usually " + colour " in colour, and live to around " + age " years old"
print(sentence)
#Output
"Grizzly bears, also known as Ursus arctos horribilis are found in Northern America. They are usually Brown in colour, and live to around 20 years old"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember to pay attention to your quotation marks. I would highly recommend playing around in IDLE with concatenation. For more information see &lt;a href="https://studyber.com/string-concatenation-in-python/"&gt;this link&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Some other things we can put in variables&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;We have now declared our first variables (a fancy term for creating a variable and giving it a value). Not all that impressive, so what else can we do with variables? As we have already learned, variables can be used to hold many different types of data. Data types are an important concept in coding. Multiplying 2 variables which contain numbers would work, but doing the same with a number variable and another which contained only text might produce unexpected results or fail all together. &lt;/p&gt;

&lt;p&gt;There are many data types which Python can work with but for simplicity the basic, commonly used types are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Integers&lt;/strong&gt; - Integers or 'int' for short are whole numbers, positive or negative e.g. 12, 458, -2537 etc.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Strings&lt;/strong&gt; - String or 'str' for short represent text and are always surrounded by either 'single' or "double" quotation marks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Floats&lt;/strong&gt; - Floats are decimal numbers e.g. 23.6, -945.00023.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Boolean&lt;/strong&gt; - Booleans represent one of 2 values either 'True' or 'False'.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So we could create the following kinds of variables:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;my_name = "Simon"&lt;/code&gt; # String&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;count = 100&lt;/code&gt; # Integer&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;measurement = 685.48&lt;/code&gt; # Float&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;is_raining = True&lt;/code&gt; # Boolean&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;Why do we care about data types?&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;The projects we choose to make will inevitably contain different types of data. Everything from the names of plants, animals, places (strings), to survey numbers and population counts (integers), to map coordinates, correlation coefficients or fuel prices (floats). In order to get the expected results from our projects we must ensure we are using the correct data types. Understanding data types and how they interact with each other is essential when working on projects with several different types of data.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Numerical Data&lt;/strong&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"Arithmetic is being able to count up to twenty without taking off your shoes." - &lt;em&gt;Mickey Mouse&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Let's say we have declared (created) a variable &lt;code&gt;num1&lt;/code&gt; and assign a value of 10 (&lt;code&gt;num1 = 10&lt;/code&gt;). We can now perform arithmetic operations (+,-,*,/) using our variable. Firstly we can perform simple calculations using a single variable. In IDLE type &lt;code&gt;num1 + 2&lt;/code&gt; and press Enter. We see the result of 12 displayed. If we type &lt;code&gt;num1&lt;/code&gt; again we can see that the value of the variable has not changed, rather we have simply performed a calculation using its value.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5AEJFVQt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nf1rrtsnq6i59qo6f44j.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5AEJFVQt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nf1rrtsnq6i59qo6f44j.jpg" alt="addition" width="91" height="47"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Other mathematical operations we can perform include '-' for subtraction (&lt;code&gt;num1 - 3&lt;/code&gt;), '*' for multiplication (&lt;code&gt;num1 * 2&lt;/code&gt;), and '/' for division (&lt;code&gt;num1 / 2&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;We can also perform calculations using multiple variables:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--is-V4Cbx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqiktnzeh83b01ghlwv1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--is-V4Cbx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqiktnzeh83b01ghlwv1.jpg" alt="math" width="117" height="164"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is all well and good but performing calculations this way gives us no way of storing the result. We may wish to perform other calculations on the result or we may wish to display it in a way other than printing to the terminal or IDLE. The solution is to store the result of our calculation in another variable. To do this we use the syntax &lt;code&gt;result = num1 + num2&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--KDmo2q0X--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s84iwesodel73js7y12z.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--KDmo2q0X--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s84iwesodel73js7y12z.jpg" alt="idle" width="177" height="78"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;A quick note on variable names. &lt;/p&gt;




&lt;p&gt;In the above example we do not need to call our variable 'results' - we could call it anything we wish such as 'chicken' or 'sdjhdkjh'. However, when naming variables it is good practice to give them a name which reflects what they contain or are used for. It can be tempting to name variables things like 'x' or 'y' but when we begin to write longer applications it can quickly become confusing as to what these variables are for. When naming things in Python there are certain conventions we should follow. Some of these conventions make our code easier to read and some forbid the use of protected words which Python reserves for other purposes. &lt;/p&gt;

&lt;p&gt;For example we may need to create a variable to store the total number of birds recorded during a point survey. If we simply name the variable 'result' or 'total' this could become confusing later - which result or total is this referring to? So we would choose something suitable such as &lt;code&gt;bird_survey_total&lt;/code&gt;. We could also have named it &lt;code&gt;birdsurveytotal&lt;/code&gt; but this is harder to read. In Python one of the naming conventions when naming variables is to use &lt;em&gt;snake case&lt;/em&gt; (it is Python after all) which means to use an underscore '_' where a space would normally sit. Therefore, &lt;code&gt;bird_survey_total&lt;/code&gt; would be easier to read and would follow the correct naming convention. &lt;/p&gt;

&lt;p&gt;If you recall the previous discussion about data types we saw boolean values can be True or False. Note the capitalised first letter - 'True' and 'False' are reserved names in Python and we cannot use them to name things. You can try this in IDLE. Declare a variable named 'True' and try to give it a value - Python will give you an error to remind you not to do this. &lt;/p&gt;

&lt;p&gt;There is more to learn with this topic and something we all get better at with practice. If you would like to know more follow &lt;a href="https://pythonguides.com/python-naming-conventions/"&gt;this link&lt;/a&gt; and try to see which of the following variable names would follow Python naming conventions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;number_of_foxes&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;numberOfFoxes&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;_numberoffoxes&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Number_Of_Foxes&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;number_of_foxes!&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;NUMBER_OF_FOXES&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;strong&gt;What about Floats?&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Floats, just like integers can be used with mathematical operators and can be combined with integers in calculations. Be aware however that the output from such calculations will be a float, even if the result is a whole number.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;num1 = 5
num2 = 3.6
num3 = num1 * num2
print(num3)
#Output
18.0 # This result is a float despite being a whole number
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;...and Booleans?&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Boolean values represent a state - something is True or False, On or Off, 0 or 1. Booleans will come into their own in the future when we discuss flow control where we can check the state of a boolean and then perform actions depending on that state. Below is a simplified example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bool = True
if bool is True - do this
if bool is False - do this instead
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Strings&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Just like numerical data, working with strings of text is an important part of coding. To recap, a string is anything inside 'single' or "double" quotations. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;'Lorem ipsum' is a string&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"Lorem ipsum" is a string&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"12345" is a string&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;'34.68' is a string&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Lorem ipsum is NOT a string - no quotation marks&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;12345 is an integer and NOT a string&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can use single and double quotations together for grammatical purposes but we must ensure that we pay attention to the kind of quotations used. For example the following would be correct:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"It's raining outside"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However this would produce an error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'It's raining outside'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Can you see why? Python takes everything in between the same kind of quotes as a string. In the second example Python read &lt;code&gt;'It'&lt;/code&gt; as a string because it is surrounded by single quotes and everything after that as a separate thing. Enclosing the text in a different quotation style allows Python to treat the whole text as a string. Another example would be using double quotes inside singles such as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'tell her I said "hello" please'
# This would work. 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, if we instead used:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'tell her I said 'hello' please'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would produce a string containing &lt;code&gt;'tell her I said '&lt;/code&gt; and another containing &lt;code&gt;' please'&lt;/code&gt; as well as giving an error message. &lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Mixed Data Types&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Care must be taken to ensure the correct data type is used. For example, multiplying 6 and 3 will produce a result of 9. What about multiplying 6 (an integer) and "3" (a string)? Try it in IDLE for yourself, was it what you expected? In this case we have literally taken the string "3" and printed it 6 times. Perhaps this is what we wanted but we must ensure we are aware of the type of data we are using.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Slicing&lt;/strong&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"No matter how thin you slice it, it's still baloney" - &lt;em&gt;Al Smith&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;We already know that printing the variable shows us the contents of that variable but what if we only want to know part of the contents? Perhaps we need to know the 3rd character in a string as an identifier or maybe the last 2 characters are important. To do this we use a technique known as &lt;em&gt;slicing&lt;/em&gt;. Despite sounding like something a hacker would do in some dodgy action movie, slicing simply means breaking down a string into individual characters and then &lt;em&gt;slicing&lt;/em&gt; out the bits we want. &lt;/p&gt;




&lt;p&gt;Why would we care about slicing?&lt;/p&gt;




&lt;p&gt;Suppose we have an application which tracks livestock numbers. Each animal is identified by a letter "C" for cow, "S" for sheep, or "P" for pig followed by a unique ID number. A sheep in the database may have the ID "S-2468" for example. By using slicing we can read the first character from the ID string value and determine what kind of animal it is. We can also poll all records and sort them by their string's first character to determine how many of each animal are represented. Slicing can be a powerful and time saving tool when used properly.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Indexing&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Each character in a string is represented by a number (the index). Computers count in a slightly different way to most of us in that instead of starting with 1 they use 0. Therefore when we are doing our slicing we need to remember that the first character in a string is represented by the index 0 not 1. For example, if we had the string &lt;code&gt;"Apple"&lt;/code&gt;, Python would read the characters and give them the following index numbers:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Lc8e0bpP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sr4ej9fcnijage9h5q1j.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Lc8e0bpP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sr4ej9fcnijage9h5q1j.jpg" alt="slicing" width="410" height="242"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In order to retrieve the correct character we simply tell Python the index number of the character we want. To do this we use the name of the variable containing the string followed by square brackets and inside these brackets we place the index number of the required character. It is important here to note that slicing takes a copy of the required character and the string being sliced remains unaffected. Also of note is that spaces are included as characters in strings so slicing a character which is a space will return " ".&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mFrdhStC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tx7avnzkdvbz1l6a0w0h.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mFrdhStC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tx7avnzkdvbz1l6a0w0h.jpg" alt="slicing 2" width="138" height="67"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above example we have a &lt;code&gt;word&lt;/code&gt; variable containing the string "Apple". We slice character number 1 from the &lt;code&gt;word&lt;/code&gt; variable and store it in a new variable named &lt;code&gt;letter&lt;/code&gt;. This gives us the letter 'p' - remember, we begin the count from 0 and so character 1 is actually the 2nd letter in the string. If we had wanted the first character we would have used &lt;code&gt;word[0]&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;In the same way that we count the 1st character as 0 we can also count backwards. Say we had a string named &lt;code&gt;phrase&lt;/code&gt; which contained a long sentence of 80 characters, if we wanted to know the last character in the string we could use &lt;code&gt;phrase[79]&lt;/code&gt; (remember the string has 80 characters but numbers start at 0 so the last number will always be 1 less than the total), however we may not know the total characters and a simpler way to do this is to use &lt;code&gt;phrase[-1]&lt;/code&gt;. Using minus numbers allows us to count backwards in the same manner as going forwards. So, [-2] would be the 2nd to last character and so no.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--QWFwCQSg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aaon8i8xosiddwlh80ex.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QWFwCQSg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aaon8i8xosiddwlh80ex.jpg" alt="slicing 3" width="191" height="63"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So now we know how to extract single characters from strings. What about if we want a range of characters? The process is similar to getting a single character but we give Python a start and end position for our slice. The syntax here is &lt;code&gt;variable_name[start:end]&lt;/code&gt;. It is important to note that the end character number is NOT included. If we use our "Apple" string example, we want to get the 1st character through to the 3rd character.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5tVtGjpu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bcdvcpv7kvq4nnc7w7py.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5tVtGjpu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bcdvcpv7kvq4nnc7w7py.jpg" alt="slicing 4" width="168" height="67"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Although 'A' is 0, 'p' is 1 and 'p' is 2 we must slice up to 3 in order for character 2 to be included. &lt;/p&gt;

&lt;p&gt;Slicing to the end of a string can be done even if we do not know the string's length by simply leaving a blank space. For example, to include everything from the 2nd character onwards we would use &lt;code&gt;word[1:]&lt;/code&gt;. To include everything from the start of the string to the 4th character we would use &lt;code&gt;word[:4]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For more information on slicing follow &lt;a href="https://www.pythonforbeginners.com/dictionary/python-slicing"&gt;this link&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Time for a challenge! Here are some tasks to go through to get some practice using mathematical operators as well as some string slicing.&lt;/p&gt;

&lt;p&gt;Task 1: &lt;/p&gt;

&lt;p&gt;Create 3 variables - &lt;code&gt;num1&lt;/code&gt; equal to 12, &lt;code&gt;num2&lt;/code&gt; equal to 28 and &lt;code&gt;num3&lt;/code&gt; equal to -3. Use these variables to calculate the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;num1&lt;/code&gt; + &lt;code&gt;num2&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;num1&lt;/code&gt; * &lt;code&gt;num2&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;num2&lt;/code&gt; * &lt;code&gt;num3&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;num1&lt;/code&gt; - &lt;code&gt;num3&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Bonus - try to solve the following using Python. What data type is the answer?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vIZdpkQC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hqna1g79l6a84poc4e2v.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vIZdpkQC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hqna1g79l6a84poc4e2v.jpg" alt="task1" width="801" height="313"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Task 2:&lt;/p&gt;

&lt;p&gt;Create 3 variables - &lt;code&gt;animal&lt;/code&gt; equal to "Crayfish", &lt;code&gt;plant&lt;/code&gt; equal to "Honeysuckle", and &lt;code&gt;habitat&lt;/code&gt; equal to "woodland".&lt;/p&gt;

&lt;p&gt;In a new variable store the following. Print the new variable to verify it is correct.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The 1st character from &lt;code&gt;animal&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;The last character from &lt;code&gt;habitat&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;The characters 'fish' from &lt;code&gt;animal&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;the characters 'Honey' from &lt;code&gt;plant&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;The last 4 characters from &lt;code&gt;habitat&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Conclusion&lt;/p&gt;




&lt;p&gt;We have now covered variable creation and some of the types of data we can store in our variables. We have also gone over how to do basic mathematics with numbers and how to slice and manipulate text. In the next article we will look at data structures, that is, a way that we can store more than one value in a variable and even turn our variables into miniature databases. I will continue to leave small challenges to try and get you thinking and practising these topics. However, I will be intentionally asking you to solve problems for which the solution involves things we have not fully covered. The reason for this is that as you go on to make your own projects you will get stuck. It happens to everyone, even the professionals and a common joke is that developers are nothing more than expert Googlers! &lt;/p&gt;

&lt;p&gt;When you do get stuck it is important to try and get yourself unstuck and learning where to find help and information is key. I will likely devote an entire article to this in the future but a good starting point is the &lt;a href="https://docs.python.org/3/"&gt;official Python documentation&lt;/a&gt; or to search for the exact issue you are having such as "python string will not print". This will usually get you on the right track and usually someone has had the exact same issue as you. More on this in the future.&lt;/p&gt;

&lt;p&gt;Thanks for reading. Constructive criticism is always appreciated. I look forward to seeing you in part 3.&lt;/p&gt;

&lt;p&gt;Simon&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>python</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Part One: Getting Started</title>
      <dc:creator>Simon Chalder</dc:creator>
      <pubDate>Fri, 18 Nov 2022 16:29:52 +0000</pubDate>
      <link>https://forem.com/simonchalder/part-one-getting-started-4ba</link>
      <guid>https://forem.com/simonchalder/part-one-getting-started-4ba</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;"Programmer? I barely knew her!" - &lt;em&gt;Unknown&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;What's it all about and why should I care?&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Fair question.&lt;/p&gt;

&lt;p&gt;At some point in your student or working career you may have been told that you should "learn to code". Well, what is learning to code? What is code? Is coding different to programming? Why should you even care?&lt;/p&gt;

&lt;p&gt;Writing code, computer programming, or writing software are all terms which are often used interchangeably and essentially mean the same thing - giving a computer a set of written instructions. Just like instructing a human worker or volunteer, the amount of instruction and the complexity of those instructions can be determined by the task we need the worker, or in this case, computer to perform. Just like their human counterparts, computers will produce poor results if they are given poor instructions. &lt;/p&gt;

&lt;p&gt;So why bother learning to code? Computers are tools which allow us to perform complex or repetitive tasks quickly and reliably. There are things we may wish to do such as collate survey results, examine geospacial data, or compare population numbers over time. In some cases we can get by using common software packages such as spreadsheets but perhaps our spreadsheet software does not allow us to display our data the correct way or does not work well with the type of data we are using. Maybe we need software to do something niche or bespoke and a readily available, off the shelf solution does not exist. In some situations, having the ability to write simple scripts (a small, usually simple application) or applications which will do a specific task for us can save us a great deal of time learning how to use a commercial software package. &lt;/p&gt;

&lt;p&gt;Here are some examples of simple software applications which you could write:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Comb through large datasets to find what you need and then manipulate that data in any way you wish&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Produce custom graphs and visualisations from your data to show others&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Write a script which will automatically go out onto the internet and retrieve data from websites or databases. No browser required!&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use machine learning to make future predictions based on historical data&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;My intention with this series is not to take you from novice to professional developer but to give you a taste of the possibilities that writing your own code can bring. How far you wish or need to take it from there is completely up to you.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"Yes! Get on with it!" - &lt;em&gt;Monty Python&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Ok, enough waffle lets start coding. A quick &lt;a href="https://en.wikipedia.org/wiki/List_of_programming_languages" rel="noopener noreferrer"&gt;online search for programming languages&lt;/a&gt; will bring back a frighteningly large list of results. Fortunately we are only going to focus on one - Python. Python, like all programming languages has its pros and cons. However, it is generally seen as a good language for beginners to get to grips with and as a bonus is used extensively in the data science and machine learning fields. Additionally, if you follow the principles of python, that is an object orientated approach (more on this later), then you will be able to pick up other programming languages easily. The way each language is written (the syntax) is slightly different from language to language but they mostly follow the same core concepts.&lt;/p&gt;

&lt;p&gt;First things first we need to install Python on the device you will be using (preferably something with a keyboard). The &lt;a href="https://www.python.org/downloads/" rel="noopener noreferrer"&gt;Python website&lt;/a&gt; contains download links for Windows and Mac, simply select the relevant link, download and install. For Linux users, you may already have python installed with your distribution - type &lt;code&gt;python -V&lt;/code&gt; into the terminal. If you see a version number you are good to go. If not follow instructions to install via your package manager. It's a good idea to bookmark the Python site as the documentation there can be very helpful when making your own projects.&lt;/p&gt;

&lt;p&gt;Python should be installed and ready to go. To begin, open your device's application list or perform a search for 'IDLE' and open the application. If all is going well up to this point you should see something similar to the image below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbrybotgx5o80ogp71lst.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbrybotgx5o80ogp71lst.jpg" alt="Python IDLE" width="701" height="716"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;IDLE stands for 'Interactive Development Learning Environment' and it is essentially a way for us to try out code without worrying about breaking anything. So lets type something and see what happens. In the text window of IDLE click to get a cursor and type your name, then press Enter.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F87xwn86z4izaf0chi8jx.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F87xwn86z4izaf0chi8jx.jpg" alt="Error Message" width="340" height="67"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Yikes! Red text! Traceback what...? What's a NameError? Why is Python angry at me? Well, firstly Python isn't angry, in fact it is trying to help us. The error message we received is telling us that Python did not understand the code we typed. Specifically, the message tells us which bit of the code it did not understand (in this case line 1) and the kind of error (NameError) gives us information as to what the problem may be. Error messages are not to be feared and you will see them a lot, particularly in the beginning.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Variables - The Coder's Magic Box&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;Let's try typing our name again but this time type &lt;code&gt;name =&lt;/code&gt; and then your name but make sure your name is in either single or double quotations. For example I would type &lt;code&gt;name = "Simon"&lt;/code&gt; and press Enter.&lt;/p&gt;

&lt;p&gt;Wait, nothing happened. Or did it? What we did here was to create a variable called 'name' and give it a value, in this case your name. A variable is a placeholder for a value and we use the '=' sign to assign values. We can imagine a variable to be a box. We give the box a name or label so that we can find it and refer to it when we need it. However, this is no ordinary box, it can stretch to hold anything from a single number or letter, to a sentence, a list of values or even an entire application spanning hundreds or even thousands or lines of code! In this instance we called our box 'name' and it contained a single word - your name.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;A quick note on 'white space' and comments&lt;/strong&gt; &lt;/p&gt;




&lt;p&gt;White space is all of the spaces and gaps in your code and they are ignored by Python. We wrote &lt;code&gt;name = "Simon"&lt;/code&gt; but we could equally have written &lt;code&gt;name="Simon"&lt;/code&gt; and Python would read both of these the same. Code is written using certain conventions which make it more human readable and allow others to more easily see and understand our code.&lt;/p&gt;

&lt;p&gt;Comments are denoted by a '#' symbol and anything written after this symbol for the remainder of the line is ignored by Python. Comments allow us to make notes in our code as a reminder to ourselves or to help explain what that part of the code is doing to anyone who reads it.&lt;/p&gt;

&lt;p&gt;Our code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# This is a comment - Python ignores this, it's just for us

name = "Simon" # Everything after the '#' is a comment
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What Python sees:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name="Simon"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Variables are one of the key building blocks we use when writing code. A simplified way of looking at a computer program would be to say that we are 'doing things with variables to produce some kind of result'.&lt;/p&gt;

&lt;p&gt;So, we created this &lt;code&gt;name&lt;/code&gt; variable and it contains your name. So where did it go? Python looked at this variable and has stored it in memory. For as long as your IDLE application is open on your device this variable will exist. When the application is closed everything held in that part of the memory will be lost. We can of course store data more permanently but that is a subject for another day. How can we check to see if Python has stored our name variable? Go back to IDLE and simply type the name of the variable - &lt;code&gt;name&lt;/code&gt; and press Enter. There is our name displayed on the screen! Python recognises the name of the variable and shows us the contents of the box.&lt;/p&gt;

&lt;p&gt;What if we now wanted to give &lt;code&gt;name&lt;/code&gt; a different value? Easy, we simply assign a new value with the '=' sign &lt;code&gt;name = "new name"&lt;/code&gt; and press Enter. If we now type &lt;code&gt;name&lt;/code&gt; and press Enter, we will see the new value has replaced the old value. Another way of showing the contents of our variables is to use &lt;code&gt;print()&lt;/code&gt;. We will get into exactly what &lt;code&gt;print()&lt;/code&gt; is later but for now just know that it will print to the screen (not your paper printer) whatever we place inside the brackets. For example:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feeb8yn3brrpaukeqfhbx.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feeb8yn3brrpaukeqfhbx.jpg" alt="IDLE" width="169" height="164"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Putting it all together&lt;/strong&gt;&lt;/p&gt;




&lt;p&gt;We now know what a variable is and how to create them, but what can we do with them? Variables aren't too exciting on their own, but what we can do with them is much more interesting. In the next part of the series I will introduce you to some of the things we can put into variables other than words as well as some ways we can interact with them. Until then, keep playing with IDLE (you can't break anything!). Try using &lt;code&gt;print()&lt;/code&gt; to display different variable names. &lt;/p&gt;

&lt;p&gt;Want a challenge? See if you can learn how to display multiple variables on the same line. Bonus points for figuring out how to put a space between the names).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;genus = "Pinus" # Declare these variables
species = "sylvestris"
print(#write your code here between the brackets)
# Output
Pinus sylvestris
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;Conclusion - the first step on the journey&lt;/strong&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;"The cool thing about being famous is travelling. I have always wanted to travel across seas, like to Canada and stuff." - &lt;em&gt;Britney Spears&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this first part of this series of articles, I wanted to write about a very important aspect of learning to code - why do it? Nearly all learning endeavours are destined to fail if we are not motivated to learn. Coding like most things is very difficult to learn if you are not interested in the subject matter. My aim with this series is simply to open your eyes to the possibilities and hopefully spark your imagination as to what can be accomplished. To this end I encourage you to look around, search online for 'python projects' and see the types of projects people are making and then think how you could use similar projects for your own work or studies. There are many great teaching resources out there and you would do well to try a few to see which one works best for you. In the meantime, thank you for reading and I look forward to seeing you in part two. &lt;/p&gt;

&lt;p&gt;Simon&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>python</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
