8 Basics Concepts of Programming in Python3

Licensed under the Creative Commons Attribution licence (CC-BY),
either version 4.0 or at your option, any later version. See:
https://creativecommons.org/licenses/by/4.0/

Author:Usmar A. Padow (amigojapan), amigojapan's homepage

Note: this document is aimed at those who ask "Where should I start programming?"

0. Sequentiality
1. Variables
2. Statements
3. Conditionals/blocks
4. Functions/Types
5. Input/output
6. Loops
7. Arrays/lists

Before we start you can use this link to run python code

0. Sequentiality/Following instructions in order
The first thing we need to learn in order to become a programmer is that instructions always follow a regular order, usually from top to bottom. For example:

  BrushMyTeeth()
  CombMyHair()
  GoToWork()
  
I will never go to or work before I brush my teeth and comb my hair...

  BrushMyTeeth()
  GoToWork()
  CombMyHair()
  
Well, the answer is that I would first brush my teeth, but I would get to work unkempt, which would cause trouble. That is why the order of the instructions in a program is so important… also because "computers are stupid” (I recommend watching this video) Which is another thing to keep in mind, with the previous script I just wrote, the computer will not intelligently know I should comb my hair before going to work. Computers are just not capable of such decision making at this level of programming. If you make a large program, and shuffle its instructions around, the program will surely not do what it was originally intended to do.

1.Variables
A variable is a place in the computer memory where some kind of value sometimes a string (some letters), sometimes a number is stored. Like the value 5 or the string "hello”. A variable can have a simple name like just the letter x or any combination of letters like last_name or social_security_number, but not spaces, last name is not a valid variable name. If we have a variable called social_security_number we could assign it the value 123458789 as a sample social security number. Variables as their name implied can vary, which seems to be different to the mathematical view on variables, in math if you say x=5 then x is always equal to 5, but in programming we can say x=3 and then x=5 and the value would first be set to 3 and then change to 5(These are called assignments in programming). In the case of a string, the value between the double quotes will be assigned to the variable, for example if we had last_name we could assign "Einstein” to it easily as follows: last_name= "Einstein”.

2. Statements
this may be the most difficult part to explain of programming, almost everything you see in a computer program is a statement, but can also appear as keywords such as while(). Lets talk about assignment statements. For example, lets take the following program

  x=3
  x=5
  x=x+1
  
What will be the result of such a program… Well, the first statement, x=3 will set x to 3, then the next statement x=5 will (maybe counter-intuitively to some) set x to 5, then the final statement x=x+1 we need to break down into its parts. We have the x on the left of the equal sign called an "lvalue” (the variable to the left of the equal sign) which is the same as the first x=3, where the x is what stores the value, then we have x+1, the value of x at this point of the program is 5 because it comes after x=5 so when we do x+1 it is the same as doing 5+1, and then finally we assign that to the lvalue, so at the end of the program, x will contain 6 which is 5+1. Other kinds of statements we will look at later in this text are things like function calls, return statements, conditional statements and boolean statements.

3. Conditionals/block of code
A conditional statement is a statement which give usually two different flow controls depending on wether the statement it is evaluation is true or false, for example: In order to explain conditional statements I am also forced to explain what blocks of code are. Firstly, here is an example in python:
x=5
  if x>3:
      print("x is more than 3")
      print("I wish x was less than 3")
  if x<3:
      print("this line wont get printed")
  x=2
  if x<3:
      print("x is less than 3")
  

download more_or_less.py

Lets go thru that program line by line. First it assigns 5 to x, then it checks if x is more than 3, since it is, it will go into the following "block of code" which starts when we add a tab or any number of spaces before entering our print statement(print is used in computers now because computers form the old age used to print their results on paper instead of a screen), as you can see, the following two lines of code both are "indented", which means they are a certain ammount to the right. This means both lines will be executed, and since x>3 is true, the print statements will be executed and the following text will display on the screen:

    x is more than 3
    I wish x was less than 3
  

Then the following line is executed if x<3:, since x is still 5, it means the statement x<3 is false, which means it won't execute the folloing print statement, so that line wont be printed to the screen. Finally we set x to 2. And next the if statement checks wether x<3 is true, which it is, printing out the text in that print statement. the complete output of this program is:

  x is more than 3
  I with x was less than 3
  x is not more than 3 
  


4. Procedures/functions
Now functions need to be broken down into 2 separate parts, the easy part which is a function call and the hard part which is a function declaration. In the beginning of this paper I used three function calls to say what I was telling the computer to do:

  BrushMyTeeth()
  CombMyHair()
  GoToWork()
  

Take the following program:
def calculate_tax(tax_type, ammount):
    if tax_type=="luxury":
        return ammount * 0.10
    else:
        return ammount * 0.08
  
  purse_tax=calculate_tax("non-luxury", 100)
  restaurant_tax=calculate_tax("luxury", 100)
  print("purse_tax is " + str(purse_tax))
  print("restaurant_tax is " + str(restaurant_tax))
  

download taxes.py

The output of this program should be this:

    purse_tax is 8.0
    restaurant_tax is 10.0
  

Function calls help us so we don't have to write the same code many times, for example, in this program we defined the way to calculate tax only once, but we did two function calls. The to calculate_tax function call, saving us from typing the same thing over and over, we could do 100 function calls to the same function and it would not increase the size of the program by much...

Now I will explain how a function is defined. First the keyword def is used, followed by the function name, function names follow the same rule as variable names, in this case our function name is calculate_tax.then an open parenthesis (then the "parameters", which are the things that change from function call to function call. They come in the form of variable names, in this case our parameters are tax_type and ammount. Then comes the function body, which in python is just a block of indented stuff as you can see this function body has the capability to give an 8 pecent tax for a non luxury item and a 10 percent tax to a luxury item. In our function calls we send the parameters to the function, and they get stored as variables of the name of the parameters. Finally there is the return statement. Which tells the program "send this back to the function call as the result". (Also note that return terminates the flow of the fucntion, no mroe operations occur ater return, and the flow of the program goes back to the function call) in this program, after return is called, it sets the lvalues of purse_tax and restaurant_tax. Finally this program prints out the values. These values are numbers so they need to be converted to strings before they can be printed using the print() statement. This is accomplished by surrounding the values with str().

5.Input/output

Now, here is the most simple program every programmer starts out with
print("hello world)
  


download hw.py

This is a simple example of "output"
Now lets try some input:
print("enter your name:")
  name=input()
  print("enter your last name:")
  lname=input()
  print("welcome to our program " + name + " " + lname + "!\n")
  

download greet.py

The output in my case after entering my name is as follows:

  enter your name:
  Usmar
  enter your last name:
  Padow
  welcome to our program Usmar Padow!
  


6. Loops
while Loops

A while loop is a loop that executed while a condition is true, and ends when the condition is false. Now let's get some example code:
cont=True
  while cont==True:
      print("continue? 1)Yes 2)No:")
      user_input=input()
      if user_input=="2":
          cont=False
  

downlad cont.py

Here is some sample output for this code:

  continue? 1)Yes 2)No:
  1
  continue? 1)Yes 2)No:
  1
  continue? 1)Yes 2)No:
  2
  


for loops. for loops are one of the most common kind of loops in programming. Here is some sample code:
sum = 0
  for counter in range(1,5):
      sum += counter
      print ("counter is " + str(counter) + " and sum is " + str(sum))
  

dowload for.py


The output of all of these programs is:

    counter is 1 and sum is 1
    counter is 2 and sum is 3
    counter is 3 and sum is 6
    counter is 4 and sum is 10
  
The for loop looks at the range given in range 1,10, it loops around setting the counter variable form 1 to 4(warning:even tho your range says 5 it will end at one less than the final number)

7. lists
A list is a data structure to hold data in order, This code contains comments, where anything after a # sign is a comment, and won't do anything in the program. Examine the comments on each line which has one to undertsand what the program does.
fruits=["banana","apple","peach","pear"] # create a list
  print(fruits[0]) # print first element of list
  print(fruits[3]) # print last element
  print("now reprinting all fruits")
  for fruit in fruits: # loops thru the fruits list and assigns each values to the fruit variable
      print(fruit) # prints current "iteration" of the fruit
  print("now reprinting all fruits in reverse")
  fruits.reverse() # reverses the list
  for fruit in fruits:
      print(fruit)
  print("now printing fruits in alphabetical order")
  fruits.sort() # sorts the list in alphabetical order
  for fruit in fruits:
      print(fruit)
  

download fruits.py
The output for this code will look like this:

  banana
  pear
  now reprinting all fruits
  banana
  apple
  peach
  pear
  now reprinting all fruits in reverse
  pear
  peach
  apple
  banana
  now printing fruits in alphabetical order
  apple
  banana
  peach
  pear
  
An "index" in programming list is a number that points to the element of the list that we want to retreieve. One thing I want to point out is that fruits[0] points to "banana" cause lists in python are "zero indexed" which means the list starts at 0, not at 1(just like the index of this tutorial). Ok, I think if you grasped this you have grasped the very basics of python, you should now be able to go on to taking the tutorials at the python pages or other sites. Here is the link to the python official tutorial.

This document was originally written in 2017 for python2 and C. Modified in 2022 to be python3 only.