DEV Community

Mwenda Harun Mbaabu
Mwenda Harun Mbaabu

Posted on

Python 101! Introduction to Python

image

Python is an interpreted, high-level language created by Guido van Rossum and released in 1991. It is dynamically typed and garbage collected.

Python programs have the extension .py and can be run from the command line by typing python file_name.py.

Probably its most noticeable characteristic is its use of significant white space to delimit code blocks, instead of the more popular {} symbols.

End-of-line semicolons (;) are optional and usually not used in Python.

Python becomes the best solution in many domains from web applications, data analysis, data science, machine learning, and AI.

Common Feature Provided By python :

  • Simplicity: Think less of the syntax of the language and more of the code.

  • Open Source: A powerful language and it is free for everyone to use and alter as needed.

  • Portability: Python code can be shared and it would work the same way it was intended to. Seamless and hassle-free.

  • Being Embeddable & Extensible: Python can have snippets of other languages inside it to perform certain functions.

  • Being Interpreted: The worries of large memory tasks and other heavy CPU tasks are taken care of by Python itself leaving you to worry only about coding.

  • Huge amount of libraries: Data Science? Python has you covered. Web Development? Python still has you covered.

  • Object Orientation: Objects help breaking-down complex real-life problems into such that they can be coded and solved to obtain solutions.

Applications of Python.

  • Artificial Intelligence
  • Desktop Application
  • Automation
  • Web Development
  • Data Wrangling, Exploration And Visualisation.

Installation:

Download the latest version of Python for your operating system here. You can read more about setting up a python development using VS Code from this tutorial by pythontutorial.net.

Python Hello World.

As Raghu Venkatesh, Engineering Manager at Atlassian said, if you can write “hello world” you can change the world. So let create our first python program, hello world program.

First, create a new folder where you will be saving you python files, let say Lux.

Second, launch the VS code and open the new folder you created, Lux.

Third, create a new python file, let say app.py file and enter the following code and save the file:

print('Hello, World!')
Enter fullscreen mode Exit fullscreen mode

The print() is a built-in function that displays a message on the screen. In our case, it’ll show the message 'Hello, Word!'.

Executing the Python program.

To execute the app.py file we created above, you first launch the Command Prompt on Windows or Terminal on macOS or Linux.

Then, navgiate to the folder containing our file, for our case Lux.

After that, type the following command to execute the app.py file:

Python3 app.py
Enter fullscreen mode Exit fullscreen mode

If everything is fine, you’ll see the following message on the screen:

Hello, World!
Enter fullscreen mode Exit fullscreen mode

Comments

A comment is text in a program's code, script, or another file that is not meant to be seen by the user running the program. However, is seen when viewing the source code.

Comments help make code easier to understand by explaining what is happening and help prevent portions of a program from executing.

# single line comment

'''
multiline comment
Using  docstring
'''
Enter fullscreen mode Exit fullscreen mode

NOTE: Use comments where appropriate and don't over do it.

Arithmetic Operators.

print(46 + 2)  # 48 (addition)
print(10 - 9)  # 1 (subtraction)
print(3 * 3)  # 9 (multiplication)
print(84 / 2)  # 42.0 (division)
print(2 ** 8)  # 256 (exponent)
print(11 % 2)  # 1 (remainder of the division)
print(11 // 2)  # 5 (floor division)
Enter fullscreen mode Exit fullscreen mode

Variables

Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

favourite_food = "Rösti"
print(favourite_food)
Enter fullscreen mode Exit fullscreen mode

Note:

Variables do not need to be declared. Their data types are inferred from their assignment statement, which makes Python a dynamically typed language. This means that different data types can be assigned to the same variable throughout the code.

favourite_food = "Rösti"
print(favourite_food)
favourite_food = 26
print(favourite_food)
favourite_food = False
print(favourite_food)
Enter fullscreen mode Exit fullscreen mode

Comparison, Logical, and Conditional Operators.

Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Conditionals: if, else, elif

# logical operators:

laundry_day = "Monday"
today = "Tuesday"
on_vacation = False
if today is laundry_day and today is not "Sunday" and on_vacation is False:
  print("It's laundry day!")
else:
  print("The laundry can wait!")


# comparison operators:
age = 21
if age >= 21:
  print("You can drive a trailer")
elif age >= 16:
  print("You can drive a car")
else:
  print("You can ride a bike")  
Enter fullscreen mode Exit fullscreen mode

Data Types

1). Strings.

#Example 1:

language = "Python"

#Example 2:

multiline_str = '''
one
per
line'''  

#Example 3, escape characters:

escape_str = "She said: \"Python is great!\""
print(escape_str) # She said: "Python is great!"  

# Example 4, concatenate strings:

one = "Lux"
two = "Academy"
print(one + " " + two) # Lux Academy 

# Example 5: interpolation.

# method 1
first_name = "Lux"
last_name = "Academy"
greet = f"Welcome at {first_name} {last_name}!" 
print(greet)  # Welcome at Lux Tech Academy!

# method 2
first_name = "Lux"
last_name = "Academy"
greet = 'Welcome at {} {}!'.format(first_name, last_name)
print(greet)  # Welcome at Lux Tech Academy!

# method 3
first_name = "Lux"
last_name = "Academy"
greet = 'Welcome at{first} {last} !'.format( first=first_name, last=last_name) 
print(greet)  # Welcome at Lux Tech Academy!

#Example 6, extract substrings

name = "Monty Python"
print(name[6:9]) # Pyt
print(name[6:]) # Python
print(name[:5]) # Monty
Enter fullscreen mode Exit fullscreen mode

2). Numbers

Python supports three numeric data types: int, float, and complex. They are inferred, so need not be specified.


age = 18 # int
pi = 3.14 # float
total = age + pi # float
print(type(age), type(pi), type(total)) # <class 'int'> <class 'float'> <class 'float'>
Enter fullscreen mode Exit fullscreen mode

3). Booleans.

# booleans

a = True
b = False
if a is True and b is False:
  print("YAY!")
Enter fullscreen mode Exit fullscreen mode

4). Lists.

A list in Python is what other programming languages call an array. They use Zero-based indexing, and the items can contain any type of data. List items are nested in [].

# can store any data type
multiple_types = [True, 3.7, "Python"]

# access and modify
favourite_foods = ["pasta", "pizza", "french fries"]
print(favourite_foods[1]) # pizza
favourite_foods[0] = "rösti"
print(favourite_foods[0]) # rösti

# subsets
print(favourite_foods[1:3]) # ['pizza', 'french fries']
print(favourite_foods[2:]) # ['french fries']
print(favourite_foods[0:2]) # ['rösti', 'pizza']

# append
favourite_foods.append("paella")

# insert at index
favourite_foods.insert(1, "soup")

# remove
favourite_foods.remove("soup")

# get length
print(len(favourite_foods)) # 4

# get subset (the original list is not modified)
print(favourite_foods[1:3]) # ['pizza', 'french fries']

# lists inside lists
favourite_drinks = ["water", "wine", "juice"]
favourites = [favourite_foods, favourite_drinks]
print(favourites[1][2]) # juice

Enter fullscreen mode Exit fullscreen mode

5). Tuples

Tuples are just like lists, but immutable (cannot be modified). They are surrounded by ().

#tuples

new_tuple = ("a", "b", "c", "d")
print(len(new_tuple)) # 4
print(new_tuple[1]) # b
print(new_tuple[1:4]) # ('b', 'c', 'd')
Enter fullscreen mode Exit fullscreen mode

6). Dictionaries.

Dictionaries are key-value pairs. They are surrounded by {} and are similar to objects in JavaScript. The values can have any data type.

language_creators = {
  "Python" : "Guido van Rossum",
  "C" : "Dennis Ritchie",
  "Java" : "James Gosling",
  "Go": "Robert Griesemer",
  "Perl" : "Larry Wall"
}

# access, modify, delete
print(language_creators["Python"]) # Guido van Rossum
language_creators["Go"] = ["Robert Griesemer", "Rob Pike", "Ken Thompson"]
print(language_creators["Go"]) # ['Robert Griesemer', 'Rob Pike', 'Ken Thompson']
print(len(language_creators)) # 5
del language_creators["Perl"]
print(len(language_creators)) # 4

# print keys and values
print(language_creators.keys())
print(language_creators.values())
Enter fullscreen mode Exit fullscreen mode

Loops.

For loops

# foor loop
for x in range(0, 3):
  print(x)

# loop through list
for x in ["Python", "Go", "Java"]:
  print(x)

# loop through dictionary
language_creators = {
  "Python" : "Guido van Rossum",
  "C" : "Dennis Ritchie",
  "Java" : "James Gosling",
}
for key, value in language_creators.items():
  print("Language: {}; Creator: {}".format(key, value))

Enter fullscreen mode Exit fullscreen mode

While loops.

# while loop
level = 0
while(level < 10):
  level += 1
Enter fullscreen mode Exit fullscreen mode

Functions.

Functions are defined using the def keyword.

# functions
def allowed_to_drive(age):
  if age >= 21:
    return True
  else:
    return False

print(allowed_to_drive(42)) # True
print(allowed_to_drive(12)) # False
Enter fullscreen mode Exit fullscreen mode

Default values for arguments may also be defined.

def is_laundry_day(today, laundry_day = "Monday", on_vacation = False):
  if today is laundry_day and today is not "Sunday" and on_vacation is False:
    return True
  else:
    return False

print(is_laundry_day("Tuesday")) # False
print(is_laundry_day("Tuesday", "Tuesday")) # True
print(is_laundry_day("Friday", "Friday", True)) # False
Enter fullscreen mode Exit fullscreen mode

Classes.

Classes are collections of variables and functions that work with those variables.
Classes in Python are defined with the class keyword. They are similar to classes in other languages like Java and C#, but differences include self being used instead of this to refer to the object resulted from the class. Also, the constructor function’s name is init, instead of the more popular classname. self must be used every time a class variable is referenced and must be the first argument in each function’s argument list, including the constructor.

Python does not support method overloading, but it can be achieved to some extent by using default values for arguments (shown in the Functions section).


# classes

class Email:
  # __ means private
  __read = False

  def __init__(self, subject, body):
    self.subject = subject
    self.body = body

  def mark_as_read(self):
    self.__read = True

  def is_read(self):
    return self.__read

  def is_spam(self):
    return "you won 1 million" in self.subject

e = Email("Check this out", "There are a bunch of free online course here: https://course.online")
print(e.is_spam()) # False
print(e.mark_as_read())
print(e.is_read()) # True
Enter fullscreen mode Exit fullscreen mode

Python also supports inheritance, which means that classes can be set to inherit methods and variables from another class or multiple classes (multiple inheritance).

# inheritance

class EmailWithAttachment(Email):
  def __init__(self, subject, body, attachment):
    super(EmailWithAttachment, self).__init__(subject, body)
    self.__attachment = attachment

  def get_attachment_size(self):
    return len(self.__attachment)

email_with_attachment = EmailWithAttachment("you won 1 million dollars", "open attachment to win", "one million.pdf")
print(email_with_attachment.is_spam()) # True
print(email_with_attachment.get_attachment_size()) # 15
Enter fullscreen mode Exit fullscreen mode

File I/O

# write
todos_file = open("todos.txt", "wb")
todos_file.write(bytes("buy a new domain name\n", "UTF-8"))
todos_file.write(bytes("work on the side project\n", "UTF-8"))
todos_file.write(bytes("learn a new programming language\n", "UTF-8"))
todos_file.close()

# read
todos_file = open("todos.txt", "r+")
todos_file_contents = todos_file.read()
print(todos_file_contents)
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
grayhat profile image
Mwenda Harun Mbaabu

Garbage collection (GC) is nothing but collecting or gaining memory back which has been allocated to objects but which is not currently in use in any part of our program.

Read More About Garbage Collection in Programming :
en.wikipedia.org/wiki/Garbage_coll...

Collapse
 
ahmad06700857 profile image
Ahmad

entechin.com/linspace-matlab-tutor...

Kindly check my article related to linspace matlab

Collapse
 
aatmaj profile image
Aatmaj

May be you guys would find my Learning Python Course useful.