Python Basics Notes
1. Variables and Data Types
Variables are used to store data.
Examples:
name = 'Alice' # String
age = 30 # Integer
height = 5.7 # Float
is_student = True # Boolean
Data Types:
- String: A sequence of characters (e.g., 'Hello, World!')
- Integer: Whole numbers (e.g., 42)
- Float: Decimal numbers (e.g., 3.14)
- Boolean: True or False
2. Basic Operations
Arithmetic Operators: Used to perform mathematical calculations.
Examples:
a = 10
b=5
sum = a + b # Addition
difference = a - b # Subtraction
product = a * b # Multiplication
quotient = a / b # Division
remainder = a % b # Modulus
power = a ** b # Exponentiation
3. Control Structures
If Statement: Executes a block of code if the condition is true.
Example:
if age > 18:
print('You are an adult.')
else:
print('You are a minor.')
For Loop: Iterates over a sequence (like a list or string).
Example:
for i in range(5):
print(i)
While Loop: Continues to execute as long as the condition is true.
Example:
count = 0
while count < 5:
print(count)
count += 1 # Increments count by 1
4. Functions
Defining Functions: Use def to define a function.
Example:
def greet(name):
return f'Hello, {name}!
print(greet('Alice')) # Output: Hello, Alice!
5. Data Structures
Lists: Ordered, mutable collections of items.
Example:
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange') # Adds 'orange' to the list
Tuples: Ordered, immutable collections of items.
Example:
dimensions = (1920, 1080) # Cannot be modified
Dictionaries: Unordered collections of key-value pairs.
Example:
student = {
'name': 'Alice',
'age': 30,
'is_student': True
print(student['name']) # Output: Alice
6. Input and Output
Input: Get user input.
Example:
user_name = input('Enter your name: ')
print(f'Hello, {user_name}!')
Output: Print to the console.
Example:
print('This is a message.')
7. Comments
Single-Line Comment: Starts with #.
Example:
# This is a comment
print('Hello!') # This prints 'Hello!'
Multi-Line Comment: Use triple quotes (''' or ''').
Example:
"""
This is a
multi-line comment.
"""
Basic Command Words
1. def: Define a function.
2. if: Start a conditional statement.
3. else: Execute code if the if condition is false.
4. elif: Check multiple conditions.
5. for: Create a loop to iterate over a sequence.
6. while: Create a loop that continues while a condition is true.
7. return: Send a value back from a function.
8. import: Bring in modules or libraries.
9. print: Output text to the console.
10. input: Get input from the user.
Example Program
Here's a simple example that combines several of these concepts:
def check_even_odd(number):
if number % 2 == 0:
return 'Even'
else:
return 'Odd'
user_input = int(input('Enter a number: '))
result = check_even_odd(user_input)
print(f'The number {user_input} is {result}.')