< Prev  |  Home  |  Next >

Python Boolean Data Type

As you have seen, some expressions give integers, for example:

Some expressions give string results, such as:

There is another other data type, called a Boolean value, which only ever gives an answer of ‘True’ or ‘False’. A bit like that game ’20 questions’, where you ask questions about what the other person is thinking, but the other person can only answer ‘Yes’ or ‘No’. What’s that? You don’t believe me? Try it our for yourself:

Notice that we use 2 equals signs (==) to mean ‘are they identical?’. We can also use less than (<) and greater than (>) symbols to compare strings as well as numbers. A string is ‘greater’ than another if it appears first in the alphabet. We have also checked to see whether a string is contained within another string.

Challenge

Write a program to find out whether “Some text” is the same as “some text”, whether -4 is less than -6, and whether the string “part” is in the string “party!!!1″.

Solution


Output:

False
False
True

‘and’ statement

It is also possible to ask if more than one thing is true, without having to write two separate statements. For example, a website will only let a person proceed if they are over 13 and if they agree to the site’s terms and conditions:

Will this person be allowed access? They do agree to the terms and conditions, but they aren’t over 13. So, the output is sadly:

False

‘or’ statement

If the above sounds a little harsh, maybe we can let the person proceed if they have their parent’s permission or if they are over 16. This means they are allowed access if either one or other of those 2 things is true:

Will this person be allowed access? They don’t have parental permission, but it’s ok as they are over 16. So the output is:

True

Challenge

Write a program to ask a person’s age, and tell them whether is it valid or not. For example, the ages -12 and 312 are invalid, but 0, 12 and 89 are valid.

Solution


Output:

What is your age?: 12
True
What is your age?: 221
False

< Prev  |  Home  |  Next >