Variables and Data Types


Variables

Think of variables as labelled containers where you can stash your information. You name these containers, toss stuff in them, and later retrieve or manipulate what’s inside. Here’s a simple example to get the hang of it:

Example: Creating and Using Variables

# Meet 'name', our variable holding the value 'Alice'
name = "Alice"

# Now, let's use the variable to create a friendly message
greeting = "Hello, " + name + "!"

# We print the greeting
print(greeting)  # Output: Hello, Alice!

Data Types

Just like you categorize your belongings, Python categorizes data using different types. Let’s explore some:

1. Numeric Data Types (Integers and Floats)

Numbers are everywhere in programming. Integers are whole numbers, while floats are numbers with decimals. Let’s see them in action:

Example: Using Numeric Variables

# Integer variable 
age = 25 
# Float variable 
temperature = 98.6

3. String Data Type (Storing Text)

Strings hold text and are often used for words, sentences, or any textual information:

Example: Using String Variables

name = "Alice" 
greeting = "Hello, Python!"

4. Boolean Data Type(True or False?)

Booleans handle binary decisions – they can be either True or False, like light switches for your code:

Example: Using Boolean Variables

is_raining = True 
is_sunny = False

5. Type Conversion and Casting: Making Sense of Different Types

Sometimes, you’ll want to transform your data. Say you want to write a number as a word – that’s where type conversion comes in:

Example: Converting Types

number = 42
number_as_string = str(number)   # Converting an integer to a string

Leave a Reply

Your email address will not be published. Required fields are marked *