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
Basic Operations
Python supports common mathematical operations:
pythonCopy code# Addition
result = 5 + 3
# Subtraction
result = 10 – 7
# Multiplication
result = 4 * 6
# Division
result = 20 / 5
# Exponentiation
result = 2 ** 3
Control Flow
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”)
else:
print(“You are a minor”)
Loops
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):
print(i)
Functions
Functions allow you to group code into reusable blocks:
pythonCopy codedef greet(name):
print(f”Hello, {name}!”)
# Call the function
greet(“Bob”)
Conclusion
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.
GIPHY App Key not set. Please check settings