Python is a versatile and powerful language known for its simplicity and readability, making it an excellent choice for beginners. This guide will walk you through the basics, including how to write your first code, work with data types, use variables, create functions, and control the flow of your program with conditionals and loops.
Let’s dive in!
First Line of Code
Every coding journey starts with a simple step. In Python, the first step is usually printing a message to the console.
print('Hello, World!')
The print()
function is used to display text or data on the screen. In this case, it prints the string 'Hello, World!'
.
Data Types
In Python, different types of data can be stored and manipulated. Here are some of the most common data types:
- int: Integer numbers (e.g., 1, 2, 100)
- float: Floating-point numbers or decimals (e.g., 1.5, 3.14)
- str: Strings, which are sequences of characters (e.g., 'Hello', 'Python')
-
bool: Boolean values, representing
True
orFalse
Example:
print(5) # Output: 5 (int)
print(3.14) # Output: 3.14 (float)
print("Python") # Output: Python (str)
print(True) # Output: True (bool)
Variables
Variables allow you to store data in memory that can be used and manipulated throughout your program. They act as labels for values.
a = 10 # a is an integer
b = 5.5 # b is a float
name = "Python" # name is a string
print(a + b) # Output: 15.5
Variable names should be meaningful, and they must follow Python's naming rules (e.g., no spaces, must start with a letter or underscore).
Functions
Functions are blocks of reusable code that perform a specific task. You define a function using the def
keyword, followed by the function name and parentheses.
def greet(name):
return f"Hello, {name}!"
print(greet('Alice')) # Output: Hello, Alice!
In this example, the function greet()
takes a name
as an argument and returns a greeting message.
Control Flow: if
, else
, and elif
To make decisions in your code, you can use conditional statements.
if
Statement:
age = 18
if age >= 18:
print("You are an adult.")
if-else
Statement:
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
if-elif-else
Statement:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Loops
Loops are used to execute a block of code multiple times. There are two main types of loops in Python: for
and while
.
while
Loop
The while
loop continues executing as long as a condition is True
.
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
for
Loop
The for
loop is used to iterate over a sequence (such as a list, tuple, or string).
for i in range(5):
print(i)
Output:
0
1
2
3
4
You can also loop through items in a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Comparison Operators
Comparison operators allow you to compare values and return a Boolean (True
or False
).
| Operator | Description | Example |
| != | Not equal to | x != y
|
| > | Greater than | x > y
|
| >= | Greater than or equal to| x >= y
|
| < | Less than | x < y
|
| <= | Less than or equal to | x <= y
|
Logical Operators
Logical operators are used to combine multiple conditions:
| Operator | Description |
| and | Returns True
if both conditions are True
|
| or | Returns True
if at least one condition is True
|
| not | Returns True
if the condition is False
|
Example:
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
Data Structures
Python provides several built-in data structures to organize and store collections of data.
Lists
Lists are ordered, mutable collections of items.
my_list = [1, 2, 3, 'apple', 'banana']
print(my_list[0]) # Output: 1
Tuples
Tuples are ordered, immutable collections of items.
my_tuple = (1, 2, 3, 'apple', 'banana')
print(my_tuple[1]) # Output: 2
Sets
Sets are unordered collections of unique items.
my_set = {1, 2, 3, 'apple'}
print(my_set) # Output: {1, 2, 3, 'apple'}
Dictionaries
Dictionaries store key-value pairs, where each key maps to a value.
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict['name']) # Output: Alice
Loops with Control Statements
You can control the flow within loops using break
, continue
, and pass
:
-
break
: Exits the loop early. -
continue
: Skips to the next iteration. -
pass
: Does nothing and moves to the next statement.
for i in range(5):
if i == 3:
break
print(i) # Output: 0, 1, 2
Top comments (1)