Python Programming for Everyone
- Name
- Jobayer Hossain
- @Jobayer977
Python is dynamically typed, interpreted, and garbage-collected programming language. It is a general-purpose programming language that can be used for multiple purposes. It is commonly used for web development (server-side), software development, mathematics, system scripting and Artificial Intelligence more.
Setting Up Python
First, we need to install python on our computer. You can download python from here (opens in a new tab). After downloading, install it on your computer. You can check the installation by running the following command on your terminal.
python --version
After installing python, in latest version of python it will be python3. So in terminal you will see something like this.
Python 3.9.1
Hello World
Now we will write our first program in python. We will write a simple program that will print "Hello World" in the terminal. Open your IDE or text editor i will use VS Code. Create a file named hello.py
and write the following code.
print("Hello World")
Now run the following command in your terminal.
python3 hello.py
You will see the following output in your terminal.
Hello World
Here we have used print
function to print the string "Hello World". In python we can use single quote or double quote to write a string. So we can write the above code like this.
print('Hello World')
Variables
Variables are which value can be changed. We can store any value in a variable. Think of a variable like a box with a label. The box can hold different things like coffee, Orange, or apple. The label tells us what's inside. So, if you have a box labeled "apple," you know there's an apple inside. Similarly, in Python, a variable is like a labeled box that holds information, like numbers or words, which we can use in our computer programs.
So we will start by defining a variable named box
and assign a value to it.
box = "apple"
Here the box
is the variable name and "apple"
is the value. We can also assign a number to a variable.
boxCapacity = 10
We cna use print
function to print the value of a variable like how we printed "Hello World" in the terminal.
box = "apple"
print(box) # apple
We can assign any kind of value to a variable. Which supports python. Now while naming a variable we have to follow some rules. let's see an example or valid and invalid variable names.
box = "apple" # Valid
box_capacity = 10 # Valid
boxCapacity = 10 # Valid
1box = "apple" # Invalid
box capacity = 10 # Invalid
box-capacity = 10 # Invalid
if = 10 # Invalid
Here we have declared some variables. The first three variables are valid. And the last four variables are invalid. We can not start a variable name with a number. We can not use space or hyphen in a variable name. And we can not use reserved keywords as a variable name. For example if
is a reserved keyword in python. So we can not use it as a variable name.
And one more thing we have to remember that python is case-sensitive. which means box
and Box
are two different variables. For example
box = "apple"
Box = "orange"
print(box) # apple
print(Box) # orange
Comments
Comments are used to explain the code. It helps other developers to understand the code. When we write a comment it will not be executed by the interpreter. There are two types of comments in python. One is single line comment and another is multi line comment. For single line comment we use #
symbol and for multi line comment we use """
or '''
symbols.
Let's see an example of comments.
# This is a single line comment
"""
This is a multi line comment
"""
'''
This is also a multi line comment
'''
We use comment mostly to explain the code.
# This is a variable named box
box = "apple"
# This is a variable named boxCapacity
boxCapacity = 10
Here we can see an use case of comments. While declaring a variable we can write a comment to explain the variable. Simply we can say that comments are used to explain the code.
Data Types
We have different types of data types in python. Some of them are
- String
- Integer
- Float
- Boolean
- List
- Tuple
- Dictionary
- Sets
String
A string in programming, including Python, is a sequence of characters. Characters can be letters, numbers, symbols, and even spaces. In Python, you create a string by enclosing a sequence of characters in single (' ') or double (" ") quotes.
For example:
myName = "Jon Snow"
Here myName
is a variable and "Jon Snow"
is a string. It's a collection of characters arranged in a specific order. You can manipulate and work with strings in various ways, like finding the length, extracting specific characters, or combining multiple strings.
Strings are indexed, starting from 0. myName[0] gives the first character. myName[1] gives the second character, and so on.
myName = "Jon Snow"
print(myName[0]) # J
print(myName[1]) # o
print(myName[2]) # n
We can also use negative index to access the string. myName[-1] gives the last character. myName[-2] gives the second last character, and so on.
myName = "Jon Snow"
print(myName[-1]) # w
print(myName[-2]) # o
print(myName[-3]) # n
We can also use slicing to access a part of the string. For example if we want to access the first 3 characters of the string we can specify the index from 0 to 3. and it will return the first 3 characters.
myName = "Jon Snow"
print(myName[0:3]) # Jon
and also we can use negative index to access the string.
myName = "Jon Snow"
print(myName[-3:-1]) # Sn
If we want to get the length of a string we can use len
function. it will return the length of the string.
myName = "Jon Snow"
print(len(myName)) # 8
we can also use in
operator to check if a character is in a string or not. it will return a boolean value.
myName = "Jon Snow"
print("J" in myName) # True
print("j" in myName) # False
To merge two strings we can use +
operator. it will concatenate two strings.
firstName = "Jon"
lastName = "Snow"
fullName = firstName + " " + lastName
print(fullName) # Jon Snow
Using +
operator we have concatenated two strings. and it's result is Jon Snow
. we can do the same thing using f
string. which is called formatted string and more readable. it's syntax is we have to put f
before the string and then we can use {}
to put the variable inside the string.
firstName = "Jon"
lastName = "Snow"
fullName = f"{firstName} {lastName}"
print(fullName) # Jon Snow
if we want to search a string in another string we can use find
function.
myName = "Jon Snow"
print(myName.find("Jon")) # 0
print(myName.find("Snow")) # 4
print(myName.find("jon")) # -1
String has many more methods. like :
myName = "Jon Snow"
print(myName.upper()) # JON SNOW
print(myName.lower()) # jon snow
print(myName.replace("Jon", "Arya")) # Arya Snow
print(myName.split(" ")) # ['Jon', 'Snow']
print(myName.strip()) # Jon Snow
print(myName.isalpha()) # False
print(myName.isnumeric()) # False
print(myName.isdigit()) # False
print(myName.islower()) # False
print(myName.isupper()) # False
Here upper
function will convert the string to uppercase. lower
function will convert the string to lowercase. replace
function will replace the first string with the second string. split
function will split the string by the given character. strip
function will remove the extra spaces from the string. isalpha
function will check if the string contains only alphabets or not. isnumeric
function will check if the string contains only numbers or not. isdigit
function will check if the string contains only digits or not. islower
function will check if the string contains only lowercase letters or not. isupper
function will check if the string contains only uppercase letters or not.
Integer
An integer is a whole number (not a fraction) that can be positive, negative, or zero. We can simply say that integer is a number without a decimal point. For example 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 are integers.
coffeePrice = 120
itemQuantity = 10
print(coffeePrice)
print(itemQuantity)
Here we have declared two variables named coffeePrice
and itemQuantity
and assigned integer values to them. Then we have printed the values of the variables. It will print the following output in the terminal.
Integer supports all the arithmetic operators. We can perform addition, subtraction, multiplication, division, modulus, on integers.
print(10 + 5) # 15
print(10 - 5) # 5
print(10 * 5) # 50
print(10 / 5) # 2.0
print(10 % 5) # 0
Float
A float is a floating-point number, which means it is a number that has a decimal place. For example 1.2, 3.4, 5.6, 7.8, 9.0 are floats.
height = 5.5
weight = 60.5
print(height)
print(weight)
Declaring a float is similar to declaring an integer. We just have to put a decimal point in the number. In the above example we have declared two variables named height
and weight
and assigned float values to them. Then we have printed the values of the variables. It will print the for height it will print 5.5
and for weight it will print 60.5
.
Float also supports all the arithmetic operators. We can perform addition, subtraction, multiplication, division, modulus, on floats.
print(10.5 + 5.5) # 16.0
print(10.5 - 5.5) # 5.0
print(10.5 * 5.5) # 57.75
print(10.5 / 5.5) # 1.9090909090909092
print(10.5 % 5.5) # 4.999999999999999
If we run this it will print the appropriate output. which we have expected. But if we want to round the output we can use round
function. It will round the output to the nearest integer.
print(round(10.5 + 5.5)) # 16
Here we have rounded the output of 10.5 + 5.5
to the nearest integer. So it will print 16
in the terminal.
Boolean
A boolean is a data type in programming that can have one of two values: True or False. Booleans are often used to represent the truth or falsity of a condition in logical operations and decision-making within computer programs. Let's see an example.
isCoffeeAvailable = True
isCoffeeSoldOut = False
print(isCoffeeAvailable) # True
print(isCoffeeSoldOut) # False
Here we have declared two variables named isCoffeeAvailable
and isCoffeeSoldOut
and assigned boolean values to them. Then we have printed the values of the variables. It will print the following output in the terminal.
In conditional statements boolean values are used to check the condition. For example
age = 18
isAdult = age > 18
print(isAdult) # False
Here we have declared a variable named age
and assigned a value of 18
. Then we have declared another variable named isAdult
and assigned a boolean value of age > 18
. Here we are checking if the age is greater than 18 or not. If the age is greater than 18 then it will return True
otherwise it will return False
.
List
A list is like a box of items It can hold different types of things. for example a list of fruits. It can hold different types of fruits like apple, orange, banana, etc. We can create a list by putting the items inside a square bracket []
and separate them by a comma ,
.
fruits = ["apple", "orange", "banana"]
print(fruits) # ['apple', 'orange', 'banana']
Indexing
Now if we want to access the items of a list we can use the index. Indexing starts from 0. fruits[0] gives the first item. fruits[1] gives the second item, and so on.
fruits = ["apple", "orange", "banana"]
print(fruits[0]) # apple
print(fruits[1]) # orange
print(fruits[2]) # banana
We can also use negative index to access the items of a list. fruits[-1] gives the last item. fruits[-2] gives the second last item
fruits = ["apple", "orange", "banana"]
print(fruits[-1]) # banana
print(fruits[-2]) # orange
print(fruits[-3]) # apple
Also we have slicing to access a part of the list. For example if we want to access the first 2 items of the list we can specify the index from 0 to 2. and it will return the first 2 items.
fruits = ["apple", "orange", "banana"]
print(fruits[0:2]) # ['apple', 'orange']
And it will also works with negative index.
fruits = ["apple", "orange", "banana"]
print(fruits[-3:-1]) # ['apple', 'orange']
Length
To get the length of a list we can use len
function. it will return the length of the list. How many items are in the list.
fruits = ["apple", "orange", "banana"]
print(len(fruits)) # 3
And also we have few more functions to work with list.
fruits = ["apple", "orange", "banana"]
fruits.append("mango") # Append: add an item to the end of the list
print(fruits)
fruits.insert(1, "mango") # Insert: add an item to a specific position of the list
print(fruits)
fruits.remove("orange") # Remove: remove an item from the list
print(fruits)
fruits.pop(1) # Pop: remove an item from a specific position of the list
print(fruits)
fruits.clear() # Clear: remove all the items from the list
print(fruits)
Tuple
Like a list, a tuple is also like a box of items. It can hold different types of things. for example a tuple of fruits. It can hold different types of fruits like apple, orange, banana, etc. We can create a tuple by putting the items inside a parenthesis ()
and separate them by a comma ,
.
fruits = ("apple", "orange", "banana")
print(fruits) # ('apple', 'orange', 'banana')
The main difference between a list and a tuple is that a list is mutable and a tuple is immutable. Which means we can change the items of a list but we can not change the items of a tuple.
For example if we want to change the first item of the list we can do it like this.
fruits = ["apple", "orange", "banana"]
fruits[0] = "mango"
print(fruits) # ['mango', 'orange', 'banana']
But if we want to change the first item of the tuple we can not do it it will throw an error.
fruits = ("apple", "orange", "banana")
fruits[0] = "mango"
print(fruits) # TypeError: 'tuple' object does not support item assignment
The main purpose of tuple is to store the data which will not be changed. For example if we want to store the days of a week we can use tuple.
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
Just like list we can access the items of a tuple using index.
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print(days[0]) # Sunday
print(days[1]) # Monday
print(days[2]) # Tuesday
We can also use negative index to access the items of a tuple.
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print(days[-1]) # Saturday
print(days[-2]) # Friday
print(days[-3]) # Thursday
And also we have slicing to access a part of the tuple. For example if we want to access the first 2 items of the tuple we can specify the index from 0 to 2. and it will return the first 2 items.
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print(days[0:2]) # ('Sunday', 'Monday')
And it will also works with negative index.
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print(days[-7:-5]) # ('Sunday', 'Monday')
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. For example
person = {
"name": "Jon Snow",
"age": 18,
"height": 5.5,
"weight": 60.5
}
We can have nested dictionary inside a dictionary. For example
person = {
"name": "Jon Snow",
"age": 18,
"height": 5.5,
"weight": 60.5,
"address": {
"city": "Winterfell",
"country": "Westeros"
}
}
Now if we want to access the items of a dictionary we can use the key. For example
person = {
"name": "Jon Snow",
"age": 18,
"height": 5.5,
"weight": 60.5,
"address": {
"city": "Winterfell",
"country": "Westeros"
}
}
print(person["name"]) # Jon Snow
print(person["age"]) # 18
print(person['address']['city']) # Winterfell
One thing we have to remember that key has to be unique. We can not have two keys with the same name. For example
person = {
"name": "Jon Snow",
"age": 18,
"height": 5.5,
"weight": 60.5,
"address": {
"city": "Winterfell",
"country": "Westeros"
},
"name": "Arya Stark"
}
print(person["name"]) # Arya Stark
It will be overwritten by the last value. So we have to be careful about that.
We can add new items to the dictionary using the key. For example
person = {
"name": "Jon Snow",
"age": 18,
"height": 5.5,
"weight": 60.5,
"address": {
"city": "Winterfell",
"country": "Westeros"
}
}
person['phone'] = '1234567890'
print(person)