Introduction to Modern Python.
Tags: programming, python, beginners, help
Published: 2022-02-11 21:58:38

Python is one of the most popular programming languages that is sought after for jobs by employers. Python is powerful, easy to use and beginner-friendly. This article introduces the reader to basic concepts that they require to know in order to get started programming with Python.

## Fun fact 
_Python was developed by Guido van Rossum in the late 1980s._
_Guido van Rossum was reading scripts from a BBC comedy series known as "Monty Python's Flying Circus"._
_He wanted a name that was short and unique, hence he named the language Python._

**Installing Python**
Visit www.python.org to download and install the latest python version. Python 3 is best for beginners since it is being actively maintained and supported by Python.

**Install a text editor**
Visit https://www.python.org/about/gettingstarted/ to learn about which text editor and IDE is best for beginners in Python. You can download and install PyCharm community version at https://www.jetbrains.com/pycharm/download/#section=windows, or Visual Studio Code at https://code.visualstudio.com.

**Creating your first python program**
1) Open your IDE and select 'create a new project'.
2) Choose a location for your project and an interpreter.
3) Click on create.
4) Right-click on 'File' then click on 'New'>'Python File' and give it a name ,say 'Pyth' then click 'Ok'.
5) We can begin by writing a basic Python program, the Hello World! program. We do this by typing in 

```
print('Hello World!')

```
6) Go to the 'Run' menu and select the 'Run' button in order to run your program.
7) At the bottom of the screen, you should be able to see

```
Hello World!
```
8) Congratulations, you have written your first Python program!
Check out the tutorial at https://realpython.com or https://www.guru.com for these steps.
Also check out https://www.youtube.com/watch?v=_uQrJ0TkZlc for beginner-friendly YouTube videos.

**Program**
A program refers to the lines of code that give the computer the instructions to be executed.

**Console**
The console is where Python outputs the code. The program is executed in order, from top to bottom.
We use `print` statement to execute instructions in Python e.g 

```
print('Hello World')

```

**Receiving input**
We use `input` to read values from the terminal window.

```
first_number = input('Enter your first number: ')
print(first_number)
```

**Comments**
Comments are added using hash character `#`.They can be used to make the code more readable by explaining the code.
**<u>NOTE</u>**
Python does not execute comments.

```
#anything after this hash character is a comment.
```

**Keywords**
Keywords are reserve words in Python that have special meaning.
They are written in lower-case except for `True` and `False` keywords.

**Type conversions**
The types of data in Python include strings, numbers and Boolean values.

_1.Strings_
A string is a sequence of characters. In Python we surround strings with quotes, either single `'Hello World!'` or double `"Hello World!"` quotes.
**<u>String concatenation</u>**
String concatenation refers to combining one string with another e.g 

```
print('Hello'+ ' Pam')
```
`# Output
Hello Pam`

_2.Numbers_
We can store numbers inside variables. 
We use parentheses to specify the order of operations e.g `((3+4)*7)`.
We use `str` function to print out a number next to a string e.g 

```
my_num = 6
print(str(my_num) + ' is the best number.')
```
`#in the console this produces 6 is the best number`
_<u>Arithmetic</u>_
i)  Addition`(+)`
ii) Subtraction`(-)`
iii)Multiplication `(*)`
iv) Division`(/)`
v)  Modulus`(%)`
vi) Exponent`(**)`
vii)Equality operator`(==)`
viii)Not equal`(!=)`
ix)  Comparison operators`(>,>=,<,<=)`
_<u>examples</u>_
```
print(5 + 3) 
print(5 - 3)
print(5 * 3)
print(5 /3)
print(5 % 3)
print(5 ** 3)
print(5 != 3) 
```
_3.Boolean values_
Boolean values are defined by `True` and `False` keywords.

**Variables**
A variable is used to store data temporarily in the computer memory.
We start by declaring the name of the variable equal to the value of the variable e.g `age=20`.
We can declare a variable and assign it a string value e.g `name = "Pam"`.
If you are using multiple words for the name of a variable, separate the name with an underscore e.g `first_name`.

**Functions**
A function is a collection of code that performs a specific task. Any code inside the function needs to be indented.
The `def` keyword is used to define a function in Python.
A code inside a function can only be executed when we call the function i.e type out the function name followed by open-close parenthesis ().

```
def say_hello():
    print('Hello User')

say_hello()
```
`#console shows Hello User`
Functions are used to modify strings and to get more information about strings.
_<u>Built-in functions</u>_
They are used to convert functions to variables and include;
`int()`
`float()`
`bool()`
`str()`
_<u>Functions related to numbers</u>_
`abs`-absolute value.
`pow`-power.
`max`-gives the largest number.
`min`-gives the smallest number.
`round`-rounding up/down.
`ceil`-ceiling function.
`sqrt`-square root.

**Parameter**
A parameter is a value that you can give to a function.

```
def say_hello(name):
    print('Hello '+ name)

say_hello('Pam')
```
`#console shows Hello Pam`

**Return statement**
`return` keyword allows Python to return information from a function. In Python we can return any data types.

```
def square(num):
    return num*num 

result = square(5)
print(result)
```
`#console gives 25`

**Logical operators**
These are used to evaluate expressions to Boolean values.

i) `and`-returns `True` if both expressions return `True`.
ii) `or`-returns `True` if at least one expression returns `True`.
iii) `not`-is placed at the beginning and inverse any value.

**If statements**
`if` statements are used to make decisions in our programs.

```
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: ")

if op == "+"
     print(num1 + num2)
elif op == "-"
     print(num1 - num2)
elif op == "*"
     print(num1 * num2)
elif op == "/"
     print(num1 / num2)
else: 
     print("Invalid operator")
```

**While loops**
`while` loop is used to repeat and execute a block of code multiple times. The code inside the loop gets executed as long as the condition holds.

```
i = 1
while i <= 10:
     print(i)
     i = i + 1  #can also use i += 1
print('Done')
```
`#console shows
1
2
3
4
5
6
7
8
9
10
Done`

**For loops**
`for` loops are used to iterate over a sequence, which can be a string, list, tuple, set, dictionary or other iterable objects.

```
fruits = ['peach', 'passion', 'pear']
for word in fruits:
    print(word)
```
`#console gives us
peach
passion
pear`

**Index**
An `index` tells us where a specific character is located inside our string, list or tuple. Strings are indexed starting with 0.

**Lists**
A list is an ordered collection of items. We give lists descriptive names. We can access elements on a list based off of their index.

```
fruits = ["bananas", "oranges", "mangoes", "apples"]
print(fruits[0])
```
`#console shows bananas`

_<u>List Functions</u>_
`append`-to add a new element at the end of a list.
`insert`-to add a new element at the beginning of a list.
`in`-to check whether an item exists on our list or not.
`len`-to know how many items we have on a list.
`for`-to iterate over all values.
`extend`-to append lists.
`count`-to know how many times a value appears on the list.
`sort`-to arrange items on a list in alphabetical order.
`reverse`-to reverse the order of lists.
`remove`-to remove an element from a list.
`pop`-to remove the last element from a list.
`clear`-to remove all elements from a list.

**Tuples**
Tuples are used to store a sequence of objects. Tuples are _immutable_, once they are created they cannot be changed or modified. They are indexed starting with 0.

```
coordinates = (35, 67)
print(coordinates[0])
```
`#console shows 35`

**Dictionaries**
Dictionaries are special structures that allow us to store information in key-value pairs. Each key in a key-value pair is associated with a given value. The keys must be unique. A value can be a string, number, list or a tuple.

```
ex_dict = {
      "Mon": "Monday",
      "Tue": "Tuesday",
      "Wed": "Wednesday",
      "Thu": "Thursday",
      "Fri": "Friday",
      }
 print(ex_dict.get("Wed"))
```
`#console shows Wednesday`

**Files**
Python `read` command allows us to get information from a file stored outside of a Python file.
The built-in `open()` function is used to open files.
We can open files in different modes;
`'r'`-_read mode_ -used only to read information from a file.
`'w'`-_write mode_ -used when we want to change existing information in the file.
`'a'`-_append mode_-used to add new information at the end of a file.
`'r+'`-_read and write mode_-allows us to read and write inside our file.
`'t'`- to open a file in text mode.
`'b'`-to open a file in binary mode.
We use `close()` function to close a file.
For example, if we have a file outside python named workers, then we can read it using: 
```
workers_file = open('workers.txt', 'r')

print(workers_file.read())

workers_file.close()

```

**Classes and Objects**
Classes and objects in Python help us represent items that cannot be represented as strings, numbers or Booleans.
We can create our own new data types using classes and objects.
Classes are defined by the `class` keyword.
The tutorial https://www.programiz.com/python-programming/class gives us more information on classes and objects.