DEV Community

Cover image for Introduction to Modern Python.
Torine6
Torine6

Posted on • Updated on

Introduction to Modern Python.

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!')

Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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')

Enter fullscreen mode Exit fullscreen mode

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

first_number = input('Enter your first number: ')
print(first_number)
Enter fullscreen mode Exit fullscreen mode

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

#anything after this hash character is a comment.
Enter fullscreen mode Exit fullscreen mode

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.
String concatenation
String concatenation refers to combining one string with another e.g

print('Hello'+ ' Pam')
Enter fullscreen mode Exit fullscreen mode

# 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.')
Enter fullscreen mode Exit fullscreen mode

#in the console this produces 6 is the best number
Arithmetic
i) Addition(+)
ii) Subtraction(-)
iii)Multiplication (*)
iv) Division(/)
v) Modulus(%)
vi) Exponent(**)
vii)Equality operator(==)
viii)Not equal(!=)
ix) Comparison operators(>,>=,<,<=)
examples

print(5 + 3) 
print(5 - 3)
print(5 * 3)
print(5 /3)
print(5 % 3)
print(5 ** 3)
print(5 != 3) 
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

#console shows Hello User
Functions are used to modify strings and to get more information about strings.
Built-in functions
They are used to convert functions to variables and include;
int()
float()
bool()
str()
Functions related to numbers
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')
Enter fullscreen mode Exit fullscreen mode

#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)
Enter fullscreen mode Exit fullscreen mode

#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")
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

#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)
Enter fullscreen mode Exit fullscreen mode

#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])
Enter fullscreen mode Exit fullscreen mode

#console shows bananas

List Functions
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])
Enter fullscreen mode Exit fullscreen mode

#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"))
Enter fullscreen mode Exit fullscreen mode

#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()

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)