Select Page

Programming in Python

Saving code to py file

So far you have been typing code directly in the Python console. You would have lost all the commands you wrote on you previous session. A better approach will be to save your code into a file with an extension of .py, so that you do not have to retype your program. To do this from the IDLE, click the File->New option and this will open a text editor, where you save, run and open recent py files.


A variable is a memory location with a name, where you store values, to be recalled later with the name. See the following boxes as memory location. You give a label to the first box as “a” and second box as “b” and assign values 3 and 5. Now you can recall the values in future calculations. In python, you can store a value of any datatype and you do not have to declare the datatype.

>>>print("Sum", a+b)
Sum 8
>>>print("Good", a)
Good Morning


The name you give for a variable, is called an Identifier. Identifiers can contain alpha-numeric characters and the underscore character. Identifier starts with an alphabetic character or an underscore. Also, you can not have a reserved Python keyword like ‘print’, ‘finally’, ‘if’

#Valid identifiers
#Invalid Identifiers
2_address="Main Street"


You can add comments to your python code, by prefixing with a hash character “#”

#get person name
name=input("Your name please")
print("Hello", name) #display name

Getting input
#get the user name and store it in variable
name=input("What is your name?")
print("Good Morning",name)
first_number=int(input('Enter first number: ');
second_number=int(input('Enter second number: ');
print('Sum', sum);

Data types

Common python datatypes: integer, string, boolean, float,list and set.

integer: Integer data type stores positive or negative numbers without any digits after the decimal place. Example: -5, 2, 1234334354.

string: String data type stores a sequence of characters called string. You have to enclose a string value with a  double quote (most common)  or single quote. Example:  “Jacob” ‘Kristy’.

boolean: Boolean data type can store logical values True or False. Example: end_reached=True. This you will use in conditional statements.

float: This datatype can store fractional values after the decimal place. Example. weight=23.5 cost=9.99

list: Lists  store multiple values of same datatype and identified by an index. Example: fruits=[“apple”, “orange”, “apple”]. names[0] is “apple”, names[1] is “Orange”, names[2] is “apple”

set: Sets are similar to list, except they do not allow duplicate values and the curly braces are used. Example: names={“Kim”, “John”, “Sue”}

#convert from string to integer
#input statement always returns a string
str=input("Please enter the first number:")
#to do calculations, we need to convert to integer, using the int function
str=input("Please enter the second number:")

#convert from integer to string

Arithmetic Operators and Expressions

Common arithmetic operators in Python: +, -, *, /, %.

The division operator always return a float value. Example 4/2 return 2.0, 5/2 is 2.5. The modulo operator is % and it gives the reminder of dividing two numbers. Example 5%2 is 1, 9%3 is 0.  There is another floor operator // that gives only the integer part of a float value. Example 5//2 is 2, 8.5/2 is 4.


print(c)#prints 18
print(a-b) #prints 12
print(a/b) #prints 5
print(a%b) #prints 0
print(c%4) #prints 2
print(c//5) #prints 3
#parenthesis can be used to change the order of precedence
print(d) #prints 16
d=(a+b)/3 #any expression inside a parenthesis will be evaluated first.
print(d) #prints 6 

#Counting increment a number by 1
print(i) #prints 1
print(i) #prints 2
i+=1 #same as i=i+1
print(i) #prints 3
i-=1 #same as i=i-1
print(i) #prints 2
print(i) #prints 0
#plus operate concatenates (adds) two strings
#str() function converts from int to string 
message="Your child's age is "+str(age)

animal1="Bull Dog"
print(len(animal1)) #prints 8 as there are 8 chars in Bull Dog.
print(animal2)#prints PANTHER
print(animal3) #prints elephant
print(animal1.strip()) #prints BullDog removes the space.

Logical Expressions

Logical expressions evaluates to True or False. They help in decision making. They will be used in “if” statement

print(a>b) #prints True
print(a<b) #prints False
print(a==9) #True
print(a!=9) #!= is not equals and is False
print(a!=b) #True

If Statement

“If” statement helps you to branch the logic, by evaluating an logical expression

speed=int(input("Enter your speed:"))
if speed>75:
   print("SLOW DOWN! You are sure to get a ticket"
   print("You are a good driver.");


As the name suggests, a list stores a collection of similar data types. List allow duplicate values.

fruits = ['orange', 'apple', 'pear', 'apple', 'banana']
#adds 'kiwi' to the end of the list
print(len(fruits)) #prints 6 which is count of the list.
print(fruits[0]) #prints orange
print(frouts[3]) #prints apple
fruits.sort() #sorts the list in ascending order


Set is similar to list, but does not allow duplicate values.

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket# fast membership testing
>>> 'crabgrass' in basket

Generate random numbers

You can import libraries with import statement

import random
print(random.randint(1,6) #Generates a random number in between  1 and 6


  1. Write a program to convert temperate in Celsius (Centigrade) to Fahrenheit. Get the temperature in Celsius as input and display the Fahrenheit value of it. Formula to use: T(°F)=T(°C) × 1.8 + 32.
  2. Get a number from user. Print if it is an odd number or even number.
  3. Write a program to print the grade (A, B, C) from the percentage of marks entered.