Chapter 2
Python Fundamentals:
There is no one way to code. Some codes are basic and will just need a line or two of code to tell
Python what to do. Others can take up blocks of code to tell the interpreter how to behave. It doesn’t
necessarily matter what kind or length of code you’ll be working with, there are going to be parts
(Python fundamentals) that are similar with all of them. Learning these fundamentals is the key to
learning to code your own programs. When you see the word “interpreter”, we are referring to Python
itself. When you download Python, you download everything that you need, including the text editor
where you write your code and Python will automatically interpret everything you do.
The Keywords in Python:
Like many programming languages, Python has a set of keywords that are strictly reserved for the compiler. They can’t be used as identifiers. Using them as identifiers will result in errors.
Here’s a list of keywords in the Python language.
false, class, finally,
none, continue, for,
true, def, from,
and, del, global,
as, elif, if,
assert, else, import,
except, in, raise,
is, return, with,
lambda, try, yield,
nonlocal, while, break,
not, or, pass
As you read this book you’ll come across these keywords. Keywords such as class, elif, for, while, if, raise and more.
Naming Identifiers:
In a Python program, there are quite a few identifiers that you can work with. You will find that theyhave many different names and can go by things like variables, entities, classes, and functions. Whenyou work on naming an identifier, you can use the same information and the same rules for all of them- this makes it a bit easier to remember what you should do. There are guidelines that help withnaming different identifiers.You have a lot of options when naming identifiers. You can use lowercase and uppercase letters incombination. You can also use the underscore symbol and numbers. Any combination of these arefine, just make sure that you don’t start an identifier name with a number and that there aren’t spacesin between the words if you use more than one to name the identifier. Examples include:
1. myClass2. var_13. print_this_to_screen
CamelCase is used by most programmers (depends on programmer) when naming identifiers. It’seasier on the eyes and has been in practice for years. CamelCase is just a convention for namingidentifiers. An example would be if you name a variable to hold a value for the number of cars in aparking lot for a program that requires this value. With CamelCase, you would capitalize the firstletter of each word: NumberOfCarsInLot or numberOfCarsInLot.Other programmers prefer the underscore symbol to separate words. This really boils down to yourstyle of coding.Other guidelines include picking an easy name to remember. This is helpful when you’ve beenworking on a program for a while or when you return to a program after a few days off. If you name itsomething that you won’t remember later on, this could cause some issues.Outside of these simple guidelines, you should be able to find plenty of names for your identifiers but,as stated before, you must not use reserved keywords for your identifiers. For example, you could notdo this:>>> global = 1File "<interactive input>", line 1global = 1^If you did, the result would be this:
SyntaxError: invalid syntax
You also cannot use special characters, such as:
- !
- @
- #
- $
- %
- And so on.
If you do something like this:
>>> a@ = 0
File "<interactive input>", line 1
a@ = 0
^
You would get this:
SyntaxError: invalid syntax
Control Flow in Python:
One of the most important things in Python is control flow. This is the order the program will be
executed in and this is regulated using function calls, loops, and conditional statements and, if they are
not in the right order in your code, the program simply cannot execute. For the purposes of this
section, we are going to concentrate on statements, which are nothing more than strings. A string is
text that you want to be displayed or you want exported out of your Python program. Python knows
that a piece of text is meant to be a string because you use either double (“”) or single (‘’) quote
marks around the text. IMPORTANT – consistency is key – if you start the string with, let’s say,
double quotes, you must end it with double quotes. Never mix your singles and doubles up because
Python won’t know what is happening. Let’s look at some examples of common Python conditional
statements:
If Statements:
The syntax for the if statement is:
if condition:
# do something
elif condition:
# do something else
else:
# do something else again
There isn’t a statement that will end the if statement and there is also a colon (:) at the end of each
control flow statement. Python is reliant on the correct use of colons and indentation so that it can tell if
it is in a specific code block or not.
For example:
if a == 1:
print "a is 1, and changes to 2"
a = 2
print "finished"
In this example, the initial print statement will only be executed if a is 1. The same goes for the a = 2
statement. However, the print “finished” statement will be executed, no matter what, when Python
comes out of the if statement.
The conditions in an if statement may be anything so long as a Boolean value is returned.
For example, these are valid conditions:
- a == 1
- b !
- c < 5=
They are valid because each will return a Boolean value of True or False, dependent on whether the
statement is true or false. You can use standard comparisons, such as:
- equal - ==
- not equal - !
- less than or equal to - <=
- greater than or equal to - >=
You can also use logical operators, like:
- and
- or
- not
Parentheses () are used as a way of isolating sections of the condition and this is to make sure that
Python knows which order to execute the comparisons in.
Take this example:
if (a == 1 and b <= 3) or c > 3:
# do something
Python now knows which order the comparisons must be run in.
For Loops:
You will hear about loops whenever you hear about Python and the most common one is the for loop.
The basic syntax is:
for the value in iterable:
# do some things
The iterable can be whichever of the Python objects that can be iterated over and that includes tuples, lists, strings, and dictionaries. Try inputting this into the editor:
In [1]: for x in [3, 1.2, 'a']:
...: print x
...:
3
1.2
'a'
Because the colon was placed at the end of line 1, Python will automatically know that the next line is
to be indented so you don’t have to do that yourself. When you have typed the print statement in,
remember to press the enter key twice so that Python knows you have completed the code.
One of the most common of all the for loop types is where a value goes in between two integers with a
set of a specific size. We do this by using the range function. If a single value is provided, we get a list
that ranges from 0 to the value of minus1:
A common type of for loop is one where the value should go between two integers with a specific set
size. To do this, we can use the range function. If given a single value, it will give a list ranging from 0
to the value minus 1:
In [2]: range(10)
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If two values are given, these are the starting value and one added to the ending value:
In [3]: range(3, 12)
Out[3]: [3, 4, 5, 6, 7, 8, 9, 10, 11]
Lastly, if a third number is provided, this will be the step size:
In [4]: range(2, 20, 2)
Out[4]: [2, 4, 6, 8, 10, 12, 14, 16, 18]
The range function may be used in a for loop as the iterable.
While Loops:
Like other computer languages, Python also has a while loop, which is pretty much like the for loop,
with the exception that the iterations are defined by conditions and not iterators:
while condition:
# do something
Have a look at this example:
In [1]: a = 0
In [2]: while a < 10:
...: print a
...: a += 1
...:
0
1
2
3
4
5
6
7
8
9
In this, the loop will be executed until a equals or goes above 10.
More on loops in further chapter.
Comments:
Sometimes when you are writing out your code, you will need to include some comments. These are
like little notes inside of the code that you, and the other programmers who look at the code, will be
able to read through to understand what is going on in the different parts of the code. These will
include a # symbol in front of the comment so that the compiler knows to just skip over that part and
go on to the next part of the code.
You are able to add in as many of these comments as you would like to help explain the code that you
are writing and to help it make sense. As long as you include the # sign in front of the comment that
you are leaving, the compiler will leave it alone and move on to the next block of code.
Variables:
Variables are another common thing used in Python code and are nothing more than storage locations.
In fact, they are portions of the memory that are reserved for the storage of values and how they are
stored is dependent on the data type of the variable. By assigning certain data types, you can store
integers, characters, and decimals.
Variables can be named pretty much anything, but the name must begin with an underscore or a letter
and they are case sensitive. To assign a value to a variable, we use the = sign.
In this example, the operand that is on the left of the operator (=) is the variable while the right
operand is the value that is assigned to it:
#!/usr/bin/python
counter = 100 # integer assignment
miles = 1000.0 # floating point
name = "Brian" # string
print counter
print miles
print name
Let’s break this down:
100 – the value assigned to the variable called counter
1000.0 – the value assigned to the variable called miles
Brian – the value assigned to the variable called name
This will be the ouput:
100
1000.0
Brian
Operators:
Operators are pretty simple parts of your code, but you should still know how they work. There are a
few you can use. For example, the arithmetic functions are great for helping you to add, divide,
subtract, and multiply different parts of code together. There are assignment operators that will assign
a specific value to your variable so that the compiler knows how to treat this. There are also
comparison operators that will allow you to look at a few different pieces of code and then determine
if they are similar or not and how the computer should react based on that information.
Let’s look at the different types of operators.
The main types of operator in Python are:
- Arithmetic operators
- Boolean operators
- Relational operators
An operator can have one or two operands – the input argument of the operator. If the operator will
only go with one operand, it is called a unary operator; two operands and it is called a binary
operator. Plus and minus signs are both unary sign operators and addition and subtraction operators,
depending on the situation:
>>> 2
2
>>> +2
2
>>>
The plus may be used to indicate a positive number, although this is not often used for this, while the
minus will change the sign of a particular value:
>>> a = 1
>>> -a
-1
>>> -(-a)
1
Addition and multiplication operators are both binary operators, which means two operands are used:
>>> 3 * 3
9
>>> 3 + 3
6
The Assignment Operator
The assignment operator is = and this is what we use to assign values to variables. In math, = has
another meaning altogether. When we use equations, the = operator is used as an equality operator =
the left-hand side of the equation will be equal to the right:
>>> x = 1
>>> x
1
In this example, we are assigning the x variable a number:
>>> x = x + 1
>>> x
2
While this may not make any sense whatsoever in math, it does make sense in programming. What we
have done is added 1 to the variable, making the right side equal to 2 and assigning 2 to x.
You can also assign one value to several variables:
>>> a = b = c = 4
>>> print a, b, c
4 4 4
Note this syntax error – this is because values cannot be assigned to literals.
>>> 3 = y
File "<stdin>", line 1
SyntaxError: can't assign to literal
Arithmetic Operators
These are the arithmetic operators in Python:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Floor division (//)
- Modulo (%)
- Power (**)
And these are the arithmetic operators in use in Python:
#!/usr/bin/python
# arithmetic.py
a = 10
b = 11
c = 12
add = a + b + c
sub = c - a
mult = a * b
div = c / 3
power = a ** 2
print add, sub, mult, div
print power
The division operator is a bit of a surprise because, usually, this will perform an integer division.
That means the result is an integer but, if you wanted a result that was a bit more exact, you would use
a floating point as an operand:
#!/usr/bin/python
# division.py
print 9 / 3
print 9 / 4
print 9 / 4.0
print 9 // 4.0
print 9 % 4
The floor division operator is used to find the floor of any value that is returned by true division:
print 9 % 4
The modulo operator will find the remainder when one number is divided by another. So, 9 % 4
equals 1 because 4 will go twice into 9 and leave 1 over.
Boolean Operators
There are three Boolean operators in Python – and, not, and or. These are used to perform logical
operations and are normally used with the reserved keywords, if and while:
#!/usr/bin/python
# andop.py
print True and True
print True and False
print False and True
print False and False
This is using the and operator which will evaluate true provided both of the operands are true.
The or operator will evaluate true only if one of the operands is true:
#!/usr/bin/python
# orop.py
print True or True
print True or False
print False or True
print False or False
We use the negation operator to make True into False and False into True
#!/usr/bin/python
# negation.py
print not False
print not True
print not ( 4 < 3 )
Relational Operators
We use relational operators when we want to compare values and these will always give a Boolean
value as a result. These are the relational operators:
Strictly less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)
Equal to (==)
Not equal to (!= or <>)
Object identity (is)
Negated object identity (is not)
This example shows them in use:
>>> 3 < 4
True
>>> 4 == 3
False
>>> 4 >= 3
True
Relational operators are not just used for numbers, but can also be used for other things, even though,
they may not always be terribly meaningful:
>>> "four" == "four"
True
>>> "a" > 4
True
>>> 'a' < 'b'
True
The basics of Python are found in all codes, ranging from basic to the more complicated code.
Practice these basics so that the more complicated parts make sense later on.
Thank You see You in the Next Chapter-Er. Gaurav Dixit
Tags:
python