Basic Python Tutorial for Beginners: Variables, Data Types
Python is an easy-to-learn programming language, making it perfect for beginners. This guide covers foundational topics like variables, data types, input/output, and operators to get you started.
Variables and Data Types
What is a Variable?
A variable is a named container for storing data values. In Python, you don’t need to declare the type of variable; it is dynamically inferred.
Examples of Variables:
# Variable declaration
x = 10 # Integer
name = "Alice" # String
is_active = True # Boolean
Strings can be enclosed in single (') or double (") quotes.
Example:
message = "Python is fun!"
print(message) # Output: Python is fun!
Booleans
Represent truth values (True or False).
Example:
is_sunny = True
print(is_sunny) # Output: True
Type Conversion
Convert between data types using built-in functions:
int(): Converts to integer.
float(): Converts to float.
str(): Converts to string.
Example:
# Implicit type conversion
a = 10
b = 3.5
result = a + b # Automatically converts to float
# Explicit type conversion
age = "25"
age_int = int(age) # Converts string to integer
print(age_int + 5) # Output: 30
Basic Input/Output
Input:
Use input() to get user input as a string.
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
Output:
Use print() to display output.
Example:
print("Welcome to Python!")
Formatted Strings:
Use f-strings for easy string formatting.
Example
age = 25
print(f"I am {age} years old.") # Output: I am 25 years old.
Operators in Python
Arithmetic Operators
Operator
Description
Example
+
Addition
a + b
-
Subtraction
a - b
*
Multiplication
a * b
/
Division
a / b
//
Floor Division
a // b
%
Modulus (remainder)
a % b
**
Exponentiation
a ** b
Example:
python
x = 10
y = 3
print(x + y) # Output: 13
print(x // y) # Output: 3
Comparison Operators
Operator
Description
Example
==
Equal to
a == b
!=
Not equal to
a != b
>
Greater than
a > b
<
Less than
a < b
>=
Greater than or equal to
a >= b
<=
Less than or equal to
a <= b
Example:
a = 5
b = 10
print(a > b) # Output: False
print(a <= b) # Output: True
Logical Operators
Operator
Description
Example
and
Returns True if both are True
a and b
or
Returns True if one is True
a or b
not
Reverses the Boolean value
not a
Example:
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
Assignment Operators
Operator
Description
Example
=
Assign
x = 5
+=
Add and assign
x += 3
-=
Subtract and assign
x -= 3
*=
Multiply and assign
x *= 3
/=
Divide and assign
x /= 3
Example:
x = 10
x += 5 # x = x + 5
print(x) # Output: 15
Best Practices for Beginners
Use Descriptive Variable Names:
Instead of x or y, use names like age or price.
Comment Your Code:
Add comments to explain the purpose of code snippets.
Test Frequently:
Run your code after small changes to catch errors early.
Learn Error Messages:
Understand Python errors like SyntaxError or NameError to debug effectively.