Python programming tutorial for beginners with examples
This post was created to help you learn Python programming quickly. It covers famous Python topics with brief explanations, example code, and their outputs. Let's start with comments in Python.
Comments in Python
Comments are used to describe a specific piece of code's intent. Comments make the code more readable and provide context for upcoming programmers.
Types of comments in Python
Single-line comments and multi-line comments are the two different types of comments in Python.
Single-line comments in Python
Python starts single-line comments with the "#" symbol. For instance:
# A single-line comment in Python
print("Hello there.") # Another single-line comment in Python
Hello there.
Multi-line comments in Python
Python encloses multi-line comments with three double quotes ("""). For instance:
""" A multi-line comment in Python """
print("Hello there.")
"""
Another
multi-line
comment
in Python
"""
Hello there.
Variables in Python
Variables are used to store values in Python or any other programming language. A variable is essentially a named memory location where values can be stored.
One of the most appealing aspects of Python programming is the lack of a command to declare variables before using them. When we assign a value to a variable in Python, the variable is created. As an example:
x = 10
print(x)
10
Furthermore, whatever value we assign to a variable, the variable adjusts and changes type. As an example:
x = 10
print(type(x))
x = "GoshLike.com"
print(type(x))
x = 12.43
print(type(x))
x = True
print(type(x))
<class 'int'>
<class 'str'>
<class 'float'>
<class 'bool'>
The type() function in Python is used to determine the data type of a value or variable. It returns the type of the object passed in as an argument.
Another advantage of using the casting feature is that we can change the type of a value. As an example:
x = "10"
print(type(x))
y = int(x)
print(type(y))
<class 'str'>
<class 'int'>
Variable naming guidelines in Python
- A variable name can begin with a letter or an underscore.
- A variable name can only contain alphanumeric and underscore characters.
Python permits the assignment of multiple values to multiple variables on the same line. For instance:
x, y, z = 10, 20, "Hello there."
print(x)
print(y)
print(z)
10
20
Hello there.
In Python, multiple variables can be assigned the same value on the same line. For instance:
x = y = z = 453.55
print(x)
print(y)
print(z)
453.55
453.55
453.55
Data types in Python
The Python programming language offers seven categories or types of data to deal with various types of values in the program. We have the "str" type to handle textual data. We have "int", "float", and "complex" types to deal with "numerical data." We have "list," "tuple," and "range" to deal with sequential data. We have "dict" to handle mapping. There are two set types available: "set" and "frozenset." For boolean types, we have "bool". Binary types come in "bytes," "bytearray," and "memoryview" varieties. The "NoneType" value for no type is the last option. As an example:
x = "GoshLike.com"
print(type(x))
x = 10
print(type(x))
x = 23.43
print(type(x))
x = 23j
print(type(x))
x = [12, 4, 5]
print(type(x))
x = (43, 5, 6)
print(type(x))
x = range(4)
print(type(x))
x = {"Language": "Python", "Marks": 94.32}
print(type(x))
x = {"Django", "Flask"}
print(type(x))
x = frozenset(x)
print(type(x))
x = True
print(type(x))
x = b"Houston"
print(type(x))
x = bytearray(34)
print(type(x))
x = memoryview(bytes(23))
print(type(x))
x = None
print(type(x))
<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>
<class 'NoneType'>
Strings in Python
Python utilizes strings to represent textual data. A string is anything that is enclosed in single or double quotation marks. For instance:
x = "Hello there."
print(type(x))
x = 'Hello there.'
print(type(x))
<class 'str'>
<class 'str'>
To assign a string that spans multiple lines to a variable in Python, you need to enclose the string within the three quotes. For example:
x = """This is a
multiline string.
A string that spans multiple lines"""
print(type(x))
<class 'str'>
White spaces are also considered part of the multiline string. As an example:
x = """Hello there,
I'm Rio.
Do
- like Python?"""
print(x)
Hello there,
I'm Rio.
Do
- like Python?
Strings can also be considered an array of characters in Python. Indexing in arrays starts with 0. Therefore "x[0]" refers to the very first character of the string value that is stored in the variable "x". For example:
x = "Houston is a beautiful city of Texas"
print(x[0]) # x[0] refers to 'H', the first character
print(x[1]) # x[1] refers to 'o'
print(x[2]) # x[2] refers to 'u'
print(x[3]) # x[3] refers to 's'
print(x[4]) # x[4] refers to 't'
print(x[-1]) # x[-1] refers to 's', the last character
H
o
u
s
t
s
Find the length of a string in Python
Use the "len()" function to find the length of a string in Python. As an example:
x = "Hello world"
print(len(x))
11
We can also access the string in character-by-character mode using the "for" loop. As an example:
x = "Hello world"
for c in x:
print(c, end="")
Hello world
This Python code defines a variable x with a string value "Hello world", and then loops through each character of the string using a for loop. Inside the loop, the print() function is called with the end parameter set to an empty string "", which means that the output will not include a newline character at the end.
The output of this code will be the string "Hello world" printed one character at a time, without any newline characters between them. The end="" parameter passed to print() ensures that each character is printed on the same line, rather than on separate lines.
The following program also does the same job as the previous one.
x = "Hello world" for i in range(len(x)): print(x[i], end="")
The range(len(x)) function generates a sequence of numbers from 0 up to but not including the length of the string x. This creates a loop that iterates through each character in the string by using the current index to access the character at that position.
Check if a specified sub-string is available in a string in Python
Use the "in" keyword to check if the specified sub-string is available in the given string. As an example:
x = "Houston is a beautiful city of Texas"
print("beautiful" in x)
print("amazing" in x)
True
False
String slicing in Python
We can slice some parts of the string using index numbers. For example, if you need to slice a part of a string from index number 2 to index number 5 (including characters at both the index numbers), Therefore, you need to write:
x[2:6]
The index number before the colon is included, whereas the index number after the colon is excluded. As an example:
x = "123456789"
print(x[0:])
print(x[2:])
print(x[0:5])
print(x[2:6])
print(x[0:len(x)])
print(x[:4])
print(x[-6:-3])
123456789
3456789
12345
3456
123456789
1234
456
String concatenation in Python
Use the "+" operator to concatenate two strings in Python. As an example:
x = "What is"
y = "up?"
z = x + " " + y
print(z)
What is up?
I used a space to maintain the space between the last word of the first string and the first word of the second string.
String formatting in Python
Use "format()", a pre-defined Python built-in function, to format a string. For example:
name = "GoshLike"
age = 1
message = "My name is {}, and I am {}."
print(message.format(name, age))
My name is GoshLike, and I am 1.
Lists in Python
Lists in Python are like arrays in other programming languages such as Java, C, and C++. Therefore, we can refer to lists as a data type in Python that can be used to store multiple values in a single variable. As an example:
myList = ["Gosh", "Like"]
print(myList)
['Gosh', 'Like']
I got the original list on the output console because I just used the list as it is to print it. We can, however, print the list item by item as follows:
myList = ["Gosh", "Like", ".", "com"]
for item in myList:
print(x)
Gosh
Like
.
com
Another thing to note is that, because the "print()" method automatically inserts a new line at the end, we can use the "end" parameter to manually define the end of the print() method as follows:
myList = ["Gosh", "Like", ".", "com"]
for x in myList:
print(x, end="")
GoshLike.com
We can have any type of element in the same list. As an example:
x = ["GoshLike", 10, True, 43.9, '0', False, "Susan"]
print("List items are:")
for item in x:
print("\t", item)
List items are:
GoshLike
10
True
43.9
0
False
Susan
I used "\t" to create a horizontal tab before each item of the list.
Find the length of a list in Python
To find the length of a list in Python, use the len() method. The len() method returns the number of items or elements available in a list in Python. For example:
x = ["Gosh", "Like", ".", "com"]
xSize = len(x)
print("Length of the list \"x\" =", xSize)
Length of the list "x" = 4
Access a specific item from a list in Python
We can also select a specific item from a list. Because indexing begins with 0, we can use "x[0]" to access the very first item of a list, say "x," "x[1]" to access the second item, and x[len(x)-1] or x[-1] (through negative indexing) to access the last item of a list. As an illustration:
x = ["GoshLike", 10, True, 43.9, '0', False, "Susan"]
print("First item =", x[0])
print("Second item =", x[1])
print("Last item =", x[len(x)-1])
print("Last item =", x[-1])
print("Second last item =", x[-2])
First item = GoshLike
Second item = 10
Last item = Susan
Last item = Susan
Second last item = False
We can also use the index range to slice a few items from a list. As an example:
x = ["GoshLike", 10, True, 43.9, '0', False, "Susan"]
y = x[2:5]
for item in y:
print(item)
True
43.9
0
The first index number, a, is included in the form myList[a:b], whereas the second index number, b, is excluded. As a result, in the preceding example, we will get items at index numbers 2, 3, and 4, which are "True," "43.9," and "0."
To get all items from start to a particular index number, let's say 6, then use myList[:7]. Because the second index number, 7, is excluded, we will get all items of the "myList" list from index numbers 0 to 6.
Similarly, to get all items starting with a particular index number, let's say 3 to the last items of a list, use myList[3:], which will return all items of a list except the items at index numbers 0, 1, and 2.
Check if a specific item is in the list in Python
To check if a specific item is in the list or not in Python, use the "if...in" clause. As an example:
x = ["GoshLike", 10, True, 43.9, '0', False, "Susan"]
if "GoshLike" in x:
print("Yes, \"GoshLike\" is in the list \"x.\"")
Yes, "GoshLike" is in the list "x."
Change the value of a specific item in a list in Python
In Python, we can change the item in a list by using the index number. To change the item available at index number 2 (the third item) from a list named "myList," for example, use the following code:
myList[2] = new_item_value
As an example:
x = ["GoshLike", 10, True, 43.9, '0', False, "Susan"]
print("Before change, the list is:")
print(x)
x[2] = "USA"
print("\nAfter change, the list is:")
print(x)
Before change, the list is:
['GoshLike', 10, True, 43.9, '0', False, 'Susan']
After change, the list is:
['GoshLike', 10, 'USA', 43.9, '0', False, 'Susan']
You can see that the third item, or the item at index number 2, is changed from "true" to "USA."
Insert items into a list in Python
To insert or add an item to a list in Python, we can use the "insert()" method. As an example:
x = ["GoshLike", 10, True, "Susan"]
print("Before insertion, the list is:")
print(x)
x.insert(2, "USA")
print("\nAfter insertion, the list is:")
print(x)
Before insertion, the list is:
['GoshLike', 10, True, 'Susan']
After insertion, the list is:
['GoshLike', 10, 'USA', True, 'Susan']
You can see that the new item "USA" is inserted into a list "x" at index number 2.
Append items to a list in Python
We can, however, use the "append()" method to append an item to a list in Python. That is, when we need to add or insert an item at the end of a list, we simply use the append() method. As an example:
x = ["GoshLike", 10, True, "Susan"]
print("Before append, the list is:")
print(x)
x.append("USA")
print("\nAfter append, the list is:")
print(x)
Before append, the list is:
['GoshLike', 10, True, 'Susan']
After append, the list is:
['GoshLike', 10, True, 'Susan', 'USA']
Remove a specific item from a list in Python
We can use the "remove()" method to remove an item from a list in Python. As an example:
x = ["GoshLike", 10, True, "Susan"]
print("Before remove, the list is:")
print(x)
x.remove("Susan")
print("\nAfter remove, the list is:")
print(x)
Before remove, the list is:
['GoshLike', 10, True, 'Susan']
After remove, the list is:
['GoshLike', 10, True]
However, there are times when we do not know the exact value of the item to be removed from a list; instead, we know the index number. As a result, we can use the pop() method to remove an item from a list at a specific index number. As an illustration:
x = ["GoshLike", 10, True, "Susan"]
print("Before pop, the list is:")
print(x)
x.pop(2)
print("\nAfter pop, the list is:")
print(x)
Before pop, the list is:
['GoshLike', 10, True, 'Susan']
After pop, the list is:
['GoshLike', 10, 'Susan']
You can see that the item that was available at index number 2 has been removed from the list "x."
However, you can remove the last item from a list using the pop() method if you do not specify the index number as its parameter. As an example:
x = ["GoshLike", 10, True, "Susan"]
print("Before pop, the list is:")
print(x)
x.pop()
print("\nAfter pop, the list is:")
print(x)
Before pop, the list is:
['GoshLike', 10, True, 'Susan']
After pop, the list is:
['GoshLike', 10, True]
Sort lists in Python
Use the "sort()" method to sort a list alphabetically if the list items are strings, or numerically if the list items are numbers. For example:
x = ["like", "gosh", "python", "code"]
x.sort()
print(x)
x = [10, 20, 5, 30, 15]
x.sort()
print(x)
['code', 'gosh', 'like', 'python']
[5, 10, 15, 20, 30]
You can also use "reverse = True" as "sort()"'s parameter to sort a list in descending order in this way:
x = [10, 20, 5, 30, 15]
x.sort(reverse = True)
print(x)
[30, 20, 15, 10, 5]
Copy a List in Python
Use the "copy()" method to copy a list in Python. As an example:
x = [10, 20, 5, 30, 15]
y = x.copy()
print(y)
[10, 20, 5, 30, 15]
Join two lists in Python
Just use the "+" operator to join two lists. As an example:
x = [10, 20, 5, 15]
y = [34, 54]
z = x + y
print(z)
[10, 20, 5, 15, 34, 54]
Sharing is stylish! Gift your friends this awesome read!