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.

 Variables

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.

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

Identifier

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
name="John"
last_name="Smith"
_name="Sue"
#Invalid Identifiers
finally=3
2_address="Main Street"

 Comment

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

#hello.py
#get the user name and store it in variable
name=input("What is your name?")
print("Good Morning",name)

#add.py
first_number=int(input('Enter first number: ');
second_number=int(input('Enter second number: ');
sum=first_number+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
x=int("3")
#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
x=int(str)
str=input("Please enter the second number:")
y=int(str)
sum=x+y
print("Sum",sum)

#convert from integer to string
x=3
str_x=str(x)

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.

 

a=15
b=3
c=a+b
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
d=a+b/3
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
i=1
print(i) #prints 1
i=i+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
i-=2
print(i) #prints 0
String
age=12
#plus operate concatenates (adds) two strings
#str() function converts from int to string 
message="Your child's age is "+str(age)

animal1="Bull Dog"
animal2="Panther"
animal3="Elephant"
print(len(animal1)) #prints 8 as there are 8 chars in Bull Dog.
animal2=animal2.upper()
print(animal2)#prints PANTHER
animal3=animal3.lower()
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

a=9
b=3
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"
else:
   print("You are a good driver.");



List

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
fruits.append('kiwi')
print(fruits)
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
fruits.pop()

Set

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
True
>>> 'crabgrass' in basket
False

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

Exercise

  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.

Reference

https://docs.python.org/3/tutorial/introduction.html