What is Python?
Python is a powerful general-purpose programming language. It is used in web development, data science, Machine Learning applications, creating software prototypes, and so on. Fortunately for beginners, Python has simple easy-to-use syntax. This makes Python an excellent language to learn to program for beginners. Python is a cross-platform programming language, which means that it can run on multiple platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual machines. It is an open source, object-oriented, high-level powerful programming language. If you come from a language like Java you will be able to feel at home.
Even though most of today’s Linux and Mac have Python pre-installed in it, the version might be out-of-date. So, it is always a good idea to install the most current version.
Facts about Python Programming Language:
Before we start Python programming, we need to have an interpreter to interpret and run our programs. If you have python installed you have an interpreter.
First Python program
print("Hello World!") # console Hello World!
As you can see above, it is so much easier to get started with python than any other language like Java, C++, etc.
Why should you learn python?
python and programming in general – is in such high demand because it is useful in just about every industry. Python is used by companies in recruiting, healthcare, financial services, marketing, education and many more.
Python is great for quick prototyping, hence is used extensively by startups to build their first minimum viable product (MVP). It is also highly scalable for medium to big applications.
According to iDataLabs 67% of the companies that use Python are small (<$50M in revenue), 9% are medium-sized ($50M – $1000M in revenue) and 17% are large (>$1000M in revenue).
Companies that use python
Python is the fastest growing programming language
Given Python’s uses across many industries and applications – and its recent explosive use in data science, machine learning and AI, Python is on a major growth trajectory. Stackoverflow.com shows Python as the fastest growing major programming language by a long-shot, by analyzing the number of visitors vs. questions about a certain topic.
Python is in high demand for jobs
Going hand-in-hand with lightning speed growth, Python programming is in high demand for jobs. Based on the number of job postings on one of the largest job search platforms, LinkedIn.com, Python ranks #2 in the most in-demand programming languages of 2020.
Python is easy to read, write, and learn
Python was built with the goal of getting rid of the complex and keeping only the necessary. Because of this, Python is easier to read, write, and learn than most other major programming languages.
Other languages like Java and C++ have some kind of a steep set up for a simple program to run. Python has a simple and easy way to get you set up and start coding in a matter of a few seconds.
Python is also an interpreted programming language. This means that unlike compiled languages like C++ or Java, you can run each line of code as soon as you finish writing it and see the results immediately. This is especially great for new programmers because you can get instantaneous feedback instead of waiting for the whole program to compile and run before you figure out that you forgot one character somewhere!
Python developers make great money
Python developers are some of the highest paid developers in the market, particularly in data science, machine learning and web development.
Python has a great community
One of the greatest tools a programmer will ever have is the support of their community. Thanks to online forums, local meet-ups, and the open source community, programmers continue to learn from and build on the success of their predecessors.
Stack Overflow is a programming question and answer platform critical for all developers when they are stuck, or wanting to share wisdom with the community. On Stack Overflow, Python is tagged in more than one million questions, demonstrating incredibly robust and active community for current and aspiring Python developers. GitHub is where developers store project code and collaborate with other developers. With over 1.5M repositories on GitHub and over 90,000 users committing or creating issues in these repositories, Python has the second largest GitHub community.
Decision making is required when we want to execute a code only if a certain condition is satisfied. if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
A program evaluates anexpression
and will execute statement(s) only if the expression is True
. If the expression is False
, the statement(s) is not executed.
In Python, the body of the if
statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True
. None
and 0
are interpreted as False
.
if 1>10: print("greater than 10") elif 1 > 5: print("greater than 5") else: print("less than 5")
The and keyword is a logical operator, and is used to combine conditional statements
if 1>10 and 2 > 3: print("") elif 1 > 5: print("") else: print("less than 5")
The or
keyword is a logical operator, and is used to combine conditional statements
if 1>10 or 2 > 3: print("") elif 1 > 5: print("") else: print("less than 5")
Pass statement
if
statements cannot be empty, but if you for some reason have an if
statement with no content, put in the pass
statement to avoid getting an error.
if 3 > 2: pass
Python is an object oriented programming language. Unlike procedure oriented programming, where the main emphasis is on functions, object oriented programming stresses on objects. An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. As many houses can be made from a house’s blueprint, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.
Syntax
# create class class class_name(): variables def __init__(self, parameters): functions # create object of class variable = class_name();
__init__() function
This special function gets called whenever a new object of that class is instantiated. This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize some if not all variables within the class or perform any operations that are necessary for the object.
Object method
instance method or object method is a method that can freely access attributes and other methods on the same object. This gives them a lot of power when it comes to modifying an object’s state.Not only can they modify object state, instance methods can also access the class itself through the self.__class__
attribute. This means instance methods can also modify class state.
class User(): name = str age = int def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name
class method
Because the class method only has access to this cls
argument, it can’t modify object instance state. That would require access to self
. However, class methods can still modify class state that applies across all instances of the class.
static method
This type of method takes neither a self
nor a cls
parameter (but of course it’s free to accept an arbitrary number of other parameters).
Therefore a static method can neither modify object state nor class state. Static methods are restricted in what data they can access – and they’re primarily a way to namespace your methods.
class User(): name = str age = int admin_type = "ADMIN" user_type = "USER" def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name @classmethod def get_admin_role(cls): return "ROLE_"+cls.admin_type @staticmethod def get_user_role(): return "ROLE_" + User.user_type
# class method print(User.get_admin_role()) # static method print(User.get_user_role())
You can delete properties on objects by using the del
keyword
kinga = User("Kinga", 8) print(kinga.get_name()) del kinga.name print(f'name: {kinga.get_name()}') # output Kinga name: <class 'str'>
class
definitions cannot be empty, but if you for some reason have a class
definition with no content, put in the pass
statement to avoid getting an error.
class User(): pass
In programming, Handling exceptions is a must when it comes to real life applications. Python has many built-in exceptions that are raised when your program encounters an error. When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.
We must handle any exception raised within our application. We do that by use try and except.
Error being raised
result = 12 / 0 print(result) # output Traceback (most recent call last): File "/Users/folaukaveinga/Github/python/main.py", line 101, in <module> exceptions.show() File "/Users/folaukaveinga/Github/python/exceptions.py", line 6, in show result = 12 / 0 ZeroDivisionError: division by zero
Handling raised error
The critical operation which can raise an exception is placed inside the try
clause. The code that handles the exceptions is written in the except
clause.
try: result = 12 / 0 print(result) except ZeroDivisionError as e: print(e) print("done")
Here the program continued its executing to the end where is before it stopped when exception was raised.
Handling specific errors
A try
clause can have any number of except
clauses to handle different exceptions, however, only one will be executed in case an exception occurs.
try: # do something pass except ValueError: # handle ValueError exception pass except (TypeError, ZeroDivisionError): # handle multiple exceptions # TypeError and ZeroDivisionError pass except: # handle all other exceptions pass
Raise an error
Exceptions are raised by Python when errors occur at runtime. We can also manually raise exceptions using the raise
keyword. We can optionally pass values to the exception to clarify why that exception was raised.
name = input("what is your name? ") if name == None or len(name) ==0 : raise ValueError("invalid name") # output - if you don't put in anything Traceback (most recent call last): File "/Users/folaukaveinga/Github/python/main.py", line 101, in <module> exceptions.show() File "/Users/folaukaveinga/Github/python/exceptions.py", line 15, in show raise ValueError("invalid name") ValueError: invalid name
Try with else clause
In some situations, you might want to run a certain block of code if the code block inside try
ran without any errors. For these cases, you can use the optional else
keyword with the try
statement. Note that exceptions in the else clause are not handled by the preceding except clauses.
try: result = 12 / 0 print(result) except ZeroDivisionError as e: print(e) else: print("all good")
Try with finally
The try
statement in Python can have an optional finally
clause. This clause is executed no matter what, and is generally used to release external resources. In all these circumstances, we must clean up the resource before the program comes to a halt whether it successfully ran or not. These actions (closing a file, GUI or disconnecting from network) are performed in the finally
clause to guarantee the execution.
try: f = open("test.txt", encoding='utf-8') # perform file operations finally: f.close() print("file closed")
Variables
Data in programming is stored in containers called variables. Every value(variable) in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type, and can even change type after they have been set. You can let python determine the data type or you can explicitly set it.
Data Types
Text Type | str |
Numeric Types: | int , float , complex |
Sequence Types: | list , tuple , range |
Mapping Type: | dict |
Set Types: | set , frozenset |
Boolean Type: | bool |
Binary Types: | bytes , bytearray , memoryview |
str data type
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str
class.
firstName = "Folau" print(firstName) firstName = str("Folau") print(firstName) # console Folau Folau
int data type
Integers can be of any length, it is only limited by the memory available. It contains positive or negative whole numbers (without fraction or decimal)
intNum = 2 print(intNum) num = int(2) print(num)
float data type
A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is a floating-point number.
number = 2.5 print(number) num = float(2.5) print(numb) #console 2.5 2.5
complex data type
Complex numbers are written in the form, x + yj
, where x is the real part and y is the imaginary part.
list data type
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.
lista = [1, 2.2, 'python'] print(lista) listb = list((1, 2.2, 'python')) print(listb) # console [1, 2.2, 'python'] [1, 2.2, 'python']
tuple data type
Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.
# how to create tuple tuple_numbers = (1, 2, 3, 1) tup = 1, 2, 3, 1, None, "Hello" nested_tuple = ((1, 2), ("Hello", "Hi"), "Python") empty_tuple = () numbs = tuple((1,2,3)) # how to access tuple elements nested_tuple = (1, 2, (3, 4), (5, 6, 7)) nested_tuple[2][0] -> 3
range data type
range returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number. The most common use of range function is to iterate sequence type. It is most commonly used in for and while loops. We can use range in python to increment and decrement step values using positive and negative integers.
# range(start, stop, step) # start - where to start from # stop - where to stop # step - how big of a step for each iteration evenNumbers = range(2, 20 ,2) for num in evenNumbers: print(num) #console 2 2 4 6 8 10 12 14 16 18
dict data type
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces {}
with each item being a pair in the form key:value
. Key and value can be of any type.
person = {"firstName":"Folau", "lastName":"Kaveinga"} print(person) user = dict(firstName="Folau", lastName="Kaveinga") print(user)
set data type
Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }
. Items in a set are not ordered.
# set numbers = set((1,2,3)) print(type(numbers)) numbers = {1, 2, 3} print(type(numbers))
fronzenset data type
Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set. But like sets, it is not ordered (the elements can be set at any index).
# tuple of vowels vowels = ('a', 'e', 'i', 'o', 'u') fSet = frozenset(vowels) print('The frozen set is:', fSet) print('The empty frozen set is:', frozenset()) # frozensets are immutable fSet.add('v') -> error
boolean data type
True
or False
. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool
. Note that True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
isMale = True print(isMale) # console True
bytes data type
The bytes() method returns a immutable bytes object initialized with the given size and data. bytes()
method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256
. The syntax of bytes()
method is
bytes([source[, encoding[, errors]]])
string = "My name is Folau" # string with encoding 'utf-8' arr = bytes(string, 'utf-8') print(arr) #console b'My name is Folau'
bytearray data type
The bytearray() method returns a bytearray object which is an array of the given bytes. bytearray()
method returns a bytearray object which is mutable (can be modified) sequence of integers in the range 0 <= x < 256
. The syntax of bytearray()
method is
bytearray([source[, encoding[, errors]]])
string = "My name is Folau" # string with encoding 'utf-8' arr = bytearray(string, 'utf-8') print(arr) #console bytearray(b'My name is Folau')
memoryview data type
The memoryview() function returns a memory view object of the given argument. A memory view is a safe way to expose the buffer protocol in Python. It allows you to access the internal buffers of an object by creating a memory view object. To expose the buffer protocol using memoryview()
, we use this syntax:
memoryview(obj)
#random bytearray random_byte_array = bytearray('ABC', 'utf-8') mv = memoryview(random_byte_array) # access memory view's zeroth index print(mv[0]) # create byte from memory view print(bytes(mv[0:2])) # create list from memory view print(list(mv[0:3])) #console 65 b'AB' [65, 66, 67]
The data type is set when you assign a value to a variable.
numbers = {1, 2, 3} print(type(numbers)) # console <class 'set'>
Explicitly declaring a data type. I found this very useful when reading other people’s code.
numbers = set((1,2,3))
Use type() function to find out a data type.
numbers = set() numbers.add(1) numbers.add(2) numbers.add(3) print(type(numbers)) # console <class 'set'>
Use isinstance function to check if an object belongs to a particular class or type
number = 2.5 print(number, "is float number?", isinstance(number,float)) #console 2.5 is float number? True