The two basic building blocks of programming are code and data.
Code is a set of instructions that tell the computer what operations to perform and how it should perform.
Data refers to the quantities, characters, and/or symbols on which operations are performed with a computer.
Simple examples of data include the number of students in class, grade point average, name, whether a switch is in an on or off position, and so on.
2 Types of Data
There are many different types of data, but in this course we will deal with four basic types of data.
The four basic types of data are called integer numbers, floating-point numbers, strings, and Booleans.
2.1 Integers
Integer numbers (or simply, integers) are counting numbers, like 1, 2, 3, but also include 0 and negative numbers.
The following are examples of data that is expressed as integers:
Number of people in a room
Personal or team score in a game
Course number
Date in a month
Temperature (in terms of number of degrees)
Examples
12, 50, 0, -3, -25
Integers are represented in Python by int Data Type.
2.2 Floats
Floating-point numbers (or simply floats) are numbers that have a decimal point in them.
The following are examples of data that is expressed as floating-point numbers:
Grade point average
Price of something
Percentages
Irrational numbers, like pi
Example
1.5, .5, -3.21, 1.0, 0.0
Floating-Point numbers are represented in Python by float Data Type.
Is it an Integer or a Floating point?
It might seem that integer and floating-point data have overlaps.
For example:
there is an integer 0 and there is a floating-point 0.0,
there is an integer 1 and a floating-point 1.0.
Although these may appear to be the same thing to us humans, Python makes a clear distinction between these two types of data.
2.3 Strings
Strings (also called text) are any sequences of characters. Examples of data that is expressed as strings include the following:
Name
Address
Course name
Title of a book, song, or movie
Sentence
Name of a file on a computer
Examples
‘Joe’, ‘Schmoe’, “Joe”, “Schmoe”, ‘This is some string data’, “OK”
In Python as in other programming languages Strings are always used within quotes – “Embark” or ‘Embark’.
Types of Quotes to Use
The string ‘Joe’ and the string “Joe” are exactly the same.
The quotes are not actually part of the string.
They are there to allow Python to understand that you are talking about a string.
You can choose to use either pair of quoting characters.
Single quotes are generally easier to use because you don’t have to hold down the Shift key to type them.
Using a Quote Character inside a String
If you want to include a quote character inside a string, you can enclose the string in the other quote characters.
For example, you might write this:
“Here’s a string with a single quote in it”
Or this:
‘Here is a string that includes two “double quote” symbols inside of it’
Strings are represented in Python by str Data Type.
2.4 Booleans
Booleans are a type of data that can only have one of two values: True or False.
The words True and False must be spelled with this capitalization:
True
False
Booleans are named after the English mathematician George Boole, who created an entire field of logic based on these two-state data items.
The following are some examples of data that can be expressed as Booleans:
The state of a light switch: True for on, False for off
Inside or outside: True for inside, False for outside
Whether someone is alive or not: True for alive, False for dead
If someone is listening: True for listening, False for not listening
Booleans are represented in Python by bool Data Type.
3 Creating and Giving a Value to a Variable
3.1 Variable
In programming, we need to store and manipulate data all the time. In order to store and manipulate data, we use a variable. Think of a variable as an envelope or a box into which you can put a value. So a variable is a container—a storage space—with a name.
The contents of a variable can change or vary over time; this is why it’s called a variable. But the name of a variable never changes.
Variable - A Memory Location
Practically a variable is a named memory location that holds a value.
Think of RAM (Random Access Memory) in your computer as a simple list or array of numbered slots, starting at 0 and going up to as much memory as you in your computer.
Every one of these memory locations can be used as a variable. That is, you can store a piece of data in any free memory slot.
Practically different types of data (integer, float, string, and Boolean) take up different amounts of memory, rather than a single “slot”.
3.2 Assignment Statements
In Python, you create and give a value to a variable with an assignment statement. An assignment statement is a line of code in which a variable is given a value.
An assignment statement has this general form:
Syntax
=
Anything written like <variable> and <expression> is a placeholder – it means that you should replace that whole thing (including the brackets) with something that you choose.
In pure computer programming terms, the equals sign is not called “equals,” it is called the assignment operator.
The value on the right side of the equals sign is assigned to the variable on the left.
EX1
age = 29
name = 'Fred'
alive = True
gpa = 3.9
3.3 Expressions with Variables
The expression on the right-hand side can also contain variables. Whenever a variable appears in an expression (that is, on the right-hand side of an assignment statement), the expression is evaluated (computed) by using the value of each variable.
It works like this: everything on the right side of the equals sign, is evaluated, and a value is computed.
The resulting value is assigned to (put into) the variable on the left.
The equals sign in an assignment statement is very different from the way an equals sign is used in math.
In math, the equals sign implies that the things on the left side and the right side have the same value.
In python it is used to assign the evaluated value on the right hand side to the variable written on the left hand side.
EX4
myAge = 25
myAge = myAge + 1 # the value of myAge will now be 26
EX5
myAge = 31
yourAge = myAge
print(yourAge) # evaluates to 31 since the value of myAge has been assigned to yourAge
We can assign a value to multiple variables using:
EX6
a = b = c = 5 # All a, b and c have the value 5
We can also assign different values to multiple variables in a single statement:
EX7
a, b, c, d = 1, 2, 3, 4 # a is 1, b is 2, c is 3 and d is 4
3.4 Reassigning Value to a Variable
Through an assignment statement when you try to assign a value to a variable Python first looks to see whether the variable to be assigned was previously used.
If the variable has never been seen before, Python allocates an empty slot of memory, attaches a name to it, and puts in the given value.
But if it finds that there already is a variable with the same name, rather than create a new variable, Python overwrites the current value of the variable with the new value.
Therefore, when you entered age = 29 and pressed Return or Enter, Python first looked to see if it had ever seen the variable name age before.
Since it had not, it allocated a memory slot somewhere (again, we don’t care where) attached the age label to it, and then put the value 29 into that memory slot.
A similar sequence happened for the other variables.
After executing that line, enter the following line and press Return or Enter:
age = 31
Python does the same sequence of steps, but now it finds that there already is a variable named age.
Rather than create a new variable, Python overwrites the current value of the variable age with the new value of 31.
The variable name age stays the same, but the contents change.
EX8
a = 100
...
a = 25
...
a = 50
# a will be equal to 50
4 Print Statements
Before we proceed further it makes sense to learn about Print statements in Python.
Print statement is used to print whatever you want to see.
The general print statement looks like this:
Syntax
print()
This <whatever you want to see> can be a text string or it can be the result of a calculated expression.
EX9
print('Hello World')
Hello World
EX10
print(101)
101
Try Yourself 1
Print the following line using the print statement:
Hi, learning Python with PyStrike is fun.
Solution
print("Hi, learning Python with PyStrike is fun.")
Hi, learning Python with PyStrike is fun.
4.1 Printing a Variable's Value
EX11
eggsInOmlette = 3
print(eggsInOmlette)
3
EX12
knowsHowToCook = True
print(knowsHowToCook)
True
Try Yourself 2
Store a value of 311 in a variable and print the same using print statement.
Solution
a = 311
print(a)
311
4.2 Printing multiple things on a single line
The print statement can also print multiple things on a single line.
You can do this by separating the items you want to print with commas.
When the print statement runs, each comma is replaced by a space.
numberInADozen = 12
print('There are', numberInADozen, 'items in a dozen')
There are 12 items in a dozen
Try Yourself 3
Store a value of 311 in a variable and use the variable to print the following line:
My House Number is 311.
Solution
a = 311
print("My House Number is",a)
My House Number is 311
4.3 Printing one or more blank lines
To make things a little clearer in your output, you may want to include one or more blank lines.
To create a blank line of output, you can use an empty print statement – just write the word print with a set of open and close parentheses.
print()
Try Yourself 4
Print the following statements: My House Number is 311.
I live in United States of America.
Solution
print("My House Number is 311")
print ()
print("I live in United States of America")
My House Number is 311
I live in United States of America
5 Swapping Values of Variables
You can swap the values of two variables by writing a simple assignment statement.
Let’s suppose we have two variables a and b.
We can swap their values with
a, b = b, a
It means if the value of a is 5 and b is 10, then the value of a will become 10 and b will become 5 after swapping.
EX15
a = 5
b = 10
a, b = b, a
print(a) # prints 10
print(b) # prints 5
Try Yourself 5
Store two values in x and y and swap them.
x = 10
y = 20
Solution
x=10
y=20
x,y = y,x
print(x)
print(y)
20
10
6 Deleting Variables
We can delete a variable using del in Python.
EX16
a = 5
print(a) # prints a
del a # a is deleted
print(a) # Gives error
NameError: name 'a' is not defined on line 7
7 ID of a Variable
The “id” or “identity” of a variable is a unique value which is associated with the variable. The id of a variable is constant and unique over the life of that variable. Two variables may have same ids if they don’t exist together i.e., their lifetime don’t overlap each other. We can access id of a variable using id function.
EX17
a = 5
b = 9
print(id(a))
print(id(b))
1
2
8 Variable Names
By definition, every variable must have a name also called indentifier.
Python doesn’t care what you use for a variable name. But it is best to make variable names as descriptive as possible.
In Python (and all computer languages), there are some rules about naming a variable, though. Here are Python’s rules about the name of a variable:
Must start with a letter (or an underscore)
Cannot start with a digit
Can have up to 256 total characters
Can include letters, digits, underscores, dollar signs, and other characters
Cannot contain spaces
Cannot contain math symbols (+, -, /, *, %, parentheses)
Here are some examples of illegal names:
49ers (starts with a digit)
table+chairs (contains a plus sign)
my age (contains a space)
(coins) (uses parentheses)
8.1 Naming Conventions
A convention is an agreed-upon way of doing things.
In programming, you can create any variable name you want as long as it follows the rules.
However, when creating variable names, it is strongly suggested that you use a naming convention i.e. a consistent approach for creating names for variables.
A. For one word:
The convention is to use all lowercase letters.
B. For putting together two or more words:
1. camelcase convention
First word – all lowercase.
Every additional word – Make the first letter uppercase; All other letters lowercase.
Here are some examples of variable names that follow the camelcase naming convention:
someVariableName
anotherVariableName
countOfBadGuys
computerScore
humanScore
bonusPointsForCollectingMushrooms
The term camelcase describes the way variable names look when using this convention.
When an uppercase letter starts a new word, it looks like the hump on a camel.
2. underscore convention
Separate words with underscores.
Here are some examples of variable names that follow the underscore naming convention:
this_is_a_variable_name
number_of_fish_in_aquarium
Avoid putting underscore (_) or double underscore (__) at the start and end of identifier names, because these have some special meaning in Python.
If you are coding on your own, obviously you can use whatever names you want, but it really is a good idea to be consistent when naming variables.
Remember, this is the general form of an assignment statement:
=
The expression on the right-hand side can also contain variables.
myAge = 31
yourAge = myAge
print(yourAge) # evaluates to 31 since the value of myAge has been assigned to yourAge
31
>>> myAge = 31
>>> yourAge = myAge
>>>
Whenever a variable appears in an expression (that is, on the right-hand side of an assignment statement), the expression is evaluated (computed) by using the value of each variable.
The equals sign in an assignment statement is very different from the way an equals sign is used in math.
In math, the equals sign implies that the things on the left side and the right side have the same value.
In python it is used to assign the evaluated value on the right hand side to the variable written on the left hand side.
myAge = 25
myAge = myAge + 1 # the value of myAge will now be 26
>>> myAge = 25
>>> myAge = myAge + 1
>>>
9 Keywords
When the Python compiler reads your code, it looks for special words called keywords to understand what your code is trying to say.
Note Python technically has an interpreter that turns your code into a machine independent byte code. But to make things simple, we’ll refer to this as the Python compiler.
The following is a list of the Python keywords.
and
as
assert
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield
False
None
True
Remember You cannot use Python keywords as a variable name. If you attempt to do so, the Python compiler will generate an error message when it tries to compile your program.
We know that computers only understand ones and zeros.
When you write code in Python, Python cannot run or execute your code directly.
Instead, it takes the code that you write and compiles it.
That is, Python converts your code into a language of ones and zeros that the computer can understand.
Every language has such a compiler.
When the Python compiler reads your code, it looks for special words called keywords to understand what your code is trying to say.
Python technically has an interpreter that turns your code into a machine independent byte code.
But to make things simple, we’ll refer to this as the Python compiler.
10 Math Operators
In Python the following math operators can be used in assignment statements:
+ Add – If operands are number, adds them; If operands are strings, joins them
– Subtract – Subtracts two numbers
* Multiply – Multiply two numbers
/ Divide – Divides two numbers and returns a float
// Integer Divide – Divides two numbers and returns an integer (floor value if not perfectly divisible)
** Raise to the power of – Left operand raised to the power of right operand
ageInMonths = 29
years = ageInMonths // 12
months = ageInMonths % 12
print("My puppy's age is", years, "years and", months, "months.")
My puppy's age is 2 years and 5 months.
>>> ageInMonths = 29
>>> years = ageInMonths // 12
>>> months = ageInMonths % 12
>>> print("My puppy's age is", years, "years and", months, "months.")
My puppy's age is 2 years and 5 months.
>>>
Try Yourself 6
Store three integers in x, y and z. Print their product.
x=5
y=10
z=20
Solution
x=5
y=10
z=20
print(x*y*z)
1000
Try Yourself 7
Write a program to add, subtract, multiply and divide two numbers.
a = 3
b = 5
Solution
a = 3
b = 5
ans1 = a + b
ans2 = a - b
ans3 = a * b
ans4 = a / b
print(ans1)
print(ans2)
print(ans3)
print(ans4)
8
-2
15
0.6
Try Yourself 8
Let’s assume
a = 4
b = 5.
Display the value of the b raised to the power of a.
Solution
a = 4
b =5
ans = a ** b
print(ans)
1024
Try Yourself 6
Principal = 1000
Rate of Interest = 5%
Time Period = 3 years
Write a program to calculate Simple Interest and Total Amount including interest.
Simple Interest is calculated using the following formula:
SI = P × R × T
where, P = Principal, R = Rate of Interest, and T = Time period.
Solution
p = 1000
r = 5
t = 3
simple_interest = (p*r*t)/100
total_amount = p + simple_interest
print("Simple Interest:",simple_interest)
print("Total amount:", total_amount)
Simple Interest: 150.0
Total amount: 1150.0
Try Yourself 7
a = 2
b = 3
Calculate the sum of cubes of these two numbers.
Solution
a = 2
b = 3
result = (a**3) + (b**3)
print(result)
35
Try Yourself 8
Length = 10
Breadth = 20
Write a program to print area and perimeter of a rectangle.
Area = Length X Breadth
Perimeter = 2 X (Length + Breadth)
Solution
length = 10
breadth = 20
area = length * breadth
perimeter = 2 * (length + breadth)
print("The area of Rectangle is", area)
print("The perimeter of Rectangle is", perimeter)
The area of Rectangle is 200
The perimeter of Rectangle is 60
Try Yourself 12
a = 1234
Calculate the sum of digits of this number.
Solution
number = 1234
first_digit = number%10
number = number//10
second_digit = number%10
number = number//10
third_digit = number%10
number = number//10
fourth_digit = number
sum_of_digits = first_digit + second_digit + third_digit + fourth_digit
print(first_digit, second_digit, third_digit, fourth_digit)
print("Sum is", sum_of_digits)
4 3 2 1
Sum is 10
10.5 Precedence of Operators
If more than two operators are present in an expression, the expression inside parentheses () are evaluated first. After that, the following table is followed:
The operator at the top has the highest precedence (priority) and that at the bottom has the least precedence (priority).
Operator
Associativity
**
Right to Left
*, @, /, //, %
Left to Right
+, –
Left to Right
in, not in, is, is not, <, <=, >, >=, !=, ==
Left to Right
not
Right to Left
and
Left to Right
or
Left to Right
=, +=, -=, *=, /=, //=, %=
Right to Left
In the case of operators having the same precedence, the evaluation will happen in the direction of their associativity.
For example
In the expression, 5*2/3, * and / have the same precedence and their associativity is from left to right. So, 5*2 will be evaluated first as it is the leftmost and then 10/3 (5*2 is 10) will be evaluated.
Alternatively use parentheses to group operations.
Using parentheses allows you to “force” the order of operations so that the steps happen in whatever order you want.
When you have nested sets of parentheses, the only rule you need to know is that sets of parentheses are evaluated from the innermost set to the outmost set.
x = 5 + ((4 * 9) / 6)
(4 * 9) is evaluated first, that result is then divided by 6, and then 5 is added to that result.
Creating & Executinga Python file
Start by opening a new Python editor window [Control+N (Windows) or Command+N (Mac), or File ➤ New].
Enter the following lines of code in the newly opened file:
Write a program to print a new number with digits reversed as of orignal one. E.g.-
INPUT : 1234 OUTPUT : 4321
Solution
number = 1234
#seperating digits of the number #1234/1000 = 1
#1234%1000 = 234
first_number = number//1000
rem = number%1000
#234/100 = 2
#234%100 = 34
second_number = rem//100
rem = rem%100
#34/10 = 3
#34%10 = 4
third_number = rem//10
fourth_number = rem%10
#creating new number with digits reversed
#1234 = (1*1000)+(2*100)+(3*10)+4 i.e., 1000+200+30+4
new_number = (fourth_number*1000)+(third_number*100)+(second_number*10)+(first_number)
print(new_number)
4321
Problem 5
first number = 7
second number = 2
Use whole number division to divide the first number by the second and also work out the remainder and display the answer in a user-friendly way (“7 divided by 2 is 3 with 1 remaining”).
Each line or command we write in Python is a statement.
EX25
print("Hello World")
print("PyStrike")
In this code, we have two statements – print(“Hello World”) and print(“PyStrike”).
11.1 Statements in Multiple Lines using \
Whenever the line gets too long to read, you can add a backslash character (\) at a logical breaking point to indicate that the line should continue to the next line.
EX26
a = 1 + 2 + 3\
+ 4 + 5 + 6\
+ 7 + 8 + 9
print(a)
11.2 Statements in Multiple Lines using ( )
Instead of using \, we can also write a statement in multiple lines if we write our expression inside ().
If we need to write multiple statements in a single line, we can do so by using a semi-colon (;) after every statement.
Note: This practice is not generally followed by Python programmers and hence is not recommended.
EX28
a = 5; b = 6; print(a)
print(b)
12 Adding Comments
Sometimes you may want to add some comments to your code to explain the approach adopted by you.
Documentation like that, written directly in your code, is called a comment.
Comments are completely ignored by Python; they are only there for humans.
There are three ways to write comments in Python:
provide a full-line comment,
add a comment after a line of code, or
use a multiline comment.
12.1 Full-line Comment
Start a line with the # character, followed by your comment.
When you type the # symbol all characters after it turn red. This is IDLE recognizing that you are typing a comment.
This is IDLE recognizing that you are typing a comment.
EX29
# This whole line is a comment
# This is another comment line
# All comment lines are ignored by Python
# Even though the next line looks like code, it's just a comment
# x = 1
# -------------------------------------
Try Yourself 10
Add a full line comment “This is a comment” to the earlier statement written in multiple lines.
Solution
a = 24 + 46\
+ 54 + 63\
+ 87 + 98
print(a)
# This is a comment
b = (24 + 46
+ 54 + 63
+ 87 + 98)
print(b)
12.2 Adding a comment after a line of code
Using # symbol you can put a comment at the end of a line of code to explain what is going on inside that line.
EX30
score = 0 # Initializing the score
priceWithTax = price * 1.09 # add in 9% tax
Try Yourself 11
Write a comment at the end of a line of code written earlier.
Solution
a = 24 + 46\
+ 54 + 63\
+ 87 + 98
print(a) # This will print value of variable a
b = (24 + 46
+ 54 + 63
+ 87 + 98)
print(b) # This will print value of variable b
12.3 Mulit-line Comment
You can create a comment that spans any number of lines by making one line with three quote marks (single or double quotes), writing any number of comment lines, and ending with the same three quote characters (single or double quotes) on the last line.
EX31
'''
A multiline comment starts with a line of three quote characters (above)
This is a long comment block
It can be any length
You do not need to use the # character here
You end it by entering the same three quotes you used to start (below)
'''
Try Yourself 12
Write a multi-line comment in the code written earlier.
Solution
a = 24 + 46\
+ 54 + 63\
+ 87 + 98
print(a)
b = (24 + 46
+ 54 + 63
+ 87 + 98)
print(b)
'''
Calculated Values of
variables a and b
are printed through this code
'''
Alternatively, to comment out a block of lines, first select all the lines that you want to comment out.
You can click at a beginning point in your code and drag across the lines you want to comment out, or you can click at the beginning point and Shift-click at the ending point.
Then go to the Format menu and choose Comment Out Region. (For some reason, IDLE adds two pound-sign characters (##) when doing this, but that works fine.)
Later, if you decide that you want to uncomment a block, select the region the same way, go to the Format menu, and choose Uncomment Region.
13 Whitespace
Python ignores all invisible characters.
The extra space is an invisible character called whitespace, which is ignored by the Python compiler.
You can add as many space characters as you want in between items on a line.
You can also add blank lines anywhere you want in Python.
When files get long, added blank lines can aid in readability.
Most programmers put spaces around math operators as another convention.
EX32
myVariable = var1 + var2 #space on either side of equals and plus