Python : Basics

Here are some basic Python examples to get you started with coding:

Hello, World!

This is the traditional first program that you write when learning a new programming language. To print "Hello, World!" in Python, you can use the `print()` function:

print("Hello, World!")
 

Variables

In Python, you can use variables to store values. To create a variable, you just need to give it a name and assign a value to it using the assignment operator (`=`). For example:


message = "Hello, World!"
print(message)

 

You can also assign a value to a variable and then change its value later:

message = "Hello, World!"
print(message)

message = "Goodbye, World!"
print(message)

 

Data Types

Python has several built-in data types, including integers, floating point numbers, strings, and boolean values.

# integers
x = 10
y = -5

# floating point numbers
a = 3.14
b = -2.718

# strings
name = "Alice"
greeting = "Hello, " + name

# boolean values
is_cool = True
is_warm = False

 

Operators

Python supports various operators, such as arithmetic operators (e.g., +, -, *, /), comparison operators (e.g., ==, !=, >, <), and logical operators (e.g., and, or, not).


# arithmetic operators
x = 3 + 4
y = 5 - 2
z = 4 * 3
w = 6 / 2

# comparison operators
a = 3 > 4
b = 5 == 5
c = 6 != 10

# logical operators
is_cold = True
is_sunny = False
is_nice = is_cold and is_sunny

 

Control Structures

Python has several control structures that allow you to control the flow of your program, such as `if` statements, `for` loops, and `while` loops.


# if statement
temperature = 30
if temperature > 25:
    print("It's hot outside.")

# for loop
for i in range(5):
    print(i)

# while loop
count = 0
while count < 5:
    print(count)
    count += 1

 

Functions

Python allows you to define your own functions, which can be used to perform specific tasks.

def greet(name):
    print("Hello, " + name + "!")

greet("Alice")
greet("Bob")