Hi there,
Do you want to learn the Python programming language? Then this blog might be for you. This blog covers the basics of Python that you need to know to get started coding in Python.
So, let's get started.
What is Python?
Python is an object-oriented, interpreted, and interactive programming language. Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very high-level dynamic data types, and dynamic typing.
How to download Python: Official Website
IDE for Python: You can use PyCharm or any IDE of your choice.
All files written in Python are saved using the ".py" extension.
First program
print("Hello World...")
This will print "Hello World..." in the console.
Variables in Python
name = "Adom" #string
age = 18 #number
isAdult = True #boolean
grade = 89.70 #float
In python we don't need to define the type of variable. Also to convert one type to other we use some methods, example given below.
# Initial variables
string_number = "123"
string_float = "123.45"
int_number = 123
float_number = 123.45
boolean_value = True
# String to Integer
int_from_string = int(string_number) # "123" -> 123
# String to Float
float_from_string = float(string_float) # "123.45" -> 123.45
# Integer to String
string_from_int = str(int_number) # 123 -> "123"
# Float to String
string_from_float = str(float_number) # 123.45 -> "123.45"
# Integer to Float
float_from_int = float(int_number) # 123 -> 123.0
# Float to Integer (Note: this truncates the decimal part)
int_from_float = int(float_number) # 123.45 -> 123
# Boolean to Integer (True -> 1, False -> 0)
int_from_boolean = int(boolean_value) # True -> 1
# Boolean to String
string_from_boolean = str(boolean_value) # True -> "True"
# Integer to Boolean (0 is False, non-zero values are True)
boolean_from_int = bool(int_number) # 123 -> True
# Float to Boolean (0.0 is False, non-zero values are True)
boolean_from_float = bool(float_number) # 123.45 -> True
# Print all conversions
print(f"String to Integer: {int_from_string}")
print(f"String to Float: {float_from_string}")
print(f"Integer to String: {string_from_int}")
print(f"Float to String: {string_from_float}")
print(f"Integer to Float: {float_from_int}")
print(f"Float to Integer: {int_from_float}")
print(f"Boolean to Integer: {int_from_boolean}")
print(f"Boolean to String: {string_from_boolean}")
print(f"Integer to Boolean: {boolean_from_int}")
print(f"Float to Boolean: {boolean_from_float}")
Output :
How to comment in Python
In Python, you can add comments to explain your code. There are two ways to do this:
Single-line comments:
# This is a single-line comment
print("Hello") # This comment is after a line of code
Multi-line comments:
"""
This is a multi-line comment.
You can write as many lines as you want.
"""
Conditions in Python
Python uses if, elif, and else for conditional statements:
age = 18
if age < 13:
print("You're a child")
elif age < 20:
print("You're a teenager")
else:
print("You're an adult")
Operators in Python
Python supports various operators:
- Arithmetic operators: +, -, , /, //, %, *
- Comparison operators: ==, !=, <, >, <=, >=
- Logical operators: and, or, not
Example:
x = 10
y = 3
print(x + y) # Addition: 13
print(x > y) # Comparison: True
print(x > 5 and y < 5) # Logical: True
String methods in Python
Python has many built-in string methods:
text = "Hello, World!"
print(text.upper()) # HELLO, WORLD!
print(text.lower()) # hello, world!
print(text.replace("Hello", "Hi")) # Hi, World!
print(text.split(",")) # ['Hello', ' World!']
Loops in Python
Python has two main types of loops: for and while.
For loop:
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
While loop:
count = 0
while count < 5:
print(count)
count += 1 # Prints 0, 1, 2, 3, 4
Lists in Python
Lists are ordered, mutable collections in Python:
# Initial list
my_list = [10, 20, 30, 40, 50]
# 1. Append an item to the list
my_list.append(60) # Adds 60 to the end of the list
# 2. Insert an item at a specific index
my_list.insert(2, 25) # Inserts 25 at index 2
# 3. Extend the list with another list
my_list.extend([70, 80, 90]) # Adds all elements from another list
# 4. Remove an item from the list
my_list.remove(30) # Removes the first occurrence of 30
# 5. Pop an item from the list (by default, removes the last element)
popped_item = my_list.pop() # Removes and returns the last element (90)
# 6. Access elements by index
first_item = my_list[0] # Access the first element (10)
last_item = my_list[-1] # Access the last element (80)
# 7. Slicing a list (getting a subset of the list)
sub_list = my_list[1:4] # Returns elements from index 1 to 3 ([20, 25, 40])
# 8. Find the index of an item
index_of_40 = my_list.index(40) # Returns the index of the first occurrence of 40
# 9. Count occurrences of an item
count_of_20 = my_list.count(20) # Counts how many times 20 appears in the list
# 10. Reverse the list
my_list.reverse() # Reverses the order of the list
# 11. Sort the list
my_list.sort() # Sorts the list in ascending order
# 12. Length of the list
length_of_list = len(my_list) # Returns the number of elements in the list
# 13. Check if an item exists in the list
is_50_in_list = 50 in my_list # Returns True if 50 is in the list, otherwise False
# 14. Clear the list (removes all elements)
my_list.clear() # Empties the list
# Print all operations
print("Appended and Inserted List: ", [10, 20, 25, 30, 40, 50, 60])
print("Extended List: ", [10, 20, 25, 30, 40, 50, 60, 70, 80, 90])
print("Popped Item: ", popped_item)
print("First Item: ", first_item)
print("Last Item: ", last_item)
print("Sub List: ", sub_list)
print("Index of 40: ", index_of_40)
print("Count of 20: ", count_of_20)
print("Reversed List: ", [80, 70, 60, 50, 40, 25, 20, 10])
print("Sorted List: ", [10, 20, 25, 40, 50, 60, 70, 80])
print("Length of List: ", length_of_list)
print("Is 50 in List: ", is_50_in_list)
print("Cleared List: ", my_list)
Output :
Range in Python
The range() function generates a sequence of numbers:
for num in range(5):
print(num) # Prints 0, 1, 2, 3, 4
# range(start, stop, step)
for num in range(2, 10, 2):
print(num) # Prints 2, 4, 6, 8
And there you have it! These are the basic concepts you need to get started with Python programming. Remember, practice makes perfect, so try out these examples and experiment with your own code. Happy coding!
The One Book That Skyrocketed My Productivity (You Need to Read This)