Python primitives – variables, built-in data types, comments, syntax, and semantics

P

This tutorial is about Python Primitives, we’ll look at the Python primitives such as – variables, built-in data types, comments, syntax, and semantics.

Before start with Python Primitives, if you are not familiar with

  1. What is Python?
  2. How to get and install Python?

I recommend you to first follow the link below

WHAT IS PYTHON? THINGS TO KNOW BEFORE CODE WITH PYTHON

HOW DO I GET AND INSTALL PYTHON?

Python Primitives

Variables

Variables are containers for data. The syntax to declare them is: variable_name = variable_value While you can name variables anything you’d like (except for a few reserved keywords), you should use a naming scheme that makes intuitive sense. The variable name should provide some indication as to what the values assigned to it are.

For example, many new programmers, use simple variable names like x and y. Do (err, try) not to do this. Instead, if you have two numbers – say 1 and 52 – use the variable names num1 and num2 instead of x and y. That way when others read your program, they can make an educated guess that num1 and num2 are probably numbers of some sort. Think of others when writing your programs, as well as your future self.

Built-in Data Types

Python has a number of built-in data types such as numbers (integers, floats, complex numbers), strings, lists, tuples, and dictionaries.

Each of these can be manipulated using:

  1. Operators
  2. Functions
  3. Data-type methods

Be sure to type each example out along with me.

Numbers

Numbers can be integers, floating points, Booleans, or complex numbers. The former three are the most important:

  • Integers are whole numbers – 1, 2, 22, 476, -99999
  • Floats have decimal points – 1.0, 2.22, 22.098, 476.1, -99999.9
  • Booleans represent either True or False (or 1 or 0). They represent data that can only be one thing or another.
Manipulating numbers
Operators

You’ve seen operators before. They’re things like addition (or concatenation) and subtraction, just like you learned in Elementary school.

>>> 2 + 3 # Addition
5
>>> num1 = 10
>>> num2 = 9.99
>>> num3 = num1 + num2
>>> num3
19.990000000000002
>>> 8 - 5 # Subtraction
3
>>> 2 * 6 # Multiplication
12
>>> 12 / 3 # Division
4.0
>>> 7 % 3 # Modulus (returns the remainder from division)
1
>>> 3 ** 2 # Raise to the power
9

Putting your pre-algebra skills to the test, let’s look at comparisons, which evaluate to boolean values – e.g., either True or False (or 1 or 0).

>>> 2 < 5
True
>>> 4 > 10
False
>>> 3 >= 3
True
>>>
>>> 5 == 6
False
>>> 6 != 9
True
>>>

Functions

Python provides you with a number of built-in functions for manipulating integers. These are always available to you. Please note: These functions can be used for any data type. There are a number of modules available in the Python Standard Library as well, such as math. To use the functions associated with these modules, you’ll first have to import the module. More on this later. For now, let’s look at a few examples of built-in functions.

float() – given an integer, this function returns a float.

>>> float(9)
9.0
>>> float(-99999)
-99999.0

int() – given a float, this function returns, and integer. This function does NOT round the input up (ceiling) to the nearest integer – it simply throws out anything after the decimal point (flooring) and returns the number. So the input of 10.6 returns 10, NOT 11. Similarly, 3.25 returns 3.

>>> int(10.6)
10
>>> int(3.25)
3

Data-type methods

Besides functions, there a number of data-type methods associated with each type of number.

float.is_integer() – tests if a float is finite.

>>> (10.0).is_integer()
True
>>> (10.1).is_integer()
False

Strings

Strings are lines of text that are declared with single or double quotes:

>>> simple_string = "hey!"
>>> simple_string
'hey!'
>>> "hello world!"
'hello world!'
>>> escaped = 'can\'t'
>>> escaped
"can't"
>>> not_escaped = "can't"
>>> not_escaped
"can't"

Manipulating strings
Operators

Like numbers, you can concatenate strings (string concatenation):

>>> "happy" + " " + "birthday"
'happy birthday'
>>> "my name is " + "john"
'my name is john'
>>>

Functions

Let’s look at just a few functions that are good to use for string manipulation:

len() – given a string, this function returns the length of it.

>>> len(name_string)
15

slice() – given a start and stop value, you can access a set of, or single, character(s).

>>> print("Hello"[2])
l
>>> print("Hello"[3])
l
>>> print("Hello"[0])
H
>>> print("Hello"[0:2])
He
>>>

Data-type methods

While we’ll only touch on a few data-type methods, be sure to check out the full Python documentation as there are a number of important functions that you should be aware of.

string.capitalize() – returns the string with the first letter capitalized.

>>> lower_case_string = "michael"
>>> lower_case_string.capitalize()
'Michael'
>>> ("empire").capitalize()
'Empire'

string.format() – you can easily format values into strings.

>>> name = "John Doe"
>>> greeting = "My name is {}".format(name)
>>> greeting
'My name is John Doe'
>>>

string.strip() – returns the string with the leading and trailing whitespace removed.

>>> are_you_happy = " Yes "
>>> are_you_happy.strip()
'Yes'

Lists

Lists, which are called Arrays in nearly every other programming language, group various types of data together.

  1. create_a_list = []
  2. numbers_list = [1, 2, 3]
  3. strings_list = [“spam”, “eggs”, “cheese”]
  4. mixed_list = [“Hello”, [1, 2, 3], False]

As you can see above, lists may contain any data type (you can mix and match, too), including other lists or nothing at all. You can access parts of lists just like strings with indexes. The syntax is the same:

>>> create_a_list = [] >>> create_a_list
[] >>> numbers_list = [1, 2, 3, 200] >>> numbers_list
[1, 2, 3, 200] >>> strings_list = ["batman", "superman", "iron man"] >>> strings_list
['batman', 'superman', 'iron man'] >>> mixed_list = ["Hello World", [4, 5, 6], False] >>> mixed_list
['Hello World', [4, 5, 6], False]

You can access elements from the list from either the beginning or end of the list:

>>> numbers_list[0] 1
>>> numbers_list[0:1] [1] >>> numbers_list[0:2] [1, 2]

Watch how you can create a new list just by accessing the elements:

>>> numbers_list = [1, 2, 3, 200] >>> new_list = numbers_list[0:3] >>> new_list
[1, 2, 3]

Negative indexes count from the last item backward:

>>> strings_list = ["batman", "superman", "iron man"] >>> strings_list[-1] 'iron man'

If you nest a list within another list, you can access the inner list using multiple indexes:

>>> mixed_list = ["Hello World", [4, 5, 6], False] >>> mixed_list[1][2] 6

Manipulating lists
Operators

Lists can be concatenated:

>>> fruits = ["apples", "grapes", "oranges"] >>> veggies = ["corn", "kale", "mushrooms"] >>> grocery_list = fruits + veggies
>>> grocery_list
['apples', 'grapes', 'oranges', 'corn', 'kale', 'mushrooms']

Functions

In general, you can think of lists as strings – only each piece of data is an element. What does that mean in practical terms? Well, the same functions you use on strings can be used for lists.

len() – given a list, this function returns the length of it.

>>> numbers_list = [1, 2, 3, 200] >>> len(numbers_list)
4

slice() – given a start and stop value, you can access a set of elements.

>>> hello = ["H", "e", "l", "l", "o"] >>> hello[2] 'l'
>>> hello[3] 'l'
>>> hello[0] 'H'
>>> hello[0:2] ['H', 'e']

Data-type methods

Again, check out the Python documentation to see all available list methods.

list.append() – used to add an item to the end of a list

>>> fruits = ["apples", "grapes", "oranges"] >>> fruits.append("blueberries")
>>> fruits
['apples', 'grapes', 'oranges', 'blueberries']

list.sort() – sort this list

>>> fruits.sort()
>>> fruits
['apples', 'blueberries', 'grapes', 'oranges']

list.pop() – given an index value, remove an element from the list

>>> numbers_list = [1, 2, 3, 200] >>> numbers_list.pop(2)
3
>>> numbers_list
[1, 2, 200]

Tuples

Tuples are similar to lists, but they are immutable – which means they cannot be changed after creation.

my_tuple = (“Michael”, “Herman”, 31, “Software Developer”)

Just like a list, you can also use indexes to access different elements:

>>> my_tuple = ("Michael", "Herman", 31, "Software Developer")
>>> my_tuple[1] 'Herman'
>>>

Often tuples are used for dictionary keys since they should (err, must) be immutable.

Manipulating tuples
Operators

Yes, you can add two tuples:

>>> first_tuple = (1, 2)
>>> second_tuple = (3, 4)
>>> third_tuple = first_tuple + second_tuple
>>> third_tuple
(1, 2, 3, 4)

Functions

list() – used to convert a tuple to a list

>>> first_tuple = (1, 2)
>>> list(first_tuple)
[1, 2]

What about converting a list to a tuple? Is there a function for that? Where would you go to find out?

Data-type methods

Because tuples are immutable, many of the list methods don’t work on tuples.

>>> first_tuple = (1, 2)
>>> first_tuple.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
>>> first_tuple.pop(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'pop'
>>> first_tuple.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'
>>> first_tuple.reverse()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'reverse'

Dictionaries

Dictionaries are a type of associative array (an object) implemented using hash tables containing key/value pairs. They are unordered.

my_dict = {“Key 1”: “Value 1”, “name”: “michael herman”, “pi”: 3.14}

You can return a key’s value using the following syntax:

>>> my_dict = {"Key 1": "Value 1", "name": "michael herman", "pi": 3.14}
>>> my_dict["name"] 'michael herman'
>>> my_dict["Key 1"] 'Value 1'

Manipulating dictionaries

Research this on your own, using the Python documentation. Need help? Comment below.

Speaking of comments…

Comments

Comments are used to describe your code so other developers can quickly understand what’s happening (as well as your future self).

# This a comment on it's own line
# You create them with the hash symbol
var = "Hello" # They can also be on the same line as code

This is all about Python Primitives. If you have any doubt or have any difficulty to understand Python Primitives. Feel free to write in a comment box about your difficulty in python primitives. You can also suggest for anything.

Thanks for reading about Python Primitives

Need Help?

Like a good friend, Python is always available if you get stuck. Perhaps you want to know how a specific object works, simply open the Python shell and then call help() to get help or dir() to see which methods are available for that particular object.

About the author

Pardeep Patel
Pardeep Patel

2 comments

  • An impressivе share! I have just forwarded this onto a coworкer who was conduϲting a little homework on this.

    And he aсtᥙally oгdered me lunch simply because I found
    it for him… lol. So let me reword this….
    Thanks for the meal!! But yeah, thanks for spending time to talk about this matter here on your
    blog.

Basics of Python