# Python 101: Variables, Operators and Simple I/O

Variables in Python

## Variables in Python

Hi, and welcome back to Python 101. In the second chapter of this course, we will have a look at variables, operators and simple I/O.

### What you'll be able to make by the end of this chapter§

Let's have a look at the programs you will be able to materialize by the end of this chapter...

#### #1 Fill the form

```## Fill the form
## THOUGHT PROCESS: Prompt the user for a few questions -&gt; Place the answers in variables, convert the data types wherever needed -&gt; print the variables in a neat layout.

name = input("Enter your name: ")
age = input("Enter your age: ")
age = int(age)

print("Name\t\t:\t", name.upper())
print("Age\t\t:\t", age)
print("Email\t\t:\t", email.upper())
```
Try it here.

#### #2 Odd or even number?

```## Determine whether the given integer is even or odd. Even numbers are multiples of 2, whereas odd numbers are not.
## THOUGHT PROCESS: Prompt the user for a number -&gt; place the answer in a variable, convert the data type -&gt; operate on number turn by turn using if statement, print even if even, else print odd.

# Input from user
number = int(input("Enter a number to be tested: "))

# Logic: determining odd/even status using the modulus arithmetic operator
if number % 2 == 0:
print(number, "is even.")
else:
print(number, "is odd.")
```
Try it here.

#### #3 Leap Year or not?

```## Program to determine whether a given year is a leap year or not. A leap year is one with 29 days in the month of February, and mathematically, it is a multiple of 400 or 100 or 4.
## THOUGHT PROCESS: Prompt the user for an year -&gt; cast the input into an integer -&gt; set a default flag for later use -&gt; operate on number turn by turn using if statement, set flag accordingly -&gt; use the flag to print the correct conclusion.

# Take the input from the user
year = int(input("Enter an year: "))
isAleapYear = False # this variable serves as a flag in the program i.e. its value will be either true or false based on conditions, and at some point in the program, this flag will decide the flow of the program i.e. which statements to execute and which ones to skip according to its value. Since Python is an interpreted language, any variable we use inside the program needs to be declared beforehand so that the interpreter knows that there is a variable by this name. We can initialize it with the wrong value, it just needs to be in the memory so that the interpreter can recognize it. We can declare this variable anywhere before its use, but the convention is to declare variables at the top, before the actual logic, for easy code walkthrough.

# Determine whether the supplied year is a leap year or not
if year % 400 == 0:
isAleapYear = True
elif year % 100 == 0:
isAleapYear = True
elif year % 4 == 0:
isAleapYear = True
else:
isALeapYear = False

# Printing the result
if isAleapYear:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
```
Try it here.

### Variables§

• A variable is a container (say, a glass), that holds a value(say, water) that may change (say, coffee).
• Once a variable is assigned a value, the variable can be used in place of that value.
• Variables are stored in the memory of your computer. This memory space is vacated as soon as the program runs it full course (google 'Python Garbage Collection' for further study). To vacate this space while the program is still running, you may use the del keyword e.g. >>> del variable_name
• Python supports 4 primitive types of variables: string, integer, floating point, Boolean (complex numbers are also supported, but are not considered primitive). Apart from these, variables can also hold more complex data types like lists, sets, tuples and dictionaries, these are known as data structures. We will get to them in due time. For now, let's grapple with the fundamental ones: string, integer, floating point and Boolean.
• Declaring a variable is easy. Simply give your variable a name, followed by an equality sign(also called assignment operator), followed by the value you want your variable to hold.
```&gt;&gt;&gt; my_variable_1 = 'Hello'      # a string variable
&gt;&gt;&gt; my_variable_2 = "Hellooooo"  # another string variable
&gt;&gt;&gt; my_variable_3 = 23           # an integer variable
&gt;&gt;&gt; my_variable_4 = 23.0         # a floating point variable
&gt;&gt;&gt; my_variable_5 = True         # a Boolean variable
```

All of the above are assignment statements, with variables on the left and values on the right

• As you can see, we do not specify any additional keyword to specify what kind of data is the variable going to hold. Python is smart, it deduces the data type based on the value we are assigning to the variable. You can check it yourself by using the builtin type function.
```&gt;&gt;&gt; type(my_variable_1)
&lt;class 'str'&gt;
&gt;&gt;&gt; type(my_variable_2)
&lt;class 'str'&gt;
&gt;&gt;&gt; type(my_variable_3)
&lt;class 'int'&gt;
&gt;&gt;&gt; type(my_variable_4)
&lt;class 'float'&gt;
&gt;&gt;&gt; type(my_variable_5)
&lt;class 'bool'&gt;
```
• Each variable type i.e. str, int, float, bool, dict, tuple, list, set has a finite set of associated functions and attributes (properties) that can be called only on a particular type of variable e.g. a string variable is open to methods like upper(), lower(), title() etc. which are not applicable to an integer variable. Likewise, an integer variable has attributes like numerator and denominator that are not applicable to strings, so on and so forth.
You can see all the associated methods and attributes in IDLE by typing in the variable name at the prompt(>>>), followed by a period(.), and then pressing Tab(or Ctrl/Cmd + Space).
• You can replace the existing value in a variable.
```&gt;&gt;&gt; variable_1 = "hi"
&gt;&gt;&gt; variable_1 = "hello"
&gt;&gt;&gt; print(variable_1)
hello
```
• Variables need to be declared before they are referenced in the code, or else the interpreter raises a NameError exception. We will cover exceptions later.

#### Guidelines for naming a variable

There are two synonyms for variables: attributes & identifiers. From lexical point of view of the Python programming language(for that matter, any programming language), identifier is the name given to entities like class, functions, variables etc. It helps differentiating one entity from another and to refer them.

Following are the rules to make a valid identifier:

• it can be a combination of lowercase alphabet (a-z), uppercase alphabet (A-Z), digits (0-9) and underscore(_) e.g. my_variable, myVariable, myVar.
• it cannot begin with a digit i.e. myVar1 is fine but 1myVar is not.
• special symbols like \$, #, !, % etc. are not allowed since they have special meanings in the language.
• there is no limit on the length of identifiers, but try to make them as readable as you can, keeping readability in mind.
• identifiers are case sensitive. so myVar and myvar are two different variables.
• identifiers should not be keywords i.e. you should not make a variable named print or True etc., as it will create problems when you want to the keyword True.

• A string is a sequence of characters, and a character is, well, you know what a character is. In literal terms, character is anything you can put on to the screen using your keyboard, like a letter, a number, a space, special symbols such as hash, percent etc. "Hello there!" is a string. It consists of 12 characters(5 + 1 + 5 + 1).
• Strings can be declared using an apostrophe/single quote('), double quotes("), 3 apostrophes(''') or 3 double quotes("""). You can use all these interchangeably, as long as you wrap your string with the same set of symbols i.e. if you cannot begin a string with a single quote and end with a double quote.
```&gt;&gt;&gt; stringOne = 'Hi there!'
&gt;&gt;&gt; stringOne
'Hi there!'
&gt;&gt;&gt; stringTwo = "Hello there!'
&gt;&gt;&gt; stringTwo
'Hello there!'
&gt;&gt;&gt; stringThree = '''Hi there from triple apostrophe strings!'''
&gt;&gt;&gt; stringThree
'Hi there from triple apostrophe strings!'
&gt;&gt;&gt; stringFour = """Hello from triple double quoted strings!"""
&gt;&gt;&gt; stringFour
'Hello from triple double quoted strings'
```
• As I said, you could either of these 4 ways to denote a string. The last two, the triple quoted strings may span multiple lines and Python won't generate any error, while in the first two cases, it will generate an error if you try to span them over multiple lines.
```&gt;&gt;&gt; stringFive = "Hello # Press enter to make it span to the next line
SyntaxError: EOL while scanning string literal
&gt;&gt;&gt; stringSix = '''Hello from a verbatim string...

...'''
&gt;&gt;&gt; stringSix
'Hello from a verbatim string...\n\n...'
```

Triple quoted strings are really helpful when you want to output ascii art on to the screen, as they preserve the whitespace you specify in the variable. Ascii art is combination of special symbols(including alphabet and numbers) that depict a picture or a logo. These come in handy while trying to output a graphic when some event occurs in the program. One example is outputting different pictures in a game of hangman, depending how many tries has a player had.

```stringSeven = '''
_______
|/ &nbsp; &nbsp; |
| &nbsp; &nbsp; (-)
| &nbsp; &nbsp; \|/
| &nbsp; &nbsp; &nbsp;|
| &nbsp; &nbsp; / \
|
|___
'''
```
If you simply enter this variable name in the interpreter and press enter, you will see a combination of sequences such as \n, \xa0. These are escape sequences, you will learn about them in the next section. For now, suffice it to know that to output this graphic as it is depicted here, you have to wrap the variable in a print() function i.e. >>> print(stringSeven)

Triple quoted strings are also used as docstrings in functions, we will get to that later.

• You may use normal strings to span multiple lines by using the line continuation character i.e. backslash (\).
```&gt;&gt;&gt; stringEight = 'This string is most likely to violate the Python guideline which says you \
should try to limit your statements to 79 characters and no further.'
&gt;&gt;&gt; stringEight
'This string is most likely to violate the Python guideline which says you should try to limit your statements to 79 characters and no further.'
```

However, PEP, the Python Enhancement Proposal prefers that if you want your strings to span multiple lines, you may use the brackets, like below.

```&gt;&gt;&gt; stringNine = ("This string is also likely to violate the Python guideline which says you "
"should try to limit your statements to 79 characters and no further.")
&gt;&gt;&gt; stringNine
'This string is also likely to violate the Python guideline which says you should try to limit your statements to 79 characters and no further.'
```

#### Unpacking a string

Strings are sequences of characters, and they can be unpacked into individual variables. Unpacking procedure can be performed on lists, dictionaries, sets and tuples, but we'll look at that later. Here's how you unpack a string:

```&gt;&gt;&gt; stringTen = "Hello"
&gt;&gt;&gt; a,b,c,d,e = stringTen
&gt;&gt;&gt; a
'H'
&gt;&gt;&gt; b
'e'
&gt;&gt;&gt; c
'l'
&gt;&gt;&gt; d
'l'
&gt;&gt;&gt; e
'o'
```

#### Referring individual characters in a string with indexes

You can extract a particular string out of a string using a number in square brackets, as below:

```&gt;&gt;&gt; stringEleven = "Ethan"
&gt;&gt;&gt; stringEleven[2]
'h'
```

What you specified in the brackets is what is called an index. Indexes are a programming language's way of storing your data sequentially in the memory. Indexes are zero based, that is the first character will be given an index of 0. Here's how the string 'Hello there!' will be stored in the memory:

```&gt;&gt;&gt; arrayRepresentation = '''
_   _   _   _   _   _   _   _   _   _   _   _
|   |   |   |   |   |   |   |   |   |   |   |   |
| H | e | l | l | o |   | t | h | e | r | e | ! |
| _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ |
0   1   2   3   4   5   6   7   8   9  10  11
'''
&gt;&gt;&gt; arrayRepresentation[8]
'e'
&gt;&gt;&gt; arrayRepresentation[6]
't'
```

You can access the characters from the end as well, using negative indexes. In this case, the first character from the end will be represented by -1. Give that a try.

NOTE: Python strings are immutable, meaning you cannot alter a string once it is declared. You, however, can assign a different string to the variable. Sounds confusing, here's what I mean by the above:

```&gt;&gt;&gt; stringTwelve = "Hello"
&gt;&gt;&gt; stringTwelve[2] = 'G'   # Can't alter a string using indexes
TypeError: 'str' object does not support item assignment
&gt;&gt;&gt; stringTwelve = "Hi"    # Can assign a different value to the variable
&gt;&gt;&gt; stringTwelve
'Hi'
```

FYI: Among the sequence data types, dictionaries and lists are mutable, whereas sets, strings, tuples are immutable.

#### Repeating a string

You can repeat a string multiple times by using the asterisk symbol (*), like this:

```&gt;&gt;&gt; stringThirteen = "Hi "
&gt;&gt;&gt; stringThirteen * 5
'Hi Hi Hi Hi Hi '
```

#### Concatenating two or more strings

You can join two strings by using the addition symbol (+), or by giving each string as an argument to the print function, or by placing the strings to be joined adjacent to each other wrapped in their own quotes. See below for example.

```&gt;&gt;&gt; stringFourteen = "Hi"
&gt;&gt;&gt; stringFifteen = " there!"
&gt;&gt;&gt; stringFourteen + stringFifteen
'Hi there!'
&gt;&gt;&gt; print(stringFourteen,stringFifteen)   # note how print adds a space between the strings in the result.
'Hi  there!'
&gt;&gt;&gt; stringFourteenTwo = 'hel' 'lo''...there'   # haven't used this much myself, but it is supported by Python.
&gt;&gt;&gt; stringFourteenTwo
'hello...there'
```

Be wary of the fact for string concatenation, all the participants should be of the type string, or you will see a TypeError. Refer to type casting below to make the required conversion.

#### Escape Sequences: how to print special characters inside strings

There are many characters you might want to include in your string, but inserting them normally will generate errors or unexpected results e.g. say you wanted to quote a great author or wanted to include a dialogue from a character in direct speech, or wanted to use the sarcastic quotation marks, or further more, wanted to emphasize a particular word using single quotes, here's how you would do it:

```&gt;&gt;&gt; stringSixteen = "Albert Einstein once said, \"Any fool can know. The point is to understand.\"" # The double quotes have special meaning in Python i.e. they are used to denote a string, that doesn't mean you can't use them in the English language constructs. You may do so by prefixing your character by a backslash character.
&gt;&gt;&gt; print(stringSixteen)
Albert Einstein once said, "Any fool can know. The point is to understand."
&gt;&gt;&gt; stringSeventeen = 'I am here to print "Game Over" on the screen.'
&gt;&gt;&gt; print(stringSeventeen)
I am here to print "Game Over" on the screen.
&gt;&gt;&gt;
```

Actually, you can use nested quotes as well, to achieve the above purpose like this:

```&gt;&gt;&gt; stringSixteen = 'Albert Einstein once said, "Any fool can know. The point is to understand."' # Nesting quotes inside the other kind of quotes.
&gt;&gt;&gt; print(stringSixteen)
Albert Einstein once said, "Any fool can know. The point is to understand."
```

Python is okay with above as long as you place the closing quotes in the right place i.e. the quotes you begin later should be closed first.

What you cannot do is this:

```&gt;&gt;&gt; stringEighteen = 'I am here to print 'Game Over' on the screen.'
SyntaxError: invalid syntax
```

because Python cannot make sense of the above, you need to escape the single quotes in the middle by prefixing them with a backslash (\).

```&gt;&gt;&gt; stringEighteen = 'I am here to print \'Game Over\' on the screen.'
&gt;&gt;&gt; print(stringEighteen)
I am here to print 'Game Over' on the screen.
```

Following are the prominent escape sequences used in Python:

```&gt;&gt;&gt; print("Backslash: \\ ")
Backslash: \
&gt;&gt;&gt; print("Single quote: \' ")
Single quote: '
&gt;&gt;&gt; print("Double quote: \" ")
Double quote: "
&gt;&gt;&gt; print("New line: \n some text")
New line:
some text
&gt;&gt;&gt; print("Tab: \t some text")
Tab: 	 some text
```

Apart from the quotes(\" and \') sequences, the Python interpreter does not interpret any of the escape sequences when you simply enter a string and press enter. You would have to use them in a print() function to see the effect of, say a \n or a \t, just like you would in a program.

```&gt;&gt;&gt; some_variable = "Hi\nthere!"
&gt;&gt;&gt; some_variable
'Hi\nthere!'
&gt;&gt;&gt; print(some_variable)
Hi
there!
```

System bell with the \a sequence doesn't work in interpreters, you will have to save a .py file with a print("\a") statement and run it from the command prompt to hear it.

#### Slicing a string

Slicing means getting a substring of a given string i.e. getting a portion of the original string. Here's how we achieve slicing in Python.

```&gt;&gt;&gt; originalString = "magnanimous"
&gt;&gt;&gt; arrayRepresentationOfOriginalString = '''           # for understanding indexes used later

0   1   2   3   4   5   6   7   8   9  10
_   _   _   _   _   _   _   _   _   _   _
|   |   |   |   |   |   |   |   |   |   |   |
| m | a | g | n | a | n | i | m | o | u | s |
| _ | _ | _ | _ | _ | _ | _ | _ | _ | _ | _ |
-11 -10  -9  -8  -7  -6  -5  -4  -3  -2  -1
'''
&gt;&gt;&gt; st = originalString   # for easy reference
&gt;&gt;&gt; st[1:5]               # st[x:y] gives us a string starting with st[x] and ending with st[y-1]
'agna'
&gt;&gt;&gt; st[-5:-1]         # -5 is actually 6 and -1 is actually 10, so this becomes st[6:10]
'imou'
&gt;&gt;&gt; st[1:5:1]         # st[x:y:z] gives us a string starting with st[x], with a step over size of 1, ending with st[y-1]
'agna'
&gt;&gt;&gt; st[1:5:2]         # starting at index 1, ending with index 5-1, with a difference of 2 between the indexes of characters
'an'
&gt;&gt;&gt; st[5:1:-1]        # FOR NEGATIVE STEP SIZE: begin at index 5, move in the opposite direction i.e. left, finish at index 1 + 1.
'nang'
&gt;&gt;&gt; st[-5:-8:-1]
'ina'
&gt;&gt;&gt; st[:5]            # select everything from index 0 to 5-1
'magna'
&gt;&gt;&gt; st[5:]            # select everything from index 5 till the end of the originalString
'nimous'
&gt;&gt;&gt; st[:]             # gives the originalString itself
'magnanimous'
```
Slicing takes characters from left to right of a string, unless you specify a negative step size. What this means is that by default, the first number should should be the index of a character on the left of character whose index is denoted by the second number, UNLESS a negative step size is specified, in which case, the first number should be the index of a character on the right of the character whose index is denoted by the second number. Not confusing, right?

#### String methods

• Python provides numerous methods for tweaking strings, each of which is handy. You can see all these by entering a string in the Python interpreter with single/double quotes, typing in a period (.), then pressing tab or Ctrl/Cmd + Space.
• To bring these into action, select one of these using arrow keys, double press Tab, type in two round brackets i.e. () and hit enter e.g. "Sample".upper()
• To get help on these methods, say title method you may do something like this: >>> help("Sample".title)

I'll list a few prominent ones here, you can explore the rest.

```&gt;&gt;&gt; stringNineteen = "lab rat for testing string methods"
&gt;&gt;&gt; s1 = stringNineteen.upper() # 'LAB RAT FOR TESTING STRING METHODS' # converts all string characters to upper case
&gt;&gt;&gt; s2 = stringNineteen.lower() # 'lab rat for testing string methods' # converts all string characters to lower case
&gt;&gt;&gt; s3 = stringNineteen.capitalize() # 'Lab rat for testing string methods' # converts first character of the string to upper case
&gt;&gt;&gt; s4 = stringNineteen.count('t')  # 5 # gives the number of occurrences of the provided character or sequence in the originalString
&gt;&gt;&gt; s5 = stringNineteen.title() # 'Lab Rat For Testing String Methods' # capitalizes the first letter of every word, just like in a headline title
&gt;&gt;&gt; s6 = stringNineteen.replace('t', 'w') # replaces occurrences of first argument with the second one. Arguments could be a sequence as well.
&gt;&gt;&gt; s7 = stringNineteen.split()   # ['lab', 'rat', 'for', 'testing', 'string', 'methods'] # gives a list of words separated by space in the originalString. Could achieve the same purpose by .split(" "). You could specify any other delimiter, like a comma i.e. .split(",").
&gt;&gt;&gt; s8 = "_".join(stringNineteen) # 'l_a_b_ _r_a_t_ _f_o_r_ _t_e_s_t_i_n_g_ _s_t_r_i_n_g_ _m_e_t_h_o_d_s' # joins together originalString with the given string as separator

## COMMON BUILTIN FUNCTIONS APPLICABLE ON STRINGS
&gt;&gt;&gt; ord('a')       # 97     # ord() function takes a single character(special ones too) and returns its Unicode value. Unicode is a collection of codes for more than 1,20,000 characters covering letters, numbers in a variety of languages, including symbols. Unicode values for letters a through z are 97 to 122 &amp; A through Z are 65 to 90. It is inverse of the builtin chr() function.
&gt;&gt;&gt; chr(97)        # 'a'    # chr() function takes a Unicode value and returns the symbol or letter represented by the provided code in the Unicode dictionary. It is inverse of the builtin ord() function.
```

#### Calculating the length of a string

We can use the inbuilt len() function to calculate the length of a string. The len() is a generic method, meaning it can be used to calculate the length of lists, tuples, dictionaries etc.

```&gt;&gt;&gt; len("Hello")
5
&gt;&gt;&gt; string1 = "merry merry"
&gt;&gt;&gt; len(string1)
11
```

So far, we have seen how the print() function is arguably the most used builtin function. Let's discuss a couple more functionalities provided by the print() function.

#### Ending a statement with a desired character

The default behavior of the print() is to print a new line after whatever we ask it to print. Now that you know about escape sequences, you would have probably guessed that it ends with a \n.

We can tweak this to suit our needs, using the end argument. Let's see this in action:

```## Put the following code in a script and execute it on the command line.
print("hunky", end = "-")
print("dory")

## The output on the command line will be:
hunky-dory
```

#### Printing multiple values

We have actually touched upon this in the string concatenation bit, for the sake of completeness, let's see it once again. We can print multiple values using the same print() function, like this:

```&gt;&gt;&gt; a = "apple"
&gt;&gt;&gt; b = "ball"
&gt;&gt;&gt; c = "cat"
&gt;&gt;&gt; print(a, b, c)
apple ball cat

# The spaces in the print statement after commas bear no effect on the output, that's just the default behavior of print function, it puts a space between the arguments supplied to it.
```

### Number data types§

Python 2 supports int, float, complex and long data types. However, long was dropped in Python 3. Integers are numbers without any fractional component e.g. 2, -2, 0. Floating point numbers have a fractional component e.g. 2.3, 3.14. Complex numbers have an imaginary bit along with them, represented by the letter j.

```&gt;&gt;&gt; myInt = 2
&gt;&gt;&gt; type(myInt) # &lt;class 'int'&gt;
&gt;&gt;&gt; myFloat = 3.14
&gt;&gt;&gt; type(myFloat) # &lt;class 'float'&gt;
&gt;&gt;&gt; myComp = 2 + 3j
&gt;&gt;&gt; type(myComp) # &lt;class 'complex'&gt;
```
Floating points have some known issues in python, especially while comparing two floating points. Visit here for floating point considerations.

#### Arithmetic Operators

Python supports mixed arithmetic: when an arithmetic operator has operands of different numeric types, the operand with less precision is widened to that of the other, where integer is narrower than floating point, which is narrower than complex.

Mathematical operators work more or less the same way on all integer types, except for a couple of exceptions.

```&gt;&gt;&gt; a = 6
&gt;&gt;&gt; b = 4
&gt;&gt;&gt; a + b         # 10          # addition
&gt;&gt;&gt; a - b         # 2           # difference
&gt;&gt;&gt; a * b         # 24          # product
&gt;&gt;&gt; a / b         # 1.5         # quotient
&gt;&gt;&gt; a // b        # 1           # floored quotient i.e. the largest integer less than the quotient(1.5) # not applicable on complex numbers
&gt;&gt;&gt; a % b         # 2           # remainder of the division a / b i.e. 6 / 4  # not applicable on complex numbers
&gt;&gt;&gt; a ** b        # 1296        # a raised to the power b i.e. 6 * 6 * 6 * 6
&gt;&gt;&gt; -a            # -6          # negation of a

c = 6 + 4j
f = 2.8
## Builtin functions designed for the integer data types
&gt;&gt;&gt; abs(-a)       # 6           # absolute value or magnitude of a
&gt;&gt;&gt; int(f)        # 2           # f converted to an integer # Result is floored
&gt;&gt;&gt; float(a)      # 6.0         # a converted to a floating point
&gt;&gt;&gt; complex(a, b) # (6+4j)      # a complex number with real part a and imaginary part b
&gt;&gt;&gt; c.conjugate() # (6-4j)      # Conjugate of the complex number c
&gt;&gt;&gt; divmod(a, b)  # (1, 2)      # the pair (a // b, a % b)
&gt;&gt;&gt; pow(a, b)     # 1296        # a raised to the power b i.e. 6 * 6 * 6 * 6
&gt;&gt;&gt; max(a, b)     # 6           # returns the larger of the two  # not applicable on complex numbers
&gt;&gt;&gt; min(a, b)     # 4           # returns the smaller of the two # not applicable on complex numbers
```

### Boolean Data Type§

Boolean is the simplest data type you will ever see. It only has two valid values: True and False. It was added to Python in version 2.3. Since then, many builtin functions and standard library functions were changed to return either True or False e.g. the isinstance(x, y) which tells us whether x is of the type y.

Boolean data type was added with the primary goal of making code clearer. For example, if you're reading a function and encounter the statement return 1, you might wonder whether the 1 represents a Boolean truth value, an index, or just a number to be used elsewhere. If the statement is return True, however, the meaning of the return value is crystal clear.

In all actuality, True and False are string versions of integers 0 and 1, and Boolean data type is a subclass of the 'int' type. Hence, it supports arithmetic, like this:

```&gt;&gt;&gt; True + 1
2
&gt;&gt;&gt; True * 20
20
&gt;&gt;&gt; False + 1
1
&gt;&gt;&gt; False * 20
0
&gt;&gt;&gt; int(True)
1
&gt;&gt;&gt; int(False)
0
```

#### Boolean operators

Following are the three boolean operators: or, and and not.

```# a or b: if a is false, then b, else a
# WHEN BOTH VALUES DENOTE FALSE: returns the second value.
# WHEN ONLY ONE VALUE DENOTES TRUE: returns the value denoting true.
# WHEN BOTH VALUES DENOTE TRUE: returns the first value
# As soon as it encounters a true value, it stops evaluating further.
&gt;&gt;&gt; 0 or 2
2
&gt;&gt;&gt; 2 or 0
2
&gt;&gt;&gt; 2 or 5
2
&gt;&gt;&gt; False or True
True
&gt;&gt;&gt; True or False
True
&gt;&gt;&gt; 0 or False
False

# a and b: if a is false, then a, else b
# WHEN BOTH VALUES DENOTE FALSE: returns the first value.
# WHEN ONLY ONE VALUE DENOTES FALSE: Returns the value denoting false.
# WHEN BOTH VALUES DENOTE TRUE: returns the second value.
# As soon as it encounters a false value, it stops evaluating further.
&gt;&gt;&gt; 0 and 2
0
&gt;&gt;&gt; 2 and 0
0
&gt;&gt;&gt; 2 and 5
5
&gt;&gt;&gt; True and False
False
&gt;&gt;&gt; False and True
False
&gt;&gt;&gt; 0 and False
0

# not a: if x is false, then True, else False
&gt;&gt;&gt; not True
False
&gt;&gt;&gt; not False
True
&gt;&gt;&gt; not 5
False
&gt;&gt;&gt; not 0
True
```

### A Few General Things§

Here are a few handy things you should take note of.

#### Getting user input: input()

The builtin input() function is used for receiving input from the user. The input function takes an argument, which is what will be flashed on the screen before the user enters a value. We can assign the value entered to a variable that we can use later in the program.

```&gt;&gt;&gt; input("Tell me your name. \n")
Tyrion Lannister                 # User types this and presses enter
'Tyrion Lannister'

&gt;&gt;&gt; name = input("Tell me your name. \n")
Tyrion Lannister
&gt;&gt;&gt; print("Did you just say " + name + "?")
Did you just say Tyrion Lannister?

```
It is worth emphasizing that the input function returns a string, so if you require it to be some other data type, it needs to be converted into the required data type. Refer to the next section on how to do just that.

#### Casting: Type Conversions

There will be times when you need to convert a string to a numeric form, or vice versa. For example, try executing

```&gt;&gt;&gt; a = 21
&gt;&gt;&gt; print("I am " + a + " years old.")
```

You should see something like this:

```Traceback (most recent call last):
File "python", line 1, in &lt;module&gt;
TypeError: Can't convert 'int' object to str implicitly
```

To get around situations like this, we can use the builtin str(), int(), float() functions.

```## Converting an integer to a string
&gt;&gt;&gt; a = 21
&gt;&gt;&gt; print("I am " + str(a) + " years old.")
I am 21 years old.

## Converting a string to an integer
&gt;&gt;&gt; age = input("How old are you? \n")      # input() returns a string, so age is a string right now.
How old are you?
22
&gt;&gt;&gt; age = int(age)                       # converting a string(age on the right) to an int(age on the left)
&gt;&gt;&gt; age_in_days = age * 365
&gt;&gt;&gt; print("You have lived for more than" + str(age_in_days) + " days.")
You have lived for more than 5830 days.

## Converting a string to a floating point
&gt;&gt;&gt; temp = float(input("Pop Quiz: What is the normal body temperature(in Celsius units) of humans?\n"))
Pop Quiz: What is the normal body temperature(in Celsius units) of humans?
38.6
&gt;&gt;&gt; print("You entered: " + str(temp))
You entered: 38.600000000000001
```

#### Comparison Operators

At some point in your program, you will the need to compare two values, and then proceed on the basis of the result of the comparison. For example, you have to compare the entered string with the stored password of the safe, and grant or revoke access to the safe on the same basis, or you have to monitor the temperature of a furnace and throw off an alarm as soon as it surpasses the maximum allowed value of temperature. Okay, a little too intricate for an example, but you get the point, don't you?

Python supports 8 comparison operations, here they are with examples:

```## COMPARISON OPERTORS
# &lt;                ## strictly less than
# &lt;=               ## less than or equal to
# &gt;                ## strictly greater than
# &gt;=               ## greater than or equal to
# ==               ## equal to
# !=               ## not equal to
# is               ## object identity tester: checks if the variables on either side of 'is' point to the same object in the memory
# is not           ## negated object identity tester

## VARIABLES FOR EXAMPLES BELOW
&gt;&gt;&gt; a = 360
&gt;&gt;&gt; b = 500
&gt;&gt;&gt; c = 360
&gt;&gt;&gt; d = a

## EXAMPLES
####################### &lt;
&gt;&gt;&gt; a &lt; b      # 360 &lt; 500
True
&gt;&gt;&gt; a &lt; c      # 360 &lt; 360
False

####################### &lt;=
&gt;&gt;&gt; a &lt;= b     # 360 &lt;= 500
True
&gt;&gt;&gt; a &lt;= c     # 360 &lt;= 360
True

####################### &gt;
&gt;&gt;&gt; a &gt; b      # 360 &gt; 500
False
&gt;&gt;&gt; a &gt; c      # 360 &gt; 360
False

####################### &gt;=
&gt;&gt;&gt; a &gt;= b     # 360 &gt;= 500
False
&gt;&gt;&gt; a &gt;= c     # 360 &gt;= 360
True

####################### ==
## returns True if the objects referred to by the variables are equal.
&gt;&gt;&gt; a == b     # 360 == 500
False
&gt;&gt;&gt; a == c     # 360 == 360
True
&gt;&gt;&gt; password == "letmein"      # "letmein" == "letmein"
True

###################### !=
&gt;&gt;&gt; a != b     # 360 != 500
True
&gt;&gt;&gt; a != c     # 360 != 500
False
&gt;&gt;&gt; password != "letmein"      # "letmein" != "letmein"
False

###################### is
## is will return True if two variables point to the same object
&gt;&gt;&gt; a is d         # we assigned a to d by d = a, so d points to the same object as a
True
&gt;&gt;&gt; d is a
True
&gt;&gt;&gt; a is c         # we assigned the value 360 to both a and c, so only the a == b returns True
False
&gt;&gt;&gt; a is b
False
## the way the is operator works is that it compares the unique numbers of the two operands given to them by Python for the current session. These unique numbers are the identity

###################### is not
&gt;&gt;&gt; a is not b
True
&gt;&gt;&gt; a is not c
True
&gt;&gt;&gt; a is not d
False
```
BEHIND THE SCENES OF THE is OPERATOR: The is operator actually compares the values returned by the builtin id() function, applied on variables on either side of the word is. The builtin id() function gives the "identity" of an object i.e. an integer which is guaranteed to be unique and constant for this object during its lifetime. Objects with non-overlapping lifetimes may have the same id value.

```&gt;&gt;&gt; a = 360
&gt;&gt;&gt; b = 500
&gt;&gt;&gt; c = 360
&gt;&gt;&gt; d = a
&gt;&gt;&gt; id(a)
23543243    # yours will be different
&gt;&gt;&gt; id(b)
23423423
&gt;&gt;&gt; id(d)
23543243    # same as a, since we made d refer to a by executing d = a
```

PYTHON CACHES SMALL INTEGER OBJECTS: Python usually caches(places them in cache memory for quick retrieval, to save time) the id of numbers from -5 to 256(this range many vary on different implementations of the language), so if you assign any number within -5 - 256 to two or more variables, their id will be same i.e.

```&gt;&gt;&gt; a = 100
&gt;&gt;&gt; b = 100
&gt;&gt;&gt; id(a)
# some random number
&gt;&gt;&gt; id(b)
# the same number as returned by id(a)
```

### Controlling The Flow Of The Program§

Python is an imperative language, as opposed to being a declarative language. Imperative paradigm suggests that the language uses its statements to jump around the program and control the way a program operates. In other words, the control shifts from one block of code to the other. Declarative languages emphasizes on what the statements would accomplish, and not on how they would do it. You specify what you want done, it is left on the machine (more specifically, compiler) to figure that out. Examples of declarative languages are SQL and Prolog.

There are three methods of controlling the flow in Python:

• Loops
• Branchincg
• Function calls

We'll cover branching for now. Branching, as the word suggests, implies that if a given condition(also known as predicate) is true, execute the following indented(four spaces or a tab) code block. Else, execute another code block. There is only one statement in Python that implements branching i.e. the if statement.

Executing code blocks in the interactive interpreter: Press enter after the colon, you will notice that the interpreter automatically indents the next line, so type away. Once you have written all statements in the new indented code block, press enter twice, and this should execute the block you just wrote.

#### if statement

The simplest form of an if statement is: if a given condition is true, execute this piece of code. If it is false, proceed by skipping the code block.

```if(True):
print("Yay!")       # prints

if True:
print("Yay!")       # prints

flag = True
if flag:
print("Yay!")       # prints

flag = False
if flag:
print("uh oh....")  # doesn't print

someTrueValue = 2
if someTrueValue:
print("Yeah!")      # prints

if not someTrueValue:   # evaluates to false
print(" :O ")       # doesn't print

someFalseValue = 0
if someFalseValue:
print("No;.")       # doesn't print

if not someFalseValue:  # evaluates to true
print("Bwahahaha")  # prints

if(2 &lt; 5):
print("You are right, 2 IS less than 5.")      # prints

if( len("Hello") == 5 ):
print("Hello is a five letter word.")          # prints

if(False):
print("Anything, it is not going to be printed anyway.")
print("The condition was wrong.")

if False:
print("Anything, it is not going to be printed anyway.")
print("The condition was wrong.")

if( 2 &gt; 5 ):
print("Bleh")
print("The condition was wrong.")
```
The predicate doesn't always have to evaluate to a Boolean result. Python is not strict this way, and never will be, as stated in PEP 285. The evaluated result may even be a list or a tuple, or any other object.

The elif and else clauses give you more ways to cover the domain of your problem. They are optional to specify.
Elif: If the predicate in the "if" is false, it will test the predicate on the first elif, and run that code block if it’s true. If the first elif is false, it tries the second one, and so on. As soon as it finds a true predicate, it will stop checking branches, and skip the rest of the if statement.
Else: The else clause is placed at the bottom of the entire if statement. If none of the other branches are executed, then Python will run this branch. It doesn't take any predicate.

```if (2 &gt; 10 ):
else:
print("Executing the else block.")

if ( 2 &gt; 10 ):
print("Oh dear....")
elif ( 2 &gt; 3 ):
print("...")
elif ( 2 &gt; 1 ):
print("Finally!")

if ( 2 &gt; 10 ):
print("Oh dear....")
elif ( 2 &gt; 3 ):
print("...")
elif ( 2 &gt; 2 ):
print(".........")
else:
print("Enrolling you for Mathematics for Dummies....")
```

### On the agenda in the next chapter§

Strings, Numbers, Operators, Controlling the flow, we have covered significant ground in this chapter, kudos to you! Try the 3 programs yourself. You will be able to make sense of them now, and in case you don't, then place a comment down below.

In the next chapter, we will cover 2 the looping constructs, namely, for and while. Till then, cheerio!