Getting Familiar with Python basics
Hello, I hope you successfully installed python if not you can do that with little help here. In this article, we are going to get familiar with python and look at the following:
- Types ( int, String, Boolean, float)
- Using text editors eg vscode, sublime text
- How to run python files
Let us get started, fire up your terminal or CMD if you are on windows( search CMD on windows and Terminal on Linux and mac). Type python and enter. You should see the following.
You can now write some python code here. Let's try adding 1 to 1.
symons@symons-macbookair:~$ python Python 2.7.17 (default, Nov 7 2019, 10:07:09) [GCC 7.4.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1+1 2 >>>
As you can see the result is 2. Our python is working!
Variables are memory name we use to hold data that can be manipulated later. For example, you want to store 30, 40 and their sum. We can store them in 3 memories num1, num2 and ans.
In python, you don't declare variable instead you just assign a value to it. eg
num1 = 30 . Let's create three variables and assign them the values above
symons@symons-macbookair:~$ python Python 2.7.17 (default, Nov 7 2019, 10:07:09) [GCC 7.4.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1+1 2 >>> num1 = 30 >>> num2 = 40 >>> ans = num1 + num2 >>> ans 70
As you can see the value of ans is 70 which is the sum. We can also alter the values of variables, for example, lets change value of num1 to 50
>>> num1 30 >>> num1 = 50 >>> num1 50 >>> ans = num1 + num2 >>> ans 90 >>>
Hope you got the concept of variables,
Every value in Python has a datatype, most frequently used are Numbers, List, Tuple, Strings, Dictionary. We will look at each of these in the next posts but let's look briefly on Strings
Strings are surrounded either single quotation marks or double quotation marks. "simon" is the same as 'simon'
Assigning strings to a variable is similar to int but we surround the value with quotes.
>>> name = 'simons' >>> name 'simons' >>>
We use the + operator to concatenate, or combine, two strings.
>>> fname = 'simon' >>> sirname = 'ombori' >>> full_name = fname + sirname >>> full_name 'simonombori'
We will learn more about strings after looking at methods.
You must have been asking yourself if we will be coding on Terminal forever, no we will use a text editor or IDE that makes our work easier and allows for multiple lines. You can download any of your choice, Personally I'm using visual studio code.
Let's see how we can run python files
- Create a folder called practice
- Open the folder with your text editor
- create a file inside that folder and name it test.py
- have something inside test.py
name = 'simons'
Save and open terminal cd into the new folder where the test.py is.
symons@symons-macbookair:~/Desktop/practice$ python test.py simons
And that is how you run python files.
bye and see you soon.