Diving deeper - Python Tutorial #2

in #steemstem7 years ago

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 Integers, Floats, Strings, Lists and the Boolean type.) If you missed the first part, you can find it here, I highly recommend checking it out if you haven't already. With that out of the way let's get started ...  

In the last post I gave you this small challenge:

 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. 

Here's my solution:

##Input
Number1 = input('Insert The first Number: ')
Number2 = input('Insert The second Number: ')
Number3 = input('Insert The third Number: ')
Number4 = input('Insert The fourth Number: ')
Number5 = input('Insert The fifth Number: ')

##Converting Strings Into Numbers
Number1=float(Number1)
Number2=float(Number2)
Number3=float(Number3)
Number4=float(Number4)
Number5=float(Number5)

##Calculating and Adding
Tab=[]
Tab.append(Number1+Number2)
Tab.append(Number1+Number3)
Tab.append(Number1+Number4)
Tab.append(Number1+Number5)
Tab.append(Number2+Number3)
Tab.append(Number2+Number4)
Tab.append(Number2+Number5)
Tab.append(Number3+Number4)
Tab.append(Number3+Number5)
Tab.append(Number4+Number5)

##Output
print('Voila! ',Tab)

Here's the result:

Insert The first Number: 5
Insert The second Number: 7
Insert The third Number: 3
Insert The fourth Number: 17
Insert The fifth Number: 12
Voila!  [12.0, 8.0, 22.0, 17.0, 10.0, 24.0, 19.0, 20.0, 15.0, 29.0]

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.


The If Statement


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 if 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 if statement inside another one. You can also include an else statement after an if statement in which you tell the program what to do if the condition isn't met. If there is no else statement and the condition chosen isn't met the program will simply jump/skip the block. There is also the elif 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...

choice = input("Write N for the number game or W for the word game: ")
if choice == 'N':
   num = int(input("Choose a Number: "))
   if (num%2) ==0 and (not num==6):
       print(num,' is an even number')
   elif num == 6:
       print('6 is an even number but if you rotate it 180 degrees it becomes 9 ... Huh that\'s odd')
   else:
       print(num,' is an odd number')
elif choice == 'W':
    word = input('Choose a word: ')
    word2 = input('Choose another word: ')
    if word[0].upper()==word2[0].upper():
        print('Your words start with the same letter, therefore they are alliterating words')
    elif word[-1].upper()==word2[-1].upper():
        print('Your words end with the same letter')
    else:
       print('I couldn\'t find a connection, yet ...')
else:
    print('Error!')

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.

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.


The While Loop 


A while statement is like an endless if statement, you choose a condition and the codes inside of it are repeatedly executed until that condition is False. The while loop is really useful but you can easily fall into an  infinite loop that keeps on running forever because the condition is still True. Here's an example of an infinite loop:

while not 5==8:
  print('I am struck') 

There are two statements which you can use to easily control these loops: the break and continue 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:

choice = 'repeat'
while choice == 'repeat':
    j = 0
    while not j == 5:
        print('I am stuck')
        j+=1
    i = 1
    choice2 = input('Would you like to repeat: ')
    if choice2.upper() == 'YES' or choice2.upper() == 'CONTINUE':
        i=0
        continue
    elif choice2.upper() =='NO' or choice2.upper() =='STOP':
        i=0
        break
    else:
        print('Error! Please try something else')
print('Out of loop')

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'.


User-defined Functions


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 return statment. Here is an example in which the function I defined prints a message (In this case, we don't need the return statment)

def even(x):
    if x%2 == 0:
        print('True')
    else:
        print('False')

even(2)
even(5)

The result:

True
False

Now Here's an example in which we return a simple value (string)

def even(x):
    if x%2 == 0:
        num = 'Even'
        return num
        print('Hi')
    else:
        num = 'Odd'
        return num
Number = 73
print(even(Number))

Result: 

Odd

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.

Note: In the second case, the program didn't display the 'Hi' message because the return statement will always end the function.

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

Thanks for reading and have a nice day :)


Image Credit:

The Python logo in the thumbnail is from Wikimedia

Useful links for further reading:

User-defined Functions

Python Control Structures (PDF)

While Loops

  One more thing, Join the @steemSTEM community, A community project to promote science technology engineering and mathematics postings on Steemit.      

Sort:  

WARNING - The message you received from @erudire is a CONFIRMED SCAM!
DO NOT FOLLOW any instruction and DO NOT CLICK on any link in the comment!

For more information about this scam, read this post:
https://steemit.com/steemit/@arcange/phishing-site-reported-steem-link-premium

If you find my work to protect you and the community valuable, please consider to upvote this warning or to vote for my witness.

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by Fancybrothers from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.