DEV Community

Antony Sleeksville
Antony Sleeksville

Posted on

Python 101: Introduction to Modern Python.

What is Python?

Python is a popular programming language which was created by Guido van Rossum and released in 1991.
Python uses new lines to complete a command, uses whitespace to define scope; such as the scope of loops, functions and classes and relies on indentation.
When programming in python you don't need to define the type of a variable in python and it's not necessary to add a semicolon at the end of the statement.
Also when creating python program you must use .py extension and you can run the same program on the command line by typing myfirst_program.py
Python has a simple and relatively straightforward syntax which enhances its readability and increases productivity as it allows one to focus more on the problem rather than structuring the code.

Why choose python as your first programming languange

  • Python is easier to understand and write.
    a=1
    b=2
    sum = a + b
    print(sum)
Enter fullscreen mode Exit fullscreen mode
  • Python can run on multiple platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual machines.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
    a = 25
    b = 37
    print(f'Before swapping: a, b = {a},{b}')
    a, b = b, a
    print(f'After swapping: a, b = {a},{b}')
Enter fullscreen mode Exit fullscreen mode
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way.

What is Python used for?

  • Web Development : It can be used on a server to create web applications.
  • Database Management : It can connect to database systems. It can also read and modify files.
  • Data Analysis, Visualization and Wrangling : It can be used to handle big data and perform complex mathematics.
  • Workflow Analysis : It can be used alongside software to create workflows.
  • Artificial Intelligence and Automation
  • Desktop Application

Common features of Python

Simple and easy to learn

Python has a very simple syntax therefore it enable you to concentrate and think more about the code.

Portability

A single Python program can run on different platforms without any change in source code. A python code can work the same way regardless of where one and can be shared very easily.

Extensible and Embeddable

You can combine Python code with other programming languages like C or Java to increase efficiency. This allows high performance and scripting capabilities that other languages do not provide out of the box.

Free and open-source

Python is always available and free for everyone to use and also you can even change Python's source code to fit your needs.

High-Level Interpreted Language

Python itself handles tasks like memory management and garbage collection which are done by CPU hence it enables you to focus more on coding.

Object Orientation

Python assists one in the break-down of high complex real life problems which may be very critical by just a way of coding which makes one end up finding appropriate solutions required.

Rich library and large community

Python has numerous reliable built-in libraries which are free and accessible everywhere so you don't have to code everything by yourself.
Any aspect of python can be covered in Data Science, Machine Learning, Web Development and AI.

How to install Python?

Click HERE then choose your Operating system for example if on windows select Windows , Mac OS select MacOS , Unix/Linux selects Unix/Linux , Other Platforms select Others
After that click on the above links depending on your OS then select the type of release/version that you want and click on it to start downloading. Double click on the file to run the installer file and install.

N/B:

  • Remember to set up the path of the system variable to enable easier execution of python file and appropriate environment storage variable. Read more here on Path set-up.

  • You can use Integrated Developed Environments, IDEs such as Pycharm and Spyder to run python programs after its installation on your computer.

  • You can set up programming language interpreters such as VS Code, Notepad++ and Sublime text to edit and run python codes. For VS Code click Here.

How to check If Python is installed on your PC?

  1. On a Windows PC, search in the start bar for Python or run the following on the Command Line (cmd.exe):
C:\Users\SleeksC>python --version
Enter fullscreen mode Exit fullscreen mode
  1. On a Linux or Mac, open the command line on Linux or on Mac open the Terminal and type:
python --version
Enter fullscreen mode Exit fullscreen mode
NOTE:
  • If you find that you do not have Python installed on your computer, then you can download it for free Download Here.

  • If python is installed then you must get a similar output as seen below:

   C:\Users\SleeksC>python --version
   Python 3.9.10

   C:\Users\SleeksC>
Enter fullscreen mode Exit fullscreen mode

Lets Try The First Python Code

Now that Python is installed and running, lets go ahead and write our first Python program.

Let's create a very simple program called "Hello World" that gives an output Hello World! on the screen.

Start by typing the following code in any text editor or an IDE and save it as hello_world.py

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

Then run the file. You will get the following output.

   Hello World!
Enter fullscreen mode Exit fullscreen mode

As you can see on the screen there is the output "Hello World!"
An easy task right there like adding one plus one.

Python Statement, Indentation and Comments

Statement

A statement is an instruction given to a python interpreter to execute a certain program. examples are if statement, for statement, while statement,

For a multiple-line statement you use a continuation character (), or the line continuation may be implied incase you choose to use parentheses ( ), brackets [ ], and braces { } and also using semicolons in a single line can produce multiple statements as shown below:

   y = 10 + 20 + 30 + \
       40 + 50 + 60 + \
       70 + 80 + 90
Enter fullscreen mode Exit fullscreen mode
   Cars = ["Tesla", 
           "Mercedes",
           "Honda"]
Enter fullscreen mode Exit fullscreen mode
   x = 4; y = 5; z = 6
Enter fullscreen mode Exit fullscreen mode

Indentation

When programming in Python, indentation is something that you will use in order to be able to define a block of code, for instance in functions and loops which may starts with indentation and ends with the first un-indented line.

   planets =["mercury", "venus", "earth", "mars", "jupiter",]
   for i in planets:
           print(i)
Enter fullscreen mode Exit fullscreen mode

Sometimes, the use of four whitespaces are preferred for indentation over tabs as it makes the code more readable.

   if True:
      print(Sleeks Creations)
Enter fullscreen mode Exit fullscreen mode

Note that:

  • Python 3 doesn't allow mixing tabs and spaces for indentation.
  • When using indentation you should be careful and consistent throughout your code to avoid unnecessary syntax errors.

Comments

Comments are useful when writing a python code since it gives a clear explanation and description of a particular python code.
Python comment starts with the # symbol.
Comments helps many people even beginners to be able to understand the code by looking into the meaningful comments.
A comment may be on its own or the comment may start after a code in the same line and python goes on to ignores it or be placed at the end of a line, and Python will ignore the rest of the line:

   #This is a single line comment
   print(Lux Tech Academy)
Enter fullscreen mode Exit fullscreen mode
   print(Lux Tech Academy) #This is a single line comment
Enter fullscreen mode Exit fullscreen mode

A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code:

   #print(What day is today?)
    print(Thursday)
Enter fullscreen mode Exit fullscreen mode

For multiline comment you just add a # symbol for each line or another way is by using triple quotes either ''' or """ which is a multi-line string that is also used as a multi-line comment as well.

   #This multi-line comment is so long
   #that it continues after
   #the first page
   print(Good Morning World)
Enter fullscreen mode Exit fullscreen mode
   """This is a great example
      of a
      multi-line comment"""
      print(I enjoy coding everyday)
Enter fullscreen mode Exit fullscreen mode

Variables and Datatype

Variables

A variable in python is a container which is used for storing data values in memory. for example,

   number = 9
Enter fullscreen mode Exit fullscreen mode

In the above case, you created a variable named number and assigned it a value 9 to the variable.
The moment you assign a value to a variable then a Variable is created. Python has no command for declaring a variable.

   full_name = "sleeks creations"
   print(full_name)

   full_name = "mark anahiem"
   print(full_name)
Enter fullscreen mode Exit fullscreen mode

In the above program, we have assigned sleeks creations to the full_name variable initially. Then, the value is changed to mark anahiem.
You can also assign the different value to multiple variables at once and the same value to multiple variables as well.

  first_name, second_name, last_name = Ian, Mark, Anahiem
    print (first_name)
    print (second_name)
    print (last_name) 
Enter fullscreen mode Exit fullscreen mode
    x = y = z = 9
      print (x)
      print (y)
      print (z)
Enter fullscreen mode Exit fullscreen mode

Data types in Python

Different values in Python has different datatypes.
Data type is an important in python programming as classes whereas variables are instance/object of these classes.
You can get the data type of any object by using the type() function.

   a = 10
   print(type(a))
Enter fullscreen mode Exit fullscreen mode

In the above example this will print the data type of the variable a which is class 'int'
Python has the following data types built-in by default in the PC.

  • 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

In python, the type() function is used to check and identify which class a variable or a value belongs to and the isinstance() function is used to check if an object belongs to a particular class.

   x = 27
   print(x, "is of type", type(x))

   x = 9.0
   print(x, "is of type", type(x))

   x = 3+6y
   print(x, "is complex number?", isinstance(3+6y,complex))
Enter fullscreen mode Exit fullscreen mode

Python Operators

Operators help in processing variables and values. For example, if you have two numeric variables, they can be added or subtracted, multiplied or divided. These operations change the value and give out new values.

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators

Arithmetic operators

Mathematical operations like addition, subtraction are performed using arithmetic operators.

   x = 18  
   y = 7  

print (x + y)    # addition  
print (x - y)     # subtraction  
print (x * y)     # multiplication  
print (x / y)      # division  
print (x % y)    # modulus  
print (x ** y)   # exponentiation  
print (x // y)    # floor division  
Enter fullscreen mode Exit fullscreen mode

Modulus operation returns the remainder of dividing two numbers . Similarly, floor division is integer division, which returns the result of division as whole integer (18 // 7 = 2).

Assignment operators

Values or variable content can be assigned to another variable using assignment operators.

    a = 7  # assign value to a  
    b = a  # assign value of a into b  
  c = a + b -2  # calculate an expression and place result into c  

   b += 2   # equivalent to b = b + 2  
   b -= 2    # equivalent to b = b - 2  
   b *= 2   # equivalent to b = b * 2  
   b /= 2    # equivalent to b = b / 2  
   b %= 2   # equivalent to b = b % 2  
   b //= 2   # equivalent to b = b // 2  
   b **= 2  # equivalent to b = b ** 2  
   b &= 2   # equivalent to b = b & 2  
   b |= 2    # equivalent to b = b | 2  
   b ^= 2    # equivalent to b = b ^ 2  
   b >>= 2  # equivalent to b = b >> 2  
   b <<= 2  # equivalent to b = b << 2  
Enter fullscreen mode Exit fullscreen mode

Comparison operators

Two values are compared and the result is a Boolean value True or False.

Used in if and loop statements to make decisions.

    x = 5  
    y = 9  

print(x == y)  # true if x and y are equal  
print(x != y)  # true if x and y are not equal  
print(x > y)  # true if x is greater than y  
print(x < y)  # true if x is less than y  
print(x >= y)  # true if x is greater than or equal to y  
print(x <= y)  # true if x is less than or equal to y  
Enter fullscreen mode Exit fullscreen mode

Here is an example that checks if x is less than y. If this condition is satisfied(true) then it execute the statement. Otherwise execute another statement.

    x = 5 
    y = 9 

if(x < y):  
    print("x is less than y");  
else:  
    print("x greater than or equal to y")  
Enter fullscreen mode Exit fullscreen mode

Logical operators

Two or more comparison operations can be combined using logical operators. These logical operators return Boolean value.

    a = 6 
    b = 10 

# True if both conditions are true  
print(a > 3 and a < 7)  

# True if one condition is true  
print(a > 6 or b < 7)  

# True if given condition is false (inverse of given condition)  
print(not(a > 3))  
Enter fullscreen mode Exit fullscreen mode

Identity operators

Identity operators compare if two objects are the same. They need to point to the same location.

 x = ["Hi", "Team"]  
 y = ["Hi", "Team"]  
 z = x 


# prints true as both are same element  
print(x is z)  

# prints false as they are two different values  
# content may be same, but value locations are different  
print(x is y)  

# comparing the values gives true  
print(x == y)  

# not negates the comparison result  
# if two variables are not same, then result is true  
print(x is not z)  
print(x is not y)  
Enter fullscreen mode Exit fullscreen mode

Python conditional statements

These commands help you make decisions based on conditions such as ‘if’ a specific condition occurs then you have to perform a set of operations, ‘else’ you have to perform another set of operations.
First, you will define some variables and assign values to them. Next, you will perform some basic ‘if’ ‘else’ operations on these variables.
for example:-

   x=100
   y=200

if (y>x):
    print (y is greater than x) 
Enter fullscreen mode Exit fullscreen mode

In the above example since the condition is true therefore you will get the output.

   y is greater than x
Enter fullscreen mode Exit fullscreen mode

Now try the ‘if’ function with a false statement

   if (x>y):
    print (x is greater than y)
Enter fullscreen mode Exit fullscreen mode

For this statement, you will not get an output since the if condition used is false.
Now include the else statement.

   x=100
   y=200
   if (x>y):
    print (x is greater than y)
else:
    print (y is greater than x)
Enter fullscreen mode Exit fullscreen mode

For ‘elif’ function for multiple conditions then you have:

   x=1
   y=2
   z=3

if (x>y) & (x>z):
    print (x is the greatest value)
elif (y>x) & (y>z):
    print (y is the greatest value)
else: 
    print (z is the greatest value)
Enter fullscreen mode Exit fullscreen mode

Loops in Python

A python loop allows you to execute a statement or group of statements multiple times.
In a loop, statements are executed sequentially, the first statement in a function is executed first, followed by the second statement and so on.

While loop
The while loop is kind of similar to if statement, it executes the code inside, if the condition is True. However, as opposed to the if statement, the while loop continues to execute the code repeatedly as long as the condition is True.
for example:

   p = 1.0
while p < 11.0 :
      p = p + 1
      print(p)
Enter fullscreen mode Exit fullscreen mode

Using the break statement you can stop the loop even if the while condition is true.

   p = 1.0
while p < 11.0 :
      p = p + 1
      if p == 5.0:
    break

      print(p)
Enter fullscreen mode Exit fullscreen mode

Using the continue statement you are able to stop the current iteration, and continue with the next.

   p = 1.0
while p < 11.0 :
       p = p + 1

      if p == 5.0:
      continue
      print(p)
Enter fullscreen mode Exit fullscreen mode

while loops can also have an optional else block.
The else part is executed if the condition in the while loop statement is false.
The while loop can be terminated with a break statement. In such cases, the else part is ignored.
The while loop's else part runs if no break occurs and the condition is false.

   p = 1
while p < 5:
  print(p)
  p = p + 1
else:
  print("p is not less than 5")
Enter fullscreen mode Exit fullscreen mode

In the above example, Inside loop is executed three times since the condition is still true but on the fourth iteration, the condition in while becomes false, therefore the else part is executed.

For loop
The for loop in Python is used to iterate over a sequence (list, tuple, string, set) or other iterable objects.

 fam = [5.7, 5.9, 6.2, 6.4]
 for height in fam:
       print(height)
Enter fullscreen mode Exit fullscreen mode

Looping through a String is possible since strings contain a sequence of characters.

   for i in "apple":
   print(i.capitalize())
Enter fullscreen mode Exit fullscreen mode

To loop through a set of code a specified number of times, you use the range() function that returns a sequence of numbers, starting from 0 by default, and increases by 1 through the iteration and ends at a specified number.

for y in range(10):
  print(y)
Enter fullscreen mode Exit fullscreen mode
    genre = ['jazz', 'rock', 'pop']
for i in range(len(genre)):
     print("I listen to", genre[i])
Enter fullscreen mode Exit fullscreen mode

A for loop can have an optional else block as well. The else part is executed if the elements in the sequence used in the for loop are exhausted.
The break keyword can be used to stop a for loop and in such cases, the else part is ignored.
A for loop's else part runs if no break occurs if break keyword has not been applied.

for y in range(10):
  print(y)
else:
  print("The End")
Enter fullscreen mode Exit fullscreen mode
for y in range(10):
  if y == 6: 
      break
      print(y)
else:
  print("Complete")
Enter fullscreen mode Exit fullscreen mode

Python List

A list is a way to give a single name to a collection of values. These values or elements can have any data type; int, float, etc., and also more advanced Python types, even other lists.
Lists allows you to use multiple of elements at once with all the information stored in the python list and is created by placing elements inside square brackets [], separated by commas.

   my_first_list = ['HTML', 'CSS', 'Javascript', 'Python']
   my_second_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
   my_third_list = [1, "Good Afternoon", 9.0]
   my_nested_list = ["Happy Weekend", [9, 18, 27], ['a']]
   print(my_first_list)
   print(my_second_list)
   print(my_third_list)
   print(my_nested_list)
Enter fullscreen mode Exit fullscreen mode

List items are ordered, changeable, and allow duplicate values.
Python list indices start at 0, and lists can be sliced, concatenated and so on.
An indexed list can be accessed by referring them using index number and remember that a list having 4 elements will have an index from 0 to 3.

  days = ['monday', 'tuesday', 'wednesday', 'thursday']
  print(days[0])  
  print(days[2])  
  print(days[4]) 
Enter fullscreen mode Exit fullscreen mode

In python, negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.

   colors = ['black','brown','white','blue','violet']
   print(colors[-1])
   print(colors[-3])
Enter fullscreen mode Exit fullscreen mode

To remove a list element, you can use either use the del statement if you know exactly which element(s) you are deleting or the remove() method which removes the specified item.

   cars = ["Mercedes", "Toyota", "Tesla", "Honda"]
   del cars[2]
   print(cars)

   del cars[1:3]
   print(cars)

   del cars
   print(cars) 
Enter fullscreen mode Exit fullscreen mode
   cars = ["Mercedes", "Toyota", "Tesla", "Honda"]
   cars.remove("Toyota")
   print(cars)

   cars.pop(1)
   print(cars)
Enter fullscreen mode Exit fullscreen mode

In order for you to slice a range of items in a List you must use the slicing operator [:].

  fruits = ["apple", "pears", "cherry", "orange", "kiwi", "plums"]
  print(fruits[2:4])
  print(fruits[4:])
  print(fruits[:])
Enter fullscreen mode Exit fullscreen mode

To add a single item to a list, you will have to use the append() method or add multiple items then use the extend() method.

   even = [2, 4, 6]

   even.append(8)
   print(even)

   even.extend([10, 12, 14])
   print(even)
Enter fullscreen mode Exit fullscreen mode

Python Tuples

Tuples, just like lists, are used to store multiple items in a single variable.
The difference between tuples and lists is that you cannot change or modify the elements of a tuple once it is assigned while you can change the elements of a list.
A tuple is created by placing all the elements inside parentheses (), separated by commas. The use of parentheses in creating tuples are optional.
A tuple can have any number of items and they may be of different types such as integer, float, list and string.

    tuple1 = ('HTML', 'Java', 'C++', 'Python')
    tuple2  = (0, 1, 2, 3, 4, 5)
    tuple3  = (9, "Good Day", 4.0)
    tuple4  = ("Happy Weekend", [36, 45, 54], ['x'])
   print(tuple1)
   print(tuple2)
   print(tuple3)
   print(tuple4)
Enter fullscreen mode Exit fullscreen mode

An example of a tuple created without using parentheses

   tuple5= True, False, False
   print(tuple5)

   a, b, c = tuple5
   print(a)
   print(b)
   print(c)
Enter fullscreen mode Exit fullscreen mode

Tuple items are ordered, unchangeable, and allow duplicate values.

   my_tuple = ("hi",)
   print(type(my_tuple))

   my_tuple = ("hi")
   print(type(my_tuple))
Enter fullscreen mode Exit fullscreen mode

In the above program, you will need to use a comma to tell python that you are creating a tuple with a single item, otherwise, python will not recognize it as a tuple.
In order to access an element in a tuple always use index operator [], where the index starts from 0.

   mytuple = (man, woman, boy, girl, child)
   print(mytuple[0])    
   print(mytuple[4])   
Enter fullscreen mode Exit fullscreen mode

Negative indexing in python tuple is similar to that one on lists.
The index of -1 refers to the last element, -2 to the second last element and so on.

   tuple = ('how', 'why', 'where', 'which', 'when', 'whom')
   print(tuple[-1])
   print(tuple[-4])
Enter fullscreen mode Exit fullscreen mode

Once a tuple is created, you cannot change its values due to its unchangeable/immutable characteristic, however you can convert the tuple into a list, change the list, and convert the list back into a tuple.

   mytuple = ("Lead", "Copper", "Iron")
   b = list(mytuple)
   b[2] = "silver"
   mytuple= tuple(b)

   print(mytuple)
Enter fullscreen mode Exit fullscreen mode

In order to access a range of elements in a tuple by using the slicing operator colon [:].

  mytuple = ('Iron', 'Copper', 'Silver', 'Gold', 'Bronze', 'Lead')

  print(mytuple[1:4])
  print(mytuple[:-4])
  print(mytuple[4:])
  print(mytuple[:])
Enter fullscreen mode Exit fullscreen mode

For concatenation or combining two tuples then you can use + operator.

    tuple1 = ("a", "b" , "c")
    tuple2 = (1, 2, 3)

    tuple3 = tuple1 + tuple2
    print(tuple3)
Enter fullscreen mode Exit fullscreen mode

In python to repeat elements in a tuple for a given number of times then use the * operator.

Both + and * operations result in a new tuple.

   color = ("black", "brown", "white")
   tuple4 = fruits * 2

   print(tuple4)
Enter fullscreen mode Exit fullscreen mode

Since you cannot change the elements in a tuple. This means that you cannot delete or remove elements from a tuple.
To delete the entire tuple use the keyword del.

   thistuple = ("Lead", "Copper", "Iron")
   del thistuple
   print(thistuple) 
Enter fullscreen mode Exit fullscreen mode
   thistuple = ("Lead", "Copper", "Iron")
   z = list(thistuple)
   z.remove("Lead")
   thistuple = tuple(z)

   print(thistuple)
Enter fullscreen mode Exit fullscreen mode

Python Sets

In a set, a single variable used to store several items.
The difference of sets in comparison to lists and tuples is that sets cannot have multiple occurrences of the same element(duplicates or repeating items) and can store unordered values.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.
Set elements are unchangeable, but you can remove elements and add new elements.
A set is created by using the built-in set() function or placing all the elements inside curly brackets {}, separated by comma.
Sets can have any number of items including different types like integer, float, tuple and string.

   thisset = {"pnemunomia", "typhoid", "malaria"}
   print(thisset)


   thisset = {4.3, "Hi", (x, y, z)}
   print(thisset)

   thisset = {"pnemunomia", "typhoid", "malaria", "pnemunomia"}
   print(thisset)
Enter fullscreen mode Exit fullscreen mode
    set1 = {"Andrew", "Mark", "Ian"}
    set2 = {9, 18, 27, 36, 45}
    set3 = {True, False, True}

    print(set1)
    print(set2)
    print(set3)
Enter fullscreen mode Exit fullscreen mode

To make a set without any elements, we use the set() function without any argument.

   myset = set(("Kenya", "Tanzania", "Uganda"))  
   print(myset)
Enter fullscreen mode Exit fullscreen mode
    myset1 = {"Kenya", "Tanzania", "Uganda"}
    print(type(myset1))
Enter fullscreen mode Exit fullscreen mode

Once a set is created, you cannot change its elements, but you can add new items by using the add() method.

   my_set = {1, 2, 3, 4}
   my_set.add(5)
   print(my_set)

   my_set.update([6, 7, 8])
   print(my_set)

   my_set.update([9, 10], {11, 12, 14})
   print(my_set)
Enter fullscreen mode Exit fullscreen mode

To remove an item in a set, use the remove(), or the discard() method. If the item to remove does not exist, remove() will raise an error therefore use discard() that will not raise an error.

   myset = {"pnemunomia", "typhoid", "malaria"}
   myset.remove("typhoid")
   print(myset)

   myset.discard("typhoid")
   print(myset)
Enter fullscreen mode Exit fullscreen mode

In python to remove the last item in a set use the pop() method:

    thisset = {"pnemunomia", "typhoid", "malaria"}
    a = thisset.pop()
    print(a)
    print(thisset)
Enter fullscreen mode Exit fullscreen mode

In order to delete the whole set then you use the clear() method which empties the set:

   myset = {"pnemunomia", "typhoid", "malaria"}

   myset.clear()

   print(myset)
Enter fullscreen mode Exit fullscreen mode

Python Dictionary

Python dictionary is collection of items where each item of a dictionary has a key/value pair that stores data values in those key:value pairs.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
A dictionary is like an associative array where each key stores a specific value and cannot be indexed by a sequence of numbers but indexed based on keys.
To be able to create python dictionary just place items inside curly brackets {} and separate them with commas.

   pop = [1.40, 332, 1.42]

   countries = ["India", "Usa", "China"]

   world = {"India":1.40, "Usa":332, "China":1.42}

   world["China"]
Enter fullscreen mode Exit fullscreen mode
   dict = {"brand": "Ford",
  "model": "Mustang",
  "year": 2022
}
print(dict)
Enter fullscreen mode Exit fullscreen mode
 mydict = {'name': 'Lux Tech College', 1: [a, b, c]}
 print(mydict)
Enter fullscreen mode Exit fullscreen mode
  my_dict1 = dict({1:'gold', 2:'diamond'})
  my_dict2 = dict([(1,'gold'), (2,'diamond')])

  print(my_dict1)
  print(my_dict2)
Enter fullscreen mode Exit fullscreen mode

Dictionaries cannot have two items with the same key and thereby when items are duplicated on a key it overwrites the existing value.

  dict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1965,
  "year": 2022
}
  print(dict)
Enter fullscreen mode Exit fullscreen mode

As a result of dictionaries being mutable then you can be able to add a new item or change the value of existing items using an assignment operator. In any case the key is already present, then the existing value gets updated and if not a new (key: value) pair is added to the dictionary.

   mydict = {'name': 'Mark', 'age': 30}

   mydict['age'] = 27
   print(mydict)

   mydict['address'] = 'Halem, New york'
   print(mydict)
Enter fullscreen mode Exit fullscreen mode
  dict = {"brand": "Ford",
  "model": "Mustang",
  "year": 2022
}
  dict["color"] = "black"
  print(dict)
Enter fullscreen mode Exit fullscreen mode

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
These are methods to remove items from a dictionary:

  • pop() method which removes the item with the specified key name:
  dict = {"name": "Mark", "age": 30, "yob": 1992, "country": "Uganda"}
  dict.pop("yob")
  print(dict)
Enter fullscreen mode Exit fullscreen mode
  • The clear() method empties the dictionary:
   dict = {"name": "Mark", "age": 30, "yob": 1992, "country": "Uganda"}
   dict.clear()
   print(dict)
Enter fullscreen mode Exit fullscreen mode
  • The popitem() method remove an arbitrary item and returns (key, value)
dict = {"name": "Mark", "age": 30, "yob": 1992, "country": "Uganda"}
dict.popitem()
print(dict)
Enter fullscreen mode Exit fullscreen mode
  • The del keyword removes the item with the specified key name and can also delete the dictionary completely:
dict = {"name": "Mark", "age": 30, "yob": 1992, "country": "Uganda"}
del dict["yob"]
print(dict)

del dict
print(dict) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)