Python Basic Structures

Now that you're probably quite familiar with variables and operators, it's time to get into more depth. In this section, you'll learn how to manipulate flow control statements to improve efficiency and quality results.

IF - ELIF - ELSE Statement in Python

This is the most basic structure you should know. "If statements" control the general behaviour of the script. When you have some variables and you want to execute an action which depends on some variable's content you apply IF/ELIF/ELSE. Example: You enter a store with 5$ and you want to buy a soda. There is no cost stamp on it. So you have to assume that is less or equal to 5$ in order for you to buy it. If it's more, you won't be able to purchase it. Go ahead open Python IDLE and press CTRL + N to create a new script. Save it as test.py and head back to edit it. Now HOLD.

Basic Syntax

if ( operation ):
      .....execute some code.....
elif ( operation ):
      .....execute some code.....
else:
      .....do something else.....

OR

if ( operation ):
      .....execute some code.....
else:
      .....do something else.....

Analysis

So let's note what we have and what we know. (Known Data Set) We ask the seller about the price of the soda. Assume soda's price is 2.5$.
  • We have a budget of 5$. So let's make a variable budget = 5. Makes sense, right?
  • We know the price of the soda, which is 2.5$. So let's make another variable soda = 2.5.
  • We know that we can buy the soda only if its price is less or equal to five dollars.
Let's see what kind of script we can make with the existing data set:

budget = 5
soda = 2.5
if (soda <= budget):
      print "You can buy the soda."
else:
      print "Sorry! You're going to need more money."

Important Note: Indentation is an important syntax rule in Python. The spaces I make before the print statements must be EQUAL. Head back to the documentation and read about it.

A slightly different example...

budget = 5
soda = 2.5
if (soda < budget):
      print "You can buy the soda."
elif (soda > budget):
      print "Buy something cheaper."
else:
      print "Sorry!"

Copy one of them and try to experiment around. Change the budget or soda to whatever number you like, edit the operation and see what the output will be. RUN your code by pressing F5 or by choosing Run > Run Module.

exercise-icon Try it!

Declare a variable num and set it to 50. Now we want you too check if that variable is smaller than 20. If it is print "Num is smaller than 20". If it isn't, you should print "Num is way larger".



?

exercise-icon Extras - Input() & Raw_input() usage - Python

If operating python 2, when an input from the user is required, you can use the input('your message') to ask from the user to enter a number value. When you want the user to enters a string type value, e.g. name, lastname, nickname, etc... you can use the raw_input('your message') function. Examples bellow:

>>>   age = input('Enter your age: ')
Enter your age: 34
>>>   print age
34

>>>   name = raw_input('Enter your name: ')
Enter your name: Bishop
>>>   print name
Bishop

Python 3 has dropped the raw_input() function and has replaced both with just the input(). To get a string from the user, we just need to replace the raw_input() from above with plain input(). To obtain an integer from the user, we make a conversion during the input() with the int() function. The above "input" paradigm, will be replaced with int(input('your message')). Int() converts anything inside its parenthesis to integers. If we enter int(2.3532), it will spit out the number 2. Makes sense, right?. Examples:

>>>   age = int(input('Enter your age: '))
Enter your age: 34
>>>   print(age)
34

>>>   name = input('Enter your name: ')
Enter your name: Bishop
>>>   print(name)
Bishop

NOTE: Observe that, in Python 3, the print function is also changed. In order to print anything, you need to use parenthesis. "Print(name)" is good. "Print name" isn't allowed.


Loop Statements - FOR loop in Python

Loops are used for repeating a certain set of actions, when there are multiple inputs given from the user, when we need to print something with known limits, make estimations or construct a series of outputs and sequences. Example: Suppose we have been asked to print a sequence from 1 to 10. If we'd use a conventional command multiple times we'd had waste of memory and functionality rates would go down quick. If we use a looping structure we can accomplish that with just two lines of code. Observe:

>>>   for item in range(1, 4):
      print item
  1
  2
  3



We set an item variable (inside the for loop) in order to spot each value in the loop, and use the function range( start, end ) to set the initial and limit values for our iteration. Since we start from 1, the ending value will be the 'end-1'. We start from 1, 4-1=3, and will print everything till 3. You don't have to declare the item var to anything in particular, before the loop. It's working without initialization. "For" loops are used generally for known number of iterations. Bellow you can see why isn't so functional to use repeated commands instead of loops.

>>>   print 1
>>>   print 2
>>>   print 3

exercise-icon Try it!

Write a for loop structure which prints all numbers from 1 to 6. Inside the for loop declare the variable sample and called it afterwards in the print function. Good luck developer!




?

WHILE loop in Python

Now that we've introduced the for loop and hopefully understood it, we need to jump into a more complex type called a 'while' loop. We use 'while' loops when we can't estimate or measure exactly how many iterations will take place when running our script. Example: We have been asked to develop a security application which during start asks the user for a password. This action can be implemented using that particular kind of loop.

Basic Structure

while ( operation ):
      ....execute some code....

Validation Example

>>>   command = str()
>>>   while command != 'quit':
          command = raw_input('Enter command: ')
Enter command: what
Enter command: wait
Enter command: ey..
Enter command: quit

See if you can understand what happens here. I'll give some clues. We have a command variable set it to a string type using the str() function. Afterwards, we initiate a loop saying that while the command is different from 'quit', ask the user to retype a new command. When the answer is 'quit', (this is when we enter 'quit' to the raw_input()) the iteration will be terminated, as shown above. I encourage you, to open up a script file and experiment with something similar.

exercise-icon Try it!

Declare a variable named apples and set it to int(). Write a 'while loop', similar to the previous example. When the user inputs a number of 9 into the apples variable, the process will be terminated. Inside the input() function use the following message "Please enter number of apples: ".





?

Try - Except Structure

This particular structure is been used for error handling. Suppose we have a function which contains two variables. Let x = 45 and y = 0. Afterwards inside the function we're attempting to divide x with y. We know from college algebra that division by zero is not possible. Python will raise an error called "ZeroDivisionError". 'Try and Except' structure allows us to handle that error and display something on the screen. Example.

>>>   x = 45
>>>   y = 0
>>>   try:
        z = x / y
except ZeroDivisionError:
        print 'Division by zero isn't allowed.'
else:
        print z

exercise-icon Try it!

Write a 'try-except' structure.Declare a variable num = int() Inside the 'try' ask the user to input a number using input('Enter a number: '), assigning the value into the num variable. Afterwards, enter the exception NameError and finally, if that error occurs, print a message 'You did not input the right type of value'. (Please use only one kind of quotes when writing code)




?

Let me explain what happens here. If we enter the example into the IDLE and run it, will have been asked to pass a number. Remember that we've set the num to an integer type. Let's say, I'm passing a string 'MyName'. Python raises a NameError, which means that I've entered a wrong value type, which is True!.

Since we've used excpetion, we're not going to see the error displayed to the screen by the IDLE, instead will use our own message to point us the error. ('You did not input the right type of value'). Everything good? Hope so! It's not that complicate right?


exercise-icon Pop Quiz

1. Declare a variable age = 25. (Use single quotes!) Write an if statement which examines the following cases: If age is larger than 18, print 'Kyle is an adult', else if (elif) age is smaller than 18, print 'He is still a minor' otherwise print 'Who is the guy?'. No need to use parenthesis with the if statement. (Just write if var = ....).

2.Write a For-loop to print out all the numbers from 5 to 20. Use an 'i' variable.

3.Declare a variable Name = str()and write a While-loop which will ask the user to enter a Name via raw_input('Enter a name: ') storing it into the Name variable, and when the name 'Josh' is entered will then terminate the loop process.

4.Declare a variable parser = float(). Use Try-Except to let user pass a value using input('Enter value: ')function and store into parser. Add an exception for again a NameError, displaying a message 'You can not trick me anymore!'.






?
python.org | Contact Me | © ksoftware.eu 2016