Introduction To Python Programming - Part 2
A Primer on Python programming for beginners
Hello, and welcome to Part two of the series “Introduction to Python Programming.” If you have not gone through the previous episode, kindly find the link below to part one.
Introduction to python programming - part one
Python Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable. You just need the equals to ‘=’ sign to assign a variable.
Name = "Akinnimi"
Age = 20
print(age) #retuns 20
Unlike some other programming languages, variables in Python can change after they have been set.
x = 200 # x is of type int
x = "Stefan" # x is now of type str
print(x) #returns Stefan
#x will overwrite x
Casting
You can change the data type of a particular variable by typecasting it.
a = str(6) # a will be '6'
b = int(6) # b will be 6
c = float(6) # c will be 6.0
Case-Sensitive
Variable names are case-sensitive.
This will create two variables
a = 4
A = "Sally"
#A will not overwrite a
Comments
To make comments in Python, the # symbol is placed in front of the sentence. Python reads and ignores the sentence.
The purpose of comments is for code documentation. It can also be used to explain what a particular code is doing.
#printing out Hello World!
print("Hello, World!")
Multiline Comments
To add a multi-line comment, you could insert a # for each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
You can use a multiline string.
"""
Writing out my first Python program
Printing out Hello World!
This is going to be fun
"""
print("Hello, World!")
Python will read the code but ignore it if the text is not assigned to a variable, and you have written a multiline comment.
Python Data Types
Data types in Python specify the kind of value a variable can hold.
Python has several built-in data types:
a. Numeric Types:
int: Integers, e.g., 5, -10.
float: Floating-point numbers, e.g., 3.14, -0.5.
b. Text Type:
str: Strings, e.g., "Hello, World!".
c. Boolean Type:
Boolean values are TRUE or FALSE
d. Sequence Types:
list: Ordered, mutable collections, e.g., [1, 2, 3].
tuple: Ordered, immutable collections, e.g., (1, 2, 3).
e. Mapping Type:
dict: Key-value mappings, e.g., {'name': 'Alice', 'age': 30}.
f. Set Types:
set: Unordered, variable collections of one-of-a-kind elements.
frozen set: Unordered, immutable groupings of distinct components.
g. Binary Types:
bytes: Unchangeable sequences of bytes, such as b'programming'.
bytearray: Mutable sequences of bytes.
memoryview: Provides a view into the memory of an object supporting the buffer protocol.
h. Custom Types:
User-defined classes and objects.
i. Special Types:
NoneType: Represents the absence of a value, denoted by None.
a. Python Numbers
There are three numeric types in Python:
int
float
complex
a = 50 # int
b = 3.5 # float
C = 18j #complex
Get the type
In Python, use the type() method to determine the type of any object:
print(type(a)) #returns <class 'int'>
print(type(b)) #returns <class 'float'>
print(type(c)) #returns <class 'complex'>
Int
An integer is a whole number, positive or negative, with no digits and an infinite length.
a = 5
b = 4566677788889
c = -456667
print(type(a)) #returns <class 'int'>
print(type(b)) #returns <class 'int'>
print(type(c)) #returns <class 'int'>
Float
A float, often known as a "floating point number," is a positive or negative number with one or more decimals.
a = 1.20
b = 2.5
c = -50.8
print(type(a)) #returns <class 'float'>
print(type(b)) #returns <class 'float'>
print(type(c)) #returns <class 'float'>
Complex
Complex numbers are denoted by a "j" as the imaginary part:
a = 16+5j
b = 3j
c = -10j
print(type(a)) #returns <class 'complex'>
print(type(b)) #returns <class 'complex'>
print(type(c)) #returns <class 'complex'>
Type Conversion
You can convert from one type to another with the int() and float() methods:
a = 5 # int
b = 5.3 # float
c = -10j #complex
#convert from int to float:
x = float(a)
#convert from float to int:
y = int(b)
#convert from int to complex:
z = complex(a)
#printing out thier values
print(x) #returns 5.0
print(y) #returns 5
print(z) #returns (-0-10j)
#checking their data type
print(type(x)) #returns <class 'int'>
print(type(y)) #returns <class 'float'>
print(type(z)) #returns <class 'complex'>
b. Python Strings
In Python, strings are wrapped by either single or double quotation marks.
‘world’ is the same as "world".
Using the print() function, you can display a string literal:
print("Hello") #returns Hello
print('Hello') #returns Hello
Assign String to a Variable
a = "Hello"
print(a) #returns Hello
Multiline Strings
Using three quotes, you can assign a multiline string to a variable:
a = """ Lorem derrym dssaawe ddfrty,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt."""
print(a)
Or three single quotes:
a = ' ' ' Lorem derrym dssaawe ddfrty,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt.' ' '
print(a)
String Length
Use the len() method to determine the length of a string.
a = "Hello, World!"
print(len(a)) #returns 13
#you will notice the whitespace between the Hello World is also counted.
String Concatenation
To concatenate or combine two strings, use the + operator.
Merging two variables together with the + sign
a = "Hello"
b = "World"
c = a + b
print(c) #returns HelloWorld
#notice there is no space in between the hello world.
#We will solve that in the next section.
To add space between the Hello World, add two “ “
first_name = "Emmanuel"
Last_name = "Akinnimi"
My_name =first_name + " " + Last_name
print(My_name) #returns Emmanuel Akinnimi
#space is now added
Modifying Strings
To modify a string, you have to call a string method on it.
strip() #removes whitespace in strings
capitalize() #Converts the first letter of each word to capital letter
upper() #converts all the letters in the word to capital case.
lower() #converts all the letters in the word to lower case.
Example:
Name = “akinnimi stefan”
print(Name.capitalize()) #returns Akinnimi Stefan
print(Name.upper()) #returns AKINNIMI STEFAN
print(Name.lower()) #returns akinnimi stefan
Check String
We can use the method IN to see if a specific phrase or character is contained in a string.
favorite= "My favorite food is mash potatoes"
print("food" in Favorite )
Python: Escape Characters
Use an escape character to insert characters that are not allowed into a string.
"""You will get an error when nesting double
quotes inside another double quotes
"""
txt = “I am going to the “stadium” to watch the football match”
print(txt) #returns an error
The solution is to use the \ backlash before the illegal character is inserted.
txt = “I am going to the \“stadium\” to waatch the football match”
print(txt)
Escape Characters
Other escape characters used in Python:
Code | Result |
\' | Single Quote |
\ | Backslash |
\n | New Line |
\t | Tab |
\b | Backspace |