Python is a powerful and versatile programming language that is perfect for beginners. Its simple and readable syntax all keywords in python are in makes it an excellent choice for those new to coding. In this guide, we’ll walk you through the basics of Python programming and help you get started on your coding journey.
Running Python Code
Python provides two main ways to run code:
Interactive Mode (Python Shell): You can open a command prompt or terminal and type python. This will bring up an interactive shell where you can type and execute Python code line by line.
Script Mode: You can write Python code in a file with a .py extension (e.g., my_script.py) and then run it using the command python my_script.py in the command prompt or terminal.
Your First Python Program
Let’s write a simple “Hello, World!” program to get started:
pythonCopy codeprint(“Hello, World!”)
Open a text editor (like Notepad, Visual Studio Code, or any other text editor of your choice) and type the above code.
Save the file with a .py extension, for example, hello.py.
Open a command prompt or terminal, navigate to the directory where you saved the file, and type python hello.py to run the program.
You should see Hello, World! printed to the console.
Variables and Data Types
Variables are used to store data in Python. Here are some common data types:
Integer (int): Whole numbers without a decimal point (e.g., 5, -10, 1000).
Float (float): Numbers with a decimal point or numbers written in scientific notation (e.g., 3.14, 2.5e3).
String (str): Sequence of characters, enclosed in either single (‘) or double (“) quotes (e.g., ‘hello’, “Python”).
pythonCopy code# Example of variable assignment
name = “Alice”
age = 30
height = 5.8
Python supports common mathematical operations:
pythonCopy code# Addition
result = 5 + 3
result = 10 – 7
result = 4 * 6
result = 20 / 5
result = 2 ** 3
Python uses indentation to define blocks of code. Here’s an example of an if statement:
pythonCopy codeif age >= 18:
print(“You are an adult”)
print(“You are a minor”)
There are two main types of loops in Python: for loops and while loops. Here’s an example of a for loop:
pythonCopy codefor i in range(5):
Functions allow you to group code into reusable blocks:
pythonCopy codedef greet(name):
# Call the function
This is just the tip of the iceberg when it comes to Python programming. As you progress, you’ll learn about more advanced topics like lists, dictionaries, classes, and modules.