Basic Python Programming

  • This guide introduces the reader informally to the basic concepts and features of the Python programming language from scratch.
  • Learn by examples! The guide supplements all explanations with clarifying examples.  
  • Python is a general-purpose, dynamic, high-level, and interpreted programming language. It is a multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.
  • Python makes development and debugging fast because no compilation step is included in Python development, and the edit-test-debug cycle is very fast.
  • Python has many web-based assets, open-source projects, and a vibrant community. 
  • Python is an open-source, cost-free programming language. It is utilized in several sectors and disciplines as a result.
  • Python has many third-party libraries that can be used to make its functionality easier. These libraries cover many domains, for example, web development, scientific computing, data analysis, and more.
  • If you find that you do not have Python installed on your computer, then you can download it for free from the following website: https://www.python.org/

Table of Contents

  1. Why Python?
  2. Installing Jupyter/Anaconda IDE
  3. Getting Started
  4. Declaring Variables
  5. Using Strings
  6. Boolean Values & Operators
  7. Lists
  8. Tuples
  9. Sets
  10. Dictionaries
  11. Arrays
  12. Loops
  13. Conditionals
  14. Functions
  15. Modules
  16. Conclusions
  17. The Road Ahead
  18. References

Why Python?

  • Easy to Use, Learn and Share
  • Low-Code/No-Code Automation
  • Dynamic Memory Allocation
  • Open-Source Projects
  • Extensive GUI Support
  • Wide Range of Libraries
  • Machine Learning (ML)

Installing Jupyter/Anaconda IDE

  • Before jumping into data science, you need to set up the required software and tools and learn how to use them. This section will teach you how to install and use the Jupyter notebook within the Anaconda IDE for building a data science ecosystem.
  • Download Anaconda installer for your operating system from: https://www.anaconda.com/downloads
  • Once the download is complete, double-click the package to start installing Anaconda using the default settings.
  • Click on Continue on the Introduction, Read Me, and License screens. Click on Agree to continue the installation, once the prompt below appears.
  • On the Destination Select screen, select “Install for me only” and use the default installation PATH.
  • Click on Continue to install Anaconda without the PyCharm IDE.
  • After the installation completes, click on Close on Summary.
  • Double-click on the Anaconda Navigator icon.
  • Go to the Home page on Anaconda IDE and install Jupyter Notebook from an application. A Jupyter Notebook interface will appear in your default browser.
  • With Jupyter Notebook open in your browser, you may have noticed that the URL for the dashboard is something like https://localhost:8888/tree. Localhost is not a website, but indicates that the content is being served from your local machine: your own computer.
  • Browse to the folder in which you would like to create your first notebook, click the “New” drop-down button in the top-right and select “Python 3”.
  • Your first Jupyter Notebook will open in new tab — each notebook uses its own tab because you can open multiple notebooks simultaneously.
  • If you switch back to the dashboard, you will see the new file Untitled.ipynb. Each .ipynb file is one notebook, so each time you create a new notebook, a new  .ipynb file will be created.
  • Cells form the body of a notebook. In the screenshot of a new notebook in the section above, that box with the green outline is an empty cell. 
  • When we run the cell from the menu bar, its output is displayed below and the label to its left will have changed from In [ ] to In [1].
  • From the menu bar, click Insert and select Insert Cell Below to create a new code cell underneath your first and try out the following code to see what happens. 
  • Behind every notebook runs a kernel. When you run a code cell, that code is executed within the kernel. Any output is returned back to the cell to be displayed. The kernel’s state persists over time and between cells — it pertains to the document as a whole and not individual cells.
  • Most of the time when you create a notebook, the flow will be top-to-bottom. 
  • If your kernel is ever stuck on a computation and you wish to stop it, you can choose the Interrupt option.

Getting Started

  • Let’s set the working directory MYPATH
import os
os.chdir('MYPATH')    # Set working directory
os. getcwd()
  • We can check the Python version
!python --version
  • Output:
Python 3.11.5
  • Let’s run the print script with 2 comments
# Script Begins 

print("I love Python!") 

# Scripts Ends 
  • Output
I love Python!

Declaring Variables

  • In Python, variables are created when you assign a value to it:
x = 5     #integer
y = "Hi!" #string
z=5.1     #float
zz = 1j   # complex
bl=False  #boolean 
print(bl)
False
print(x)
5
print(y)
Hi!
print(z)
5.1
print(zz)
1j
print(type(bl))
print(type(x))
print(type(y))
print(type(z))
print(type(zz))
<class 'bool'>
<class 'int'>
<class 'str'>
<class 'float'>
<class 'complex'>
  • You can convert from one type to another with the int()float(), and complex() methods:
x = 1    # int
y = 2.8  # float
z = 1j   # complex

#convert from int to float:
a = float(x)

#convert from float to int:
b = int(y)

#convert from int to complex:
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>

Using Strings

Strings are Arrays. Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode characters. A String is a data structure in Python that represents a sequence of characters. Strings are used widely in many different applications, such as storing and manipulating text data, representing names, addresses, and other types of data that can be represented as text.

  • Assigning a single-line string to a variable
a = "Hi!"
print(a)
Hi!
  • Assigning a multi-line string to a variable
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
  • Loop through the letters in the word “banana”:
for x in "banana":
  print(x)
b
a
n
a
n
a
  • The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
13
  • To check if a certain phrase or character is present in a string, we can use the keyword in:
txt = "The best things in life are free!"
print("free" in txt)
True
  • Check if “expensive” is NOT present in the following text
txt = "The best things in life are free!"
print("expensive" not in txt)
True
  • You can return a range of characters by using the slice syntax
b = "Hello, World!"
print(b[2:5])
llo
  • Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Hello
  • Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
llo, World!
  • Use negative indexes to start the slice from the end of the string:
#From: "o" in "World!" (position -5) 
#To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
orl
  • The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
HELLO, WORLD!
  • The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
hello, world!
  • The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Hello, World!
  • The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!
  • The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
['Hello', ' World!']
  • Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
  • To add a space between them, add a ” “:
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Hello World

Boolean Values & Operators

  • The Python Boolean type is one of Python’s built-in data types. It’s used to represent the truth value of an expression. Booleans represent one of two values: True or False:
Input: 1==1
Output: True

Input: 2<1
Output: False
  • The output <class ‘bool’> indicates the variable is a Boolean data type
a = True
type(a)

b = False
type(b)

Output:

<class 'bool'>
<class 'bool'>
  • When you compare two values, the expression is evaluated and Python returns the Boolean answer:
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output:
True
False
False
  • Print a message based on whether the condition is True or False:
a = 200
b = 33

if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")
Output:
b is not greater than a
  • The bool() function allows you to evaluate any value, and give you True or False in return
print(bool("Hello"))
print(bool(15))
Output:
True
True
  • Boolean Operations in Python are simple arithmetic of True and False values:
    • or
    • and
    • not
    • == (equivalent)
    • != (not equivalent)
  • Let’s try a Python Boolean with an if statement and OR operator that checks if a is greater than b or b is smaller than c and it returns True if any of the conditions are True (b<c)
# Python program to demonstrate
# or operator

a = 1
b = 2
c = 4

if a > b or b < c:
	print(True)
else:
	print(False)

if a or b or c:
	print("At least one number has Boolean value as True")
Output:
True
At least one number has Boolean value as True
  • Boolean And Operator: In the first part of the code,  the overall expression a > b and b < c evaluates to False. Hence, the code will execute the else block and print False. Whereas in the second part, a is 0, conditions a and b, and c will evaluate to False because one of the variables (a) has a Boolean value of False. Therefore, the code will execute the else block and print “At least one number has a Boolean value as False”.
# Python program to demonstrate
# and operator

a = 0
b = 2
c = 4

if a > b and b<c:
	print(True)
else:
	print(False)
	
if a and b and c:
	print("All the numbers has Boolean value as True")
else:
	print("At least one number has Boolean value as False")
Output:
False
At least one number has Boolean value as False
  • The Boolean Not operator only requires one argument and returns the negation of the argument i.e. returns the True for False and False for True:
# Python program to demonstrate
# not operator

a = 0

if not a:
	print("Boolean value of a is False")
Output:
Boolean value of a is False
  • Boolean == (equivalent) and != (not equivalent) Operator. Both operators are used to compare two results. == (equivalent operator returns True if two results are equal and != (not equivalent operator returns True if the two results are not same.
# Python program to demonstrate
# equivalent an not equivalent
# operator

a = 0
b = 1

if a == 0:
	print(True)
	
if a == b:
	print(True)
	
if a != b:
	print(True)
Output:
True
True
  • The is keyword is used to test whether two variables belong to the same object. The test will return True if the two objects are the same else it will return False even if the two objects are 100% equal. The code below first assigns the value 10 to variables x and y. It then compares x and y using the “is” operator and prints True because they refer to the same object. Next, it assigns two separate lists to x and y. It then compares x and y using the “is” operator and prints False because the lists are different objects in memory. 
# Python program to demonstrate
# is keyword
 
 
x = 10
y = 10
 
if x is y:
    print(True)
else:
    print(False)
 
x = ["a", "b", "c", "d"]
y = ["a", "b", "c", "d"]
 
print(x is y)
Output:
True
False
  • in operator checks for the membership i.e. checks if the value is present in a list, tuple, range, string, etc. The code below creates a list of animals and checks if the string “lion” is present in the list. If “lion” is found in the list, it prints “True”.
# Python program to demonstrate
# in keyword
 
# Create a list
animals = ["dog", "lion", "cat"]
 
# Check if lion in list or not
if "lion" in animals:
    print(True)
Output:
True
  • Python also has many built-in functions that return a Boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
x = 200
print(isinstance(x, int))
Output:
True

Lists

  • list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].
  • Lists are great to use when you want to work with many related values (your assortment of files, your song playlists, your browser bookmarks, your emails, the collection of videos, etc.). They enable you to keep data together that belongs together, condense your code, and perform the same methods and operations on multiple values at once.
  • Lists are used to store multiple items in a single variable, e.g.
mylist = ["apple", "banana", "cherry"]
print(mylist)
Output:
['apple', 'banana', 'cherry']
  • List items are ordered, changeable, and allow duplicate values.
  • List items are indexed, the first item has index [0], the second item has index [1] etc.
  • List items can be of any data type, e.g.
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
  • A list can contain different data types:
list1 = ["abc", 34, True, 40, "male"]
  • Lists are defined as objects with the data type ‘list’:
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Output:
<class 'list'>
  • It is also possible to use the list() constructor when creating a new list:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Output:
['apple', 'banana', 'cherry']
  • To determine how many items a list has, use the len() function:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output:
3
  • In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. 
# Python program to demonstrate
# accessing of element from list
 
# Creating a List with
# the use of multiple values
List = ["Go", "For", "Python"]
 
# accessing a element from the
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

Output:
Accessing a element from the list
Go
Python
  • Accessing elements from a multi-dimensional list
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Go', 'For'], ['Python']]
 
# accessing an element from the
# Multi-Dimensional List using
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])
Output:
Accessing a element from a Multi-Dimensional list
For
Python
  • Negative Indexing means start from the end
  • -1 refers to the last item, -2 refers to the second last item etc.
  • (the first item has index 0)
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Output:
cherry
  • You can specify a range of indexes by specifying where to start and where to end the range, e.g. return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Output:
['cherry', 'orange', 'kiwi']
  • This example returns the items from the beginning to, but NOT including, “kiwi”:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Output:
['apple', 'banana', 'cherry', 'orange']
  • This example returns the items from “orange” (-4) to, but NOT including “mango” (-1):
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Output: 
['orange', 'kiwi', 'melon']
  • To determine if a specified item is present in a list use the in keyword:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")
Output:
Yes, 'apple' is in the fruits list
  • To change the value of a specific item, refer to the index number
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Output:
['apple', 'blackcurrant', 'cherry']
  • To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Output:
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
  • If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
Output:
['apple', 'blackcurrant', 'watermelon', 'cherry']
  • If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly, e.g. change the second and third value by replacing it with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
Output:
['apple', 'watermelon']
  • To insert a new list item, without replacing any of the existing values, we can use the insert() method
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
Output:
['apple', 'banana', 'watermelon', 'cherry']
  • To add an item to the end of the list, use the append() method:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output:
['apple', 'banana', 'cherry', 'orange']
  • To append elements from another list to the current list, use the extend() method:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Output:
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
  • The remove() method removes the specified item
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Output:
['apple', 'cherry']
  • The pop() method removes the specified index
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
Output:
['apple', 'cherry']
  • The del keyword can also delete the list completely
thislist = ["apple", "banana", "cherry"]
del thislist
  • The clear() method empties the list. The list still remains, but it has no content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Output:
[]
  • You can loop through the list items by using a for loop:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)
Output:
apple
banana
cherry

Tuples

  • Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable or immutable.
  • It is an ordered collection, so it preserves the order of elements in which they were defined.
  • Since tuples are indexed, they can have items with the same value (duplicates).
  • Tuple items can be of any data type with strings, integers and Boolean values.
  • Tuples are written with round brackets, separated by a comma:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Output:
('apple', 'banana', 'cherry')
  • As with Lists, you can use the len() function
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Output:
3
  • To create a tuple with only one item, you have to add a comma after the item
thistuple = ("apple",)
print(type(thistuple))
Output:
<class 'tuple'>
  • It is also possible to use the tuple() constructor to make a tuple
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Output: 
('apple', 'banana', 'cherry')
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
 
# Creating a Tuple
# with the use of string
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
 
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
 
# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

Output:
Initial empty Tuple: 
()

Tuple with the use of String: 
('Geeks', 'For')

Tuple using List: 
(1, 2, 4, 5, 6)

Tuple with the use of function: 
('G', 'e', 'e', 'k', 's')

Read more:

Sets

  • In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
  • Set items are unchangeable, but you can remove items and add new items.
  • The values True (False) and 1 (0) are considered the same value in sets, and are treated as duplicates.
  • Set items can be of any data type.
  • The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
  • Sets are written with curly brackets:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Output:
{'banana', 'cherry', 'apple'}
  • To determine how many items a set has, use the len() function
thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Output:
3
  • Sets are defined as objects with the data type ‘set’:
myset = {"apple", "banana", "cherry"}
print(type(myset))
Output:
<class 'set'>
  • It is possible to use the set() constructor to make a set
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Output:
{'banana', 'cherry', 'apple'}
# Python program to demonstrate 
# Creation of Set in Python

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with 
# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with
# the use of Constructor
# (Using object to Store String)
String = 'GeeksForGeeks'
set1 = set(String)
print("\nSet with the use of an Object: " )
print(set1)

# Creating a Set with
# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with
# the use of a tuple
t=("Geeks","for","Geeks")
print("\nSet with the use of Tuple: ")
print(set(t))

# Creating a Set with
# the use of a dictionary
d={"Geeks":1,"for":2,"Geeks":3}
print("\nSet with the use of Dictionary: ")
print(set(d))

Output:
Initial blank Set: 
set()

Set with the use of String: 
{'k', 'e', 'F', 'r', 'o', 'G', 's'}

Set with the use of an Object: 
{'k', 'e', 'F', 'r', 'o', 'G', 's'}

Set with the use of List: 
{'Geeks', 'For'}

Set with the use of Tuple: 
{'Geeks', 'for'}

Set with the use of Dictionary: 
{'Geeks', 'for'}
​
  • Python has a set of built-in methods that you can use on sets: add, clear, copy, difference, difference_update, discard, intersection, intersection_update, isdisjoint, isubset, etc.
  • Once a set is created, you cannot change its items, but you can add new items.
  • To add one item to a set use the add() method
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)
Output:
{'orange', 'banana', 'cherry', 'apple'}
  • To add items from another set into the current set, use the update() method, e.g. add elements from tropical into thisset
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

Output:
{'banana', 'cherry', 'mango', 'papaya', 'apple', 'pineapple'}
  • To remove an item in a set, use the remove(), or the discard() method
thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Output:
{'cherry', 'apple'}
  • Other options: the clear() method empties the set; the del keyword will delete the set completely
  • Loop through the set, and print the values
thisset = {"apple", "banana", "cherry"}

for x in thisset:
  print(x)
banana
cherry
apple
  • The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)
Output:
{1, 2, 3, 'a', 'b', 'c'}
  • The intersection() method will return a new set, that only contains the items that are present in both sets.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.intersection(y)

print(z)

Output:
{'apple'}
  • The symmetric_difference_update() method will keep only the elements that are NOT present in both sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.symmetric_difference_update(y)

print(x)
Output:
{'banana', 'google', 'microsoft', 'cherry'}

Dictionaries

  • Dictionaries are used to store data values in key: value pairs.
  • A dictionary is a collection which is ordered (as of Python version 3.7), changeable and do not allow duplicates.
  • Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
  • To determine how many items a dictionary has, use the len() function.
  • The values in dictionary items can be of any data type.
  • From Python’s perspective, dictionaries are defined as objects with the data type ‘dict’
  • It is possible to use the dict() constructor to make a dictionary
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)
Output:
{'name': 'John', 'age': 36, 'country': 'Norway'}
  • You can access the items of a dictionary by referring to its key name, inside square brackets
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]
print (x)
Output:
Mustang
  • The keys() method will return a list of all the keys in the dictionary
x = thisdict.keys()
print (x)
Output:
dict_keys(['brand', 'model', 'year'])
  • The values() method will return a list of all the values in the dictionary
x = thisdict.values()
print (x)
Output:
dict_values(['Ford', 'Mustang', 1964])
  • Make a change in the original dictionary, and see that the values list gets updated as well
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Output:
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 2020])
  • Check if “model” is present in the dictionary
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")
Output:
Yes, 'model' is one of the keys in the thisdict dictionary
  • The update() method will update the dictionary with the items from the given argument
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})
print (thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
  • Adding an item to the dictionary is done by using a new index key and assigning a value to it
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
  • The pop() method removes the item with the specified key name:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}
  • The clear() method empties the dictionary:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)
Output:
{}
  • Make a copy of a dictionary with the copy() method:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
  • Add Items to a Python Dictionary with Different Data Types
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'Go'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'Life', '2': 'Python'}}
print("\nAdding a Nested Key: ")
print(Dict)

Output:
Empty Dictionary: 
{}

Dictionary after adding 3 elements: 
{0: 'Go', 2: 'For', 3: 1}

Dictionary after adding 3 elements: 
{0: 'Go', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value: 
{0: 'Go', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key: 
{0: 'Go', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Python'}}}
  • Dictionary Methods: clear, copy, fromkeys, get, items, keys, pop, popitem, setdefault, update, and values.

Arrays

  • An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. 
  • The array can be handled in Python by a module named array. 
  • A user can treat lists as arrays. However, the user cannot constrain the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type. 
  • This code below creates two arrays: one of integers and one of doubles. It then prints the contents of each array to the console:
import array as arr
a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
	print(a[i], end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ", end=" ")
for i in range(0, 3):
	print(b[i], end=" ")
Output:
The new created array is :  1 2 3 

The new created array is :  2.5 3.2 3.3 
  • Elements can be added to the Array by using built-in insert() function. Insert is used to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. append() is also used to add the value mentioned in its arguments at the end of the array. 
import array as arr
a = arr.array('i', [1, 2, 3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
	print(a[i], end=" ")
print()
a.insert(1, 4)
print("Array after insertion : ", end=" ")
for i in (a):
	print(i, end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
	print(b[i], end=" ")
print()
b.append(4.4)
print("Array after insertion : ", end=" ")
for i in (b):
	print(i, end=" ")
print()
Output:
Array before insertion :  1 2 3 
Array after insertion :  1 4 2 3 
Array before insertion :  2.5 3.2 3.3 
Array after insertion :  2.5 3.2 3.3 4.4 
  • In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array. The index must be an integer. 
import array as arr
a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])
Output:
Access element is:  1
Access element is:  4
Access element is:  3.2
Access element is:  3.3
  • Elements can be removed from the array by using built-in remove() function but an Error arises if element doesn’t exist in the set.
  • In Python array, there are multiple ways to print the whole array with all the elements, but to print a specific range of elements from the array, we use Slice operation. Slice operation is performed on array with the use of colon(:). To print elements from beginning to a range use [:Index], to print elements from end use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index:End Index] and to print whole List with the use of slicing operation, use [:]. Further, to print whole array in reverse order, use [::-1]. 
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
	print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th "
	"element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)

Output:

Initial Array: 
1 2 3 4 5 6 7 8 9 10 
Slicing elements in a range 3-8: 
array('i', [4, 5, 6, 7, 8])

Elements sliced from 5th element till the end: 
array('i', [6, 7, 8, 9, 10])

Printing all elements using slice operation: 
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

  • Read more about Python arrays here.

Loops

  • A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Loop through the letters in the word “banana”:
for x in "banana":
  print(x)
Output:
b
a
n
a
n
a
  • With the break statement we can stop the loop before it has looped through all the items:
#Exit the loop when x is "banana"
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

Output:
apple
banana
  • To loop through a set of code a specified number of times, we can use the range() function
for x in range(6):
  print(x)

Output:
0
1
2
3
4
5
  • The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter:
for x in range(2, 30, 3):
  print(x)
Output:
2
5
8
11
14
17
20
23
26
29
  • A nested loop is a loop inside a loop. The “inner loop” will be executed one time for each iteration of the “outer loop”:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
  • With the while loop we can execute a set of statements as long as a condition is true. Print i as long as i is less than 6:
i = 1
while i < 6:
  print(i)
  i += 1
Output:
1
2
3
4
5

Conditionals

  • Python Conditions and If statements support the usual logical conditions
    • Equals: a == b
    • Not Equals: a != b
    • Less than: a < b
    • Less than or equal to: a <= b
    • Greater than: a > b
    • Greater than or equal to: a >= b
  • If statement:
a = 33
b = 200
if b > a:
  print("b is greater than a")
Output:
b is greater than a
  • The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”
a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
Output:
a and b are equal
  • The else keyword catches anything which isn’t caught by the preceding conditions.
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")
Output:
a is greater than b
  • Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
  print("Both conditions are True")
Output:
Both conditions are True
  • Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
  print("At least one of the conditions is True")
Output:
At least one of the conditions is True
  • Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
  print("a is NOT greater than b")
Output:
a is NOT greater than b
  • You can have if statements inside if statements, this is called nested if statements
x = 41

if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")
Output:
Above ten,
and also above 20!

Functions

  • Python Function is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.
  • There are mainly two types of functions in Python.
    • Built-in library function: These are Standard functions in Python that are available to use.
    • User-defined function: We can create our own functions based on our requirements.
  • We can define a function using the def keyword
# A simple Python function
def fun():
	print("Welcome to Python")


# Driver code to call a function
fun()
Output:
Welcome to Python
  • You can pass data, known as parameters, into a function.
  • A function can return data as a result.
  • Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma:
def add(num1: int, num2: int) -> int:
	"""Add two numbers"""
	num3 = num1 + num2

	return num3

# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
# some more functions
def is_prime(n):
	if n in [2, 3]:
		return True
	if (n == 1) or (n % 2 == 0):
		return False
	r = 3
	while r * r <= n:
		if n % r == 0:
			return False
		r += 2
	return True
print(is_prime(78), is_prime(79))

Output:
False True
  • If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")
Output:
The youngest child is Linus
  • Keyword Arguments: You can also send arguments with the key = value syntax
def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
The youngest child is Linus
  • If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.
def my_function(**kid):
  print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")
Output:
His last name is Refsnes
  • You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Output:
apple
banana
cherry
  • To let a function return a value, use the return statement:
def my_function(x):
  return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
Output:
15
25
45
  • A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
#Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
Output:
15
  • Lambda functions can take any number of arguments:
#Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
Output:
30

Modules

  • Python Module is a file that contains built-in functions, classes and variables.
  • Consider a module to be the same as a code library. Let’s create a simple calc.py in which we define two functions, one add and another subtract.
# A simple module, calc.py
def add(x, y):
	return (x+y)

def subtract(x, y):
	return (x-y)

  • Save this code in a file named calc.py within the working directory.
  • Now, we are importing the calc that we created earlier to perform add operation.
# importing module calc.py
import calc

print(calc.add(10, 2))

Output:
12
  • The * symbol used with the import statement is used to import all the names from a module to a current namespace.
# importing sqrt() and factorial from the
# module math
from math import *

# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
  • Directories List for Modules: sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search for the required module.
# importing sys module
import sys
 
# importing sys.path
print(sys.path)
  • We can rename the module while importing it using the keyword.
# importing sqrt() and factorial from the
# module math
import math as mt

# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(mt.sqrt(16))
print(mt.factorial(6))
Output:
4.0
720
  • We can import specific names from a module without importing the module as a whole
# import only pi from math module
from math import pi

print(pi)

Output:
3.141592653589793

  • The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc.):
  • Let’s the dictionary person1 in calc.py
person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}
  • Running the code snippet
import calc as mymod

a = mymod.person1["age"]
print(a)

Output:
36

Conclusions

  • Python is a general-purpose and open source computer programming language. It is commonly used for both standalone programs and scripting applications in a wide variety of domains, by hundreds of thousands of developers worldwide.
  • This practical guide summarizes basics of Python programming. It is designed to serve as a concise collection of code examples to be a companion to other books, tutorials and other learning materials for aspiring data scientists.

The Road Ahead

  • Consider Step 2: 100 basic Python codes to try (coming soon).
  • Earn free online diploma in Python programming.
  • Check How Python Integrates with Other Technologies, Programming Languages and Third-Party Providers.
  • Have better understanding on using Python for cloud computing projects. The major merit of using Python is its ability to allow deployment of services irrespective of platforms used. You can execute Python in cloud. It is a huge advantage associated with Python.

References


Go back

Your message has been sent

Warning

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

€5.00
€15.00
€100.00
€5.00
€15.00
€100.00
€5.00
€15.00
€100.00

Or enter a custom amount


Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

Discover more from Our Blogs

Subscribe to get the latest posts sent to your email.

2 responses to “Basic Python Programming”

  1. TheDogGod avatar

    Great Read Can i leave my thoughts ?! –

    Thanks for reading , Love The Blog !!
    Thanks – TheDogGod – http://www.pomeranianpuppies.uk

    Liked by 1 person

    1. alxzp avatar

      Thanks for your feedback!

      Like

Leave a reply to TheDogGod Cancel reply

Discover more from Our Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading