Diving deeper - Python Tutorial #2

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@fancybrothers·
0.000 HBD
Diving deeper - Python Tutorial #2
<html>
<p>Welcome everyone to the second article in my Python journey. In the last post I showed you how to install Python, basic input and output functions and some basic types of data (We talked about<strong> Integers</strong>, <strong>Floats</strong>,<strong> Strings</strong>, <strong>Lists</strong> and <strong>the Boolean type.) </strong>If you missed the first part, you can find it <a href="https://steemit.com/steemstem/@fancybrothers/your-starting-point-python-tutorial-1">here</a>, I highly recommend checking it out if you haven't already. With that out of the way let's get started ... &nbsp;</p>
<p><img src="https://cdn.steemitimages.com/DQmSZgXejA6QpRoNKK3bzqf1R1jyPRMYHr1FTDdbYMdkzSp/cover.jpg" width="800" height="480"/></p>
<p>In the last post I gave you this small challenge:</p>
<blockquote>&nbsp;Write a program in which the user is asked to write five numbers, then the program calculates the sum of each two of those five numbers, adds them to a list and then finally displays the list.&nbsp;</blockquote>
<p>Here's my solution:</p>
<pre><code>##Input<br>
Number1 = input('Insert The first Number: ')<br>
Number2 = input('Insert The second Number: ')<br>
Number3 = input('Insert The third Number: ')<br>
Number4 = input('Insert The fourth Number: ')<br>
Number5 = input('Insert The fifth Number: ')<br>
<br>
##Converting Strings Into Numbers<br>
Number1=float(Number1)<br>
Number2=float(Number2)<br>
Number3=float(Number3)<br>
Number4=float(Number4)<br>
Number5=float(Number5)<br>
<br>
##Calculating and Adding<br>
Tab=[]<br>
Tab.append(Number1+Number2)<br>
Tab.append(Number1+Number3)<br>
Tab.append(Number1+Number4)<br>
Tab.append(Number1+Number5)<br>
Tab.append(Number2+Number3)<br>
Tab.append(Number2+Number4)<br>
Tab.append(Number2+Number5)<br>
Tab.append(Number3+Number4)<br>
Tab.append(Number3+Number5)<br>
Tab.append(Number4+Number5)<br>
<br>
##Output<br>
print('Voila! ',Tab)</code></pre>
<p>Here's the result:</p>
<blockquote>Insert The first Number: 5<br>
Insert The second Number: 7<br>
Insert The third Number: 3<br>
Insert The fourth Number: 17<br>
Insert The fifth Number: 12<br>
Voila! &nbsp;[12.0, 8.0, 22.0, 17.0, 10.0, 24.0, 19.0, 20.0, 15.0, 29.0]</blockquote>
<p>In the input part, we are simply asking the user to enter 5 numbers which we are going to store in different variables (Number1, Number2...). Then, we are going to convert them into floats (or integers) because as I said in the previous post the input function stores the user's input into a string variable, for now, we have to go through them one by one. Now, we have to make an empty table and add to it all the necessary numbers using the append method which adds a certain number to the chosen table to the right, again one by one. Finally, we use the print function to display the table to the user. As you can see, this program is much more complex then it should that's why in today's post we are going to be talking about loops (control structures) and user-defined functions.</p>
<hr>
<center><h1>The If Statement</h1></center>
<hr>
<p>Unlike other programming languages, Python uses blank space at the beginning of each line (3 spaces to be exact) to define the blocks of code. The<strong> if</strong> statement is used to carry out a block of codes called statements only when a certain condition is met. Python also allows you to use an <strong>if</strong> statement inside another one. You can also include an<strong> else</strong> statement after an <strong>if</strong> statement in which you tell the program what to do if the condition isn't met. If there is no <strong>else</strong> statement and the condition chosen isn't met the program will simply jump/skip the block. There is also the<strong> elif</strong> statement which as you might have guessed is short for else if, this statement is used to define another condition. Before the example, I got to remind you to use two equal signs to define a certain condition because as we saw in the last post, one equal sign is used to declare a variable or change it. Alright, let's get to the example...</p>
<pre><code>choice = input("Write N for the number game or W for the word game: ")<br>
if choice == 'N':<br>
 &nbsp;&nbsp;num = int(input("Choose a Number: "))<br>
 &nbsp;&nbsp;if (num%2) ==0 and (not num==6):<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(num,' is an even number')<br>
 &nbsp;&nbsp;elif num == 6:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('6 is an even number but if you rotate it 180 degrees it becomes 9 ... Huh that\'s odd')<br>
 &nbsp;&nbsp;else:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print(num,' is an odd number')<br>
elif choice == 'W':<br>
 &nbsp;&nbsp;&nbsp;word = input('Choose a word: ')<br>
 &nbsp;&nbsp;&nbsp;word2 = input('Choose another word: ')<br>
 &nbsp;&nbsp;&nbsp;if word[0].upper()==word2[0].upper():<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('Your words start with the same letter, therefore they are alliterating words')<br>
 &nbsp;&nbsp;&nbsp;elif word[-1].upper()==word2[-1].upper():<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('Your words end with the same letter')<br>
 &nbsp;&nbsp;&nbsp;else:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('I couldn\'t find a connection, yet ...')<br>
else:<br>
 &nbsp;&nbsp;&nbsp;print('Error!')</code></pre>
<p>To demonstrate everything I talked about, I made a program which consists of two small subprogrammes  (the number game and the word game). First, we have to ask the user to choose which part of the programme he wants to use, to do that, I used the input function to ask the user to chose either 'N' or 'W' which then I stored inside a variable called choice. Next, I used the if statement to basically tell the program which part to run based on the user's choice. The number program is pretty straightforward, you ask the user to choose a number and then determines if it's odd or even using the module which, as I showed you in the last post, you can 'define' using the percentage symbol (%) and if it's a 6, the program will print a small 'joke' (I had to add a different from 6 condition because the program have to run the conditions one by one).
The word program, on the other hand, is a bit more complex. The program shows if the two words given by the user start or end with the same letter. To do that, I used this code word[0].upper() which applies the upper module on the first letter of the word string and word[-1].upper() which applies the upper module on the last letter of the word string. In both programs, I used the If, elif and else statements to assign each output to certain conditions.</p>
<p><center>Note: The .upper() module is used to change a letter into uppercase, if you use it on a number, a special character, a symbol or an uppercase letter it will stay the same.</center></p>
<hr>
<center><h1>The While Loop&nbsp;</h1></center>
<hr>
<p>A <strong>while </strong>statement is like an endless <strong>if </strong>statement, you choose a condition and the codes inside of it are repeatedly executed until that condition is<strong> False. </strong>The <strong>while</strong> loop is really useful but you can easily fall into an &nbsp;infinite loop that keeps on running forever because the condition is still <strong>True.</strong> Here's an example of an infinite loop:</p>
<blockquote>while not 5==8:<br>
 &nbsp;&nbsp;print('I am struck')&nbsp;</blockquote>
<p>There are two statements which you can use to easily control these loops: the <strong>break</strong> and <strong>continue</strong> statement which are used to terminate the loop or to start it back from the top, respectively. Using these statements outside the loop causes a certain error (SyntaxError: 'break' outside loop). Here is an example:</p>
<pre><code>choice = 'repeat'<br>
while choice == 'repeat':<br>
 &nbsp;&nbsp;&nbsp;j = 0<br>
 &nbsp;&nbsp;&nbsp;while not j == 5:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('I am stuck')<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;j+=1<br>
 &nbsp;&nbsp;&nbsp;i = 1<br>
 &nbsp;&nbsp;&nbsp;choice2 = input('Would you like to repeat: ')<br>
 &nbsp;&nbsp;&nbsp;if choice2.upper() == 'YES' or choice2.upper() == 'CONTINUE':<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;i=0<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;continue<br>
 &nbsp;&nbsp;&nbsp;elif choice2.upper() =='NO' or choice2.upper() =='STOP':<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;i=0<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break<br>
 &nbsp;&nbsp;&nbsp;else:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('Error! Please try something else')<br>
print('Out of loop')</code></pre>
<p>At the start of the program, I assigned a string ('repeat') to a variable called choice. This variable is a sort of an on/off button, the program will keep running endlessly until its changed. To start the loop I already set it to 'repeat'. Next, I used the while statement and the condition needed. I wanted the loop to display the 'I am stuck' message 5 times so instead of typing print multiple times I used another while statement and a variable called j which I used as a counter. This variable starts at 0 and each loop I add one to it until it reaches 5 at which point the loop stops. (j+=1 is the same as j = j+1). Now, the program will ask the user if he wants to stop the loop. To make the program more efficient, I planted another while loop which will only stop if the user enters a correct answer using a variable called "i". I also used the upper module to avoid 'case problems'.</p>
<hr>
<center><h1>User-defined Functions</h1></center>
<hr>
<p>We talked a lot about Python's pre-defined functions. Today I am going to show you how to create your own functions. To do that, we use a statment called def to create a sort of subprogramme that we will call when we need it. Your subprogramme could even retern values, to do this you have to use the <strong>return</strong> statment. Here is an example in which the function I defined prints a message (In this case, we don't need the return statment)
<pre><code>def even(x):<br>
 &nbsp;&nbsp;&nbsp;if x%2 == 0:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('True')<br>
 &nbsp;&nbsp;&nbsp;else:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('False')<br>
<br>
even(2)<br>
even(5)</code></pre>
<p>The result:</p>
<blockquote>True<br>
False</blockquote>
<p>Now Here's an example in which we return a simple value (string)</p>
<html>
<pre><code>def even(x):<br>
 &nbsp;&nbsp;&nbsp;if x%2 == 0:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;num = 'Even'<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return num<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;print('Hi')<br>
 &nbsp;&nbsp;&nbsp;else:<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;num = 'Odd'<br>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return num<br>
Number = 73<br>
print(even(Number))</code></pre>
<p>Result:&nbsp;</p>
<blockquote>Odd</blockquote>
<p>As you can see, in the first program the even function prints 'True' or 'False' depending on the number entered. On the other hand, in the second program, the even function acts as a variable, therefore, you need a print function to display its value. </p>
<center>Note: In the second case, the program didn't display the 'Hi' message because the return statement will always end the function.</center>
<hr>
<p>The next challenge is pretty easy: You have to rewrite the same challenge using while and if statments to make it more 'compact'. Also users can define how much numbers they want to write</p>
<p>Thanks for reading and have a nice day :)</p>
<hr>
<h1><strong>Image Credit:</strong></h1>
<p>The Python logo in the thumbnail is <a href="https://commons.wikimedia.org/wiki/File:Python-logo-notext.svg">from Wikimedia</a></p>
<h1><strong>Useful links for further reading:</strong></h1>
<p><a href="https://www.codementor.io/kaushikpal/user-defined-functions-in-python-8s7wyc8k2">User-defined Functions</a></p>
<p><a href="http://gsl.mit.edu/media/programs/sri-lanka-summer-2011/materials/t-l03.pdf">Python Control Structures (PDF)</a></p>
<p><a href="https://wiki.python.org/moin/WhileLoop">While Loops</a></p>
<p>&nbsp;&nbsp;One more thing, Join the <a href="https://steemit.com/@steemstem">@steemSTEM</a> community, A community project to promote science technology engineering and mathematics postings on Steemit.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>
<p><center><img src="https://steemitimages.com/DQmeJgsbM5K3pUC8kPBToDKRxE2gijUXvgvX6oUiBgaaiyk/atom.gif" width="640" height="280"/></center></p>
</html>
👍 , , , , , ,