Welcome to Python 101! — Lets get started with the basics

wekesa360

Michael Abraham Wekesa

Posted on April 16, 2022

Welcome to Python 101! — Lets get started with the basics

Python is a high-level programming language, in layman's language, it is closer to human understanding(English like) than it is to machines. Python is an interpreted language and a general purpose programming language.

A brief history of python

Python is programming language that came into life in the 1980s and was developed by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands, with the ideology of it being a successor to the ABC programming language.

Since then python has evolved through several versions to the latest version python 3.10 (as of the time of writing this article) with a first release date of 4 October, 2021

Python 2.0, released 16 October 2000, with new features including a cycle-detecting garbage collector for memory management and support for Unicode.

Python 3.0, released on 3 December 2008.With this version there was massive revision that it was not backward compatible with previous python versions.

Before we get our hands dirty, let's set some rules of engagement, shall we!

Syntax in Python

Python has a very simple and user friendly syntax, that you'll find simple and easy to grasp.
Some include:

  • Indentation in python is crucial, it can break your code!

  • Python is case sensitive, State and state are different

  • All variables should start with a lowercase letter

  • classes begin with capital letters

  • The standard is to actually use English names in programming

Identifiers (names you define for variables, types, functions, and labels) should not be keywords in python and start with a symbol or number.

For more on style and best practices in python check out on PEP-8

Installing python

Python Basics

Base types

  1. int (integer)
value = 76
Enter fullscreen mode Exit fullscreen mode
  1. float
value = 56.21
Enter fullscreen mode Exit fullscreen mode
  1. bool (boolean)
is_blue = True
Enter fullscreen mode Exit fullscreen mode
  1. str (string)
message = "Hello world!"
Enter fullscreen mode Exit fullscreen mode

Backslash is used for escaping characters.
e.g

  • \' - Single quote
  • \b - backspace
  • \n - new line
  • \r - carriage return
  • \t - tab
message = " \t Sammy\'s cat ran away\nand into the bush it went.\n"
# print - an inbuilt function to print an output
print(message)
Enter fullscreen mode Exit fullscreen mode
# output
#     Sammy's cat ran away
# and into the bush it went.
Enter fullscreen mode Exit fullscreen mode

Multiline strings

   message = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
   sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
   Ut enim ad minim veniam, 
   quis nostrud exercitation ullamco laboris nisi ut 
   aliquip ex ea commodo consequat."""
Enter fullscreen mode Exit fullscreen mode

Sequence types

  1. list

Lists are modifiable and can hold values of different types.

list_country = ["Russia",  "South Africa", "Japan", "Peru"]
random_list  = ["x", 3.14, 4, False, "No way"]
Enter fullscreen mode Exit fullscreen mode
  1. tuple

Tuples cannot be modified once created. They are immutable.

coordinates = (33.56, 4.56, 21.89)
Enter fullscreen mode Exit fullscreen mode
  1. range

Is a function returning a sequence of numbers, starts from 0 and increments by 1 by default.
Format: range(start, stop, step)

for x in range(0,10,2):
    print(x)
Enter fullscreen mode Exit fullscreen mode

Mapping types

Dictionary

Is a collection of data that is stored in key-value pair, key is unique
e.g "Laptop" is the key and "Mac book" the value.

backpack = {"Laptop":"Mac book", "Headphones": "Sony",  "Hard drive": "SSD"}
Enter fullscreen mode Exit fullscreen mode

Set types

  1. set

A set is an unordered collection that is mutable, iterable and has unique elements.

fruits = {"apple", "mango", "orange"}
Enter fullscreen mode Exit fullscreen mode

2.frozen-set

Freezes the elements, making them unchangeable.

fruits = ({"apple, "mango", "orange"})
Enter fullscreen mode Exit fullscreen mode

Conversions

Change a value of one data type to another.

""" 1.str to int"""
int("10") #output: 10

""" 2. float to int"""
int(10.34) #output: 10

""" 3. any data type to str"""
str(10.10) #output: "10.1"
str(3==3) #output:  "True"

""" 4. character to ASCII code """
ord('*') #output: 42

""" 5. string to list"""
message = "Hello world!"
message_list = list(message)
# print- print output
print(message_list)
# output
# ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']

""" 6. dictionary to list """
day = {"day":14, "month": "Feb", "year": 2022}
# create a list with list compression
generated_list = [(x, y) for x, y  in day.items()]
# print - print output
print(generated_list)
# output
# [('day', 14), ('month', 'Feb'), ('year', 2022)]

""" 7. list to string """
word_list = ["The", "new", "version", "of", "slack", "is", "amazing"]
word_str = " ".join(word_list)
print(word_str)
# output
# The new version of slack is amazing

""" 8. list to set """
number_list = [34, 45, 67 ,87]
number_set = set(number_list)
print(number_set)
# output
# {34, 67, 45, 87}

""" 9. list to dictionary """
day_list = [('day', 14), ('month', 'Feb'), ('year', 2022)]
day_dict = dict(day_list)
print(day_dict)
# output
# {"day":14, "month": "Feb", "year": 2022}
Enter fullscreen mode Exit fullscreen mode

Working with Strings

There are several ways in which strings can be manipulated.

print("Hello")

# output
# Hello

print("Hello", "world", "!")

# output
# Hello world !

print("Hello", "world", sep="-")

# output
# Hello-world

print("Hello") # for every print, output is set to a new line
print("world")

# output
# Hello
# World

print("Hello", "world", sep="-", end="!") 

# output
# Hello-world!

print("Hello", end=" ") # without new line
print("World")

# output
# Hello world
Enter fullscreen mode Exit fullscreen mode

String Concatenation

String concatenation is the operation of joining character strings end-to-end.(wikipedia)

first_name = "John"
middle_name = "Magarita"
last_name = "Omondi"

print(first_name + " " + middle_name + " " + last_name)

# output
# John Magarita Omondi
Enter fullscreen mode Exit fullscreen mode

String formatting

first_name = "John"
middle_name = "Magarita"
last_name = "Omondi"
salary = 50000
print("{0} {1} earns a salary of ${2}".format(first_name, middle_name, salary))

# output
# John Magarita earns a salary of $50000
Enter fullscreen mode Exit fullscreen mode

With knowing the basics of python, you can write simple command line programs
for example:

Simple mad-libs generator program

""" A simple word game that takes user input based on the word type and 
inserting in to a paragraph """

noun1 = input("Enter a noun(Plural): ")
place = input("Enter a place: ")
noun2 = input("Enter a noun: ")
noun3 = input("Enter a noun(Plural): ")
adjective1 = input("Enter an Adjective: ")
verb1 = input("Enter a verb: ")
verb2 = input("Enter a verb: ")
number = input("Enter a number: ")
adjective2 = input("Enter an Adjective: ")
body_part = input("Enter a body part: ")
verb3 = input("Enter a verb: ")

mad_lib = """Two {0}, both alike in dignity,
In fair {1} where we lay our scene,
From ancient {2} break to new mutiny,
Where civil blood makes civil hands unclean.
From forth the fatal loins of these two foes
A pair of star-cross`d {3} take their life;
Whole misadventured piteous overthrows
Do with their {4} bury their parents` strife.
The fearful passage of their {5} love,
And the continuance of their parents` rage,
Which, but their children`s end, nought could {6},
Is now the {7} hours` traffic of our stage;
The which if you with {8} {9} attend,
What here shall {10}, our toil shall strive to mend. """.format(noun1, place, noun2, noun3, adjective1, verb1, verb2,number, adjective2,body_part, verb3)

print("\n====Mad Lib (Romeo and Juliet: Prologue Ad-lib) ====\n")
print(mad_lib)
Enter fullscreen mode Exit fullscreen mode

Conclusion

Python is an amazing multi-purpose programming language that can be used in almost all fields in technology, from AI to scripting and data science. The best part is, it is fun to learn and user-friendly.
Happy coding!

💖 💪 🙅 🚩
wekesa360
Michael Abraham Wekesa

Posted on April 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to level up your backend skills
webdev How to level up your backend skills

November 16, 2024

Hello DEV Community!
cybersecurity Hello DEV Community!

September 5, 2024

Conditions (If-else-elif) Part-08
beginners Conditions (If-else-elif) Part-08

September 4, 2024