Now that we have a Python Interpreter running in our machine,
all we have to do is to set ablaze our journey into Python programming.
Writing "hello world" program
It's been the culture of programming to produce the phrase Hello, World! ever since the birth of
In python, typing the phrase "Hello, world!" is just as simple as pronouncing it, spanning only one line of code.
Now, let us see if we can do that in a blink of eye with Python:
On your machines, open the Console, or Terminal, or CMD or whatever you call it, and type the code below:
This will open and start the python interpreter with the version being the python you are running on your machine.
Having the Shell started, type the python code below to sniff a smell of "Hellow world" in Python: >>> print ("Hello, World!")
This shall do it, printing "Hello, World!" to the console, and hence we are done! The actuall console shall look like this:
At this point in time, let's take a look at some fast runnings with python...
Running Python In a File
If you have a coding background from another programming language though,
I suggest you've already noticed that running python directly from the Shell is just inconvenient,
as you've got to type the very similar code every time you need to run it,
plus you have a difficult approach to improve or add some more features to your code.
In this snippet, lets try to reproach this behaviour.
To prevent this, we need to run our code from the file, so next time we need to run python, we just need to call the file;
and or whenever we need to add more features to our code, we just edit the file and hence we're good on our way.
Create the file, using your favourite text editor...
that may include Notepad, Notepad++, Sublime etc.
Add the python code you want to run,
— In this case print("Hello, World")
Save your file under the file extension .py;
— That is anyname.py
Navigate to the folder that you saved your file;
— In linux, you may use command: $ cd ~/foldername
Once in the folder, where the .py file is stored, type the following command in your console:
$ python filename.py
and the text Hello, World! shall too appear in the console.
Reference the image below in mysite folder, /home/usr/mysite
Variables, Strings and Numbers
A Variable is a container for holding our data; It can be Numbers, Strings(texts) and other datatypes..
Declaring a variable in python is a matter of providing a variable name, and the assigning of the variable value (content).
Below is a fully working python variable with string contained in it as its value. >>> name = "Amin"
As can be seen from the above code,
python variables are not explicitly declared (set) as to what type of data they're gonna hold. In fact, this is a natural thing in python.
Strings Strings are just the actual texts that we use in everyday communication, quoted in single or double quotation marks ("" or '');
Declaring a string variable in python works as in this examples:
>>> doubleString = "This is a double quoted string!"
>>> singleString = 'This is another single quoted string!'
String can be indexed, that is naming the positioning of items, and pick any character(s) that we would like to use ;
The indexing in any language starts from 0, that is, reading of the string characters start from 0;
Therefore, in the string variable above, a letter 'T' in the text 'This...' is on doubleString.
To slice our string variable above, especially the 'i' in 'is' word, we can do as follows: >>> print (doubleString) # i
We can also tell where we want to start and end, eg: >>> print(doubleString[5:7]) # is Numbers
In python programming, Numbers are just the real world numerical digits that we use in daily calculations.
They are the Integers, Floating Point Numbers and Complex Numbers.
The Integers range from 0 to any profile non-decimal number; the Floats has the decimal point,
and the Complex has the imaginary part: They are in a form 9+3j where 9 is a real number, and 3j is an imaginary part.
Below is the asignment of python numbers and their usage:
We can however do mathematical calculations with the numbers above using different mathematical operators:
"+" for addition, "-" for subtraction, "*" for multiplication and "/" for division.
Here we go:
In python, Lists would be described to be as it sounds... It's just a group of data, seperated by commas, contained in square brackets!
Lists in other programming languages, especially C Family would be called Arrays
A list can be declared by setting open and close square brackets, and all the data seperated by comma goes between them.
Below is how we could use Python Lists:
Just as we did with the strings, lists can be indexed / sliced too. we can achieve slicing in the above lists variable as: >>> print(lists) # me Tuples
By design and functionality, python tuples are like list with small differences posed between them.
Python Lists use square brackets while Tuples use Paranthesis ( )
Python Lists can be manipulated, I mean reassigned or changed, where as tuples can not.
Python Tuples support indexing too... and you can use the techniques we did above to slice the Tuples.
given we have a shop order of different fruits; we would take down our order as:
>>> fruits = ("bananas","oranges","lemons","mangoes")
We can slice this fruits as in below code:
>>> print (fruits) # lemons
Python Inputs and Outputs
Every programming language has it's method for recieving data for internal processing and outputing the processed information to the user.
Python is not excluded however, in this trending fun... Input
To input data in python is just as easy as it sounds in english. All you need to do is to tell python to do exactly that, in plain English,
followed by some hint to the user on what you want him/her to enter, in paranthesis quoted string.
Action speaks louder than words; let's take a look on the code below:
>>> name = input("what is your name?")
The code above will come with a line asking the user what his name is, at the same time allowing him to enter text from the keyboard! Output
We are lucky that we can take the data from user, But it is also important to remember to give him back what he has given us, wee-processed.
In the below code, the user's name will be shown back to the user via standard output, which is a console in this case,
with greetings targeting exactly to him/her.
>>> name = input("What is your name?") # Amin >>> print("Hello "+name) # Hello Amin
In the above snippet, the program asks the user for his/her name; and suppose the user entered the name Amin
The program, then, greets the user... in this case, by saying Hello, Amin
Our code, by for now has been running as smooth as it would against all odds,
but we still can't be able to control which part of the code we want to be executed whenever we want it to.
We can do so by using the program controls. The IF condition will help us to control our code in this case,
especially using the comparison operators. We will see the operators in the next section,
but for now, we will use == equality comparison operator, which checks if the two objects are simillar.
Don't be offended if you can't this operator thing for now, just remember it compare two items, if they are equal.
Taken our fruits list above, we can control which fruit should be shown based on our preference.
Observe the code below:
>>> fruits = ["bananas","oranges","lemons","mangoes"] >>> if fruits == "oranges":
... print ("The second fruits required are orange!") #The second fruits required are oranges
This will ensure that only if, the fruit on the index 1, which is the human count of 2,
is oranges, then it should tell that the fruits needed next are oranges; otherwise it should do nothing.
What if we want to re-run the very same bunch of code as to the number of our choice?
Leave that to me - it's under my control, otherwise you will fill your console or file with a bunch of tomato codes :)
To solve this problem, then it is perfect time when functions are called into the stage!
A function, also called methods, though not truly, is the collection of codes to achieve a specific computing process!
Taken an example we want to build a house, then we would need brick laying,
we will involve the buying of iron sheets, ceilings etc untill our house stands as a whole.
The same also happens exactly with functions...
In python, we declare a function using a keyword def, followed by function name,followed by paranthesis ( ),
and then the colon (:)
The code below is perfectly true declaration of a python function. def functionName():
Using the python's function feature, our "Hello, World!" thing, would be called as:
>>> def hello (): ... print ("Hello, world!")
Now, we could simply call our function as follows:
>>> hello() # Hello, World!
Good job! Last concept to be covered in this article of ours is loops.
A loop is a group of code that keeps repeating so long as a specific condition remains true.
There are many conditions in Python, and we will look into those, in the coming lessons.
The loop keywords in python are: for which keeps repeating for the item being in true condition,
and the while loop, which keeps repeating while the condition is true.
The use of for differs drastically, but one of which would be:
>>> name = "Amin" >>> for letter in name: ... print(letter)
In programming, a keyword is a word preserved by the programming language for internal use.
The keywords in Python are :
All the keywords above are preserved by python... They can't be used for variable names, functions or classes.
In the next lessons, we will look into this topics and more in details...