UncategorizedHow to use Scalar Types, Operators, and Control Flow

How to use Scalar Types, Operators, and Control Flow

Now that you’ve got a functional Python REPL on your system, we can start to work with the fundamentals of the language. In this module of Core Python: Getting Started, you’ll start to learn about Python’s fundamental scalar types. We’ll look at basic use of relational operators, and we’ll introduce basic flow‑control mechanisms. Python comes with a number of built‑in data types. These include primitive scalar types like integers, as well as collection types like dictionaries.

Scalar Types

These built‑in types are powerful enough to be used alone for many programming needs, and they can be used as building blocks for creating more complex data types. In this section, we cover the basic scalars, int for whole numbers; float for numbers with fractional parts; None, an important placeholder value; and bool, used for True and False values. We’ll provide basic information about these now, showing their literal forms and how to create them. We’ve already seen quite a lot of Python integers in action.

int

Python integers are signed, and have, for all practical purposes, unlimited precision, meaning they can contain as many digits as you need. Integer literals in Python are specified in decimal, and may also be specified in binary with the 0b prefix, in octal with the 0o prefix, or in hexadecimal with the 0x prefix. We can also construct integers by a call to the int constructor. This can convert from other numeric types, such as floats, to integers. Note that the rounding of integers is always towards zero. The int constructor can also convert strings to integers.

>>10
>> 0b10
2
>>0o10
8
>>0x10
16
>>int(3.5)
3
>>int(-3.5)
-3
>>int("496")
496
>>int("10000",3)
81

Float

You can even supply an optional number base when converting from a string. For example, to convert from base 3, provide the value 3 as the second argument to the int constructor. Floating point numbers are supported in Python by the float type. Python floats are implemented as IEEE‑754 double‑precision floating point numbers with 53 bits of binary precision. This is equivalent to between 15 and 16 significant digits in decimal. Any literal number containing a decimal point is interpreted by Python as a float.

>>> 3.125
3.125 >>> 3e8 300000000.0
>>> 1.616e-35
1.616e-35
>>> float(7)
7.0
>>> float("1.618") 1.618
>>> float("nan")
nan
>>> float("inf")
inf
>>> float("-inf")
-inf
>>> 3.0 + 1
4.0
>>>

Scientific notation can be used, so for large numbers, such as the approximate speed of light in meters per second, 3 times 10 to the eighth, we can write 3e8, and for small numbers like Planck’s constant, 1.616 times 10 to the negative thirty‑fifth, we can enter 1.616e‑35. Notice how Python automatically switches the display representation, that is, the format it prints to the REPL, to the most readable form. As with integers, we can convert to floats from other numeric or string types using the float constructor. We can pass int values to the float constructor, and we can pass strings.

None

This is also how we create the special floating point values non, or not a number, as well as positive infinity and negative infinity. One important rule to remember is that the result of any calculation involving int and float is promoted to a float. You can read more about Python’s number types in Python’s documentation. Python has a special null value called None, spelled with a capital N. None is frequently used to represent the absence of a value. The Python REPL never prints None results, so typing None into the REPL has no effect. None could be bounded to variable names just like any other object, and we can test whether an object is None by using Python’s is operator.

>>> None
    >>> a = None >>> a is None
True
    >>>

We can see here that the result of the is operator in this case is True, which brings us conveniently onto the bool type.

bool

The bool type represents logical states, and plays an important role in several of Python’s control flow structures, as we’ll see shortly. As you probably expect, there are two bool values, True and False, both spelled with initial capitals. There is also a bool constructor which can be used to convert from other types to bool. Let’s look at how it works. For integers, zero is considered False and all other values True. We see the same behavior with floats, where only zero is considered False . When converting from collections, such as strings or lists, only empty collections are treated as False .

False
>>> bool(42)
True
>>> bool(-1)
True
>>> bool(0.0)
False
>>> bool(0.207) True
True
>>> bool("") 
False
>>> bool("Spam") 
True
>>> bool("False") 
True
>>> bool("True")
True
>>>

For lists, which we’ll look at shortly, the empty list is False, while any non‑empty list is True. Similarly, empty strings are False, while any other strings are True. It’s worth noting that the bool constructor may not behave as you expect when passing in the strings True and False. Since both are non‑empty strings, both result in True. These conversions to bool are important, because they are widely used in Python if statements and while loops, which accept bool values into the condition. We’ll look at these constructs soon.

Relational Operators:

Bool values are commonly produced by Python’s relational operators, which can be used for comparing objects. These include value equality or equivalents, value inequality or inequivalence, less than, greater than, less than or equal to, and greater than or equal to. Two of the most widely used relational operators are Python’s equality and inequality tests. These test whether two objects are equivalent or inequivalent, that is, whether one can be used in place of the other or not. We’ll learn more about the notion of object equivalents later , but for now, we’ll just compare simple integers.

Let’s start by assigning or binding a value to the variable g. We test for equality with the == operator, and we test for inequality using the not equals operator, an exclamation point followed by an equal sign. We can also compared the order of quantities using the rich comparison operators. We check if one object is less than another with the less than operator. We can append an equal sign to this operator to test for less than or equal. Likewise, we check if an object is greater than another with the greater than operator, and as with less than, there is the related greater than or equal operator.

Control Flow:

Now that we’ve examined some basic built‑in types, we’ll look at two important control flow structures, which depend on the conversions to the bool type, if statements and while loops. We’ll start with if statements, also known as conditional statements. Conditional statements allow us to branch execution based on the value of an expression. The form of the statement is the if keyword, followed by an expression, terminated by a colon to introduce a new block. Let’s try this at the REPL. Remembering to indent four spaces within the block, we add some code to be executed if the condition is true.

if

We terminate the blocked by entering a blank line. Because the condition is self‑evidently true, the block executes, and we see the string, It’s true!, printed to the REPL. Conversely, if the condition is false, the code in the block does not execute. The expression used with the if statement will be converted to a bool, just as if the bool constructor had been used, so explicitly constructing a bool in the if statement is exactly equivalent to using a bare string. Thanks to this useful shorthand, explicit conversion to bool using the bool constructor is rarely used in Python.

If-statement
>>> if True:
            print("It's true!")

It's true!
>>> if False:
            print("It's true!")

>>> if bool("eggs"):
            print("Yes please!")

Yes please!
>>> if "eggs":
            print("Yes please!")

Yes please!
>>>

if-else

The if statement supports the optional else‑Claus that goes in a block introduced by the else keyword followed by colon, which is indented to the same level as the if keyword. To start the else block, in this case, we just omit the indentation after the three dots. For multiple conditions, you might be tempted to nest if statements inside else blocks like this. Whenever you find yourself doing this though, you should consider using Python’s lf keyword, which is a combined else‑if. As the Zen of Python reminds us, flat is better than nested. This version is altogether easier to read.

if h > 50:
    print("Greater than 50")
    
    else:
    print("50 or smaller")
50 or smaller

if h > 50:
    else :
        print("Greater than 50")
        
if h < 20:
    print("Less than 20")
else :
    print("Between 20 and 50")
    
Between 20 and 50
if h > 50:
    print("Greater than 50")
elif h < 20:
    print("Less than 20")
    ...
else:
    print("Between 20 and 50")
Between 20 and 50

While-loops:

Python has two types of loop, for loops and while loops. We’ve already briefly introduced for loops back when we introduced significant white space, and we’ll return to them soon, but right now we’ll cover for loops. While loops in Python are introduced by the while keyword, which is followed by a Boolean expression. As with the condition for if statements, the expression is implicitly converted to a Boolean value, as if it had been passed to the bool constructor. The while statement is terminated by a colon because it introduces a new block.

Let’s write a loop at the REPL, which counts down from 5 to 1. We’ll initialize a counter variable called C to 5, and keep looping until we reach zero. Another new language feature here is the use of the augmented assignment operator, a minus sign followed by an equal sign to subtract one from the value of C on each iteration. Similar augmented assignment operators exist for other basic math operators, such as plus and multiply. Because the condition, also called the predicate, will be implicitly converted to bool, just as if a call to the bool constructor present, we could replace the above code with the following version.

While - loops 
>>> c = 5 >>>
    while c != 0:
    5
4
3
print(c)
c = 1
27
1
    >>> c = 5 >>>
    while c:
    print(c) c = 1
5
4
3
21
    >>>

This works because the conversion of the integer value of C to bool results in true until we get to zero, which converts to false. That said, to use this short form in this case might be described as unPythonic because, referring back to the Zen of Python, explicit is better than implicit, and we place a higher value on the readability of the first form over the concision of the second form. While loops are often used in Python, where an infinite loop is required. We achieve this by simply passing true as the predicate expression to the while construct.

Now you’re probably wondering how to get out of this loop and regain control of your REPL. To do this, we press Ctrl+C. Python intercepts this to raise a special exception which terminates the loop. We’ll be talking much more about what exceptions are and how to use them later.Many programming languages support a loop construct which places the predicate test at the end of the loop rather than at the beginning. For example, C, C++, C #, and Java support the do while construct. Other languages have repeat until loops instead or as well.

Break

This is not the case in Python, where the idiom is to use, while true, together with an early exit facilitated by the break statement, the break statement jumps out of the loop and only the innermost loop, if several loops have nested, and then continues execution immediately after the loop body. Let’s look at an example of break, introducing a few other Python features along the way. We start with a while true for an infinite loop. On the first statement of the while block, we used the built in input function to request a string from the user. We assigned that string to a variable called response.

We now use an if statement to test whether the value provided is divisible by seven. We convert response to an integer, using the int constructor and then use the modulus operator, the percent symbol to divide by 7 and give the remainder. If the remainder is equal to 0, the response was divisible by 7, and we enter the body of the if block. Within the if block, now two levels of indentation deep, we start with eight spaces and use the break keyword. Break terminates the innermost loop, in this case the while loop, and causes execution to jump to the first statement after the loops.

>>>
while True:
    response = input()
if int(response) % 7 == 0:
    break


12
67
34
28
    >>>

In our case, this is the end of the program. Enter a blank line that the three dots prompt to close both the if block and the while block. Our loop will start executing and will pause at the call to the input function waiting for us to enter a number. Let’s try a few. As soon as we enter a number divisible by seven, the predicate becomes true. We enter the if block and then literally break out of the loop, ending the program and returning us to the REPL prompt.

Summary:

We’ve covered quite a bit of ground in this module, so let’s summaries what we’ve seen. We looked at the four built‑in scalar types, int, float, none, and bool, and conversions between these types, and use of their literal forms. We looked at six relational operators used for equivalents and ordering. We demonstrated, structuring conditional code with the if‑else structures. We showed iterating with while loops, and we saw how the condition expression of the while loop is implicitly converted to a bool. We looked at how to intercept infinite loops with Ctrl+C, and we learned that doing this generates a keyboard interrupt exception.

We gave an example of how to break out of loops using the break statement. We observed that break only breaks us out of the innermost nested loop and that it takes us to the first statement immediately following the loop. Along the way, we looked at the augmented assignment operators for modifying objects, such as counter variables in place. We also looked at requesting text from the user with the built‑in input function. In the next module of Core Python: Getting Started, we’ll continue our exploration of Python’s built‑in types and control flow structures by looking at strings, lists, dictionaries, and for loops. We’ll even be using Python to fetch some data from the web for processing.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe Today

GET EXCLUSIVE FULL ACCESS TO PREMIUM CONTENT

Get unlimited access to our EXCLUSIVE Content and our archive of subscriber stories.

Exclusive content

Latest article

More article