You are on page 1of 6

BeyondPapers Workshop 1.

0 (Launch into Python Programming)

Handling Different Data Types: Going


Mathematical in Python

Getting Data
Most of the times, programmers see the need to get inputs from users, for
further processing or use in program. The input method solves this riddle. It
prompts the user to enter data, one ‘bit’ at a time, reads it and returns it as a
value in a string data type.
The print("Computer's Message: ") syntax communicates with the user, extracts
data from the user, and assigns the data as a value to a variable. For example:

x = input("Enter your age: ")


print(x)

Seen the magic? Now let’s use it more practically:

# Code to calculate a user's age


CurentYear = input("Hello! My name is Agewitch. Can you please help me out
with the current year?: ")
print("Your age is:", CurentYear - input("Please let me know your Date-of-Birth:
"))

It gave an error, right? Defintely! We failed to convert the string-typed inputs into
mathematical data-types – numbers!

# Code to calculate a user's age


CurentYear = int(input("Hello! My name is Agewitch. Can you please help me out
with the current year?: "))
print("Your age is", CurentYear – int(input("Please let me know your Date-of-
Birth: ")))

That was too complex, right? Now let’s break it down:

# Code to calculate a user's age

1 |B e y o n d P ap e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

CurentYear = input("Hello! My name is Agewitch. Can you please help me out


with the current year?: ") # Asks the user for the current year.
DOB = input("Please let me know your Date-of-Birth: ") # Ask the user for his
Date-of-Birth.
Age = int(CurentYear) - int(DOB) # Converts each variable to integer, and
calculates the user's age.
print("Your age is", Age) # Prints the user's age.

Random Numbers
You can generate random numbers using the random built-in module. All you
have to do is to import the random module, and add some junks of parameters to
your code:

import random # Imports the random module, as Python does not have the
random() function.
x = random.randrange(0,100) # Returns any number between 0 and 99
print(x)

In application:

# This code was written by Professor Ajay of the Music department, FUTA. He
could not conduct an examination for his Music students, and would now use the
students’ attendance (40%), coupled with a random exam score (60%). He is
strict, but would never fail his students, so all random numbers to be used must
be at least half of 60%, and must never be up to 60%

import random
attend = input("""Prof. Ajay: We had just 4 classes this semester, right?
Student: Of course, Prof.
Prof. Ajay: How many of them did you attend?
Student: """)
attendance = int(attend) * 10 # Multiplies attend by 10. Each class carries 10
marks!
rand = random.uniform(0.5,1.0) # Returns any random number between 0.5 and
0.99999999... but never 1.0

2 |B e y o n d P ap e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

score = attendance + rand * 60 # Multiples rand by 60, to give a random number


between 30 and 59.99.. but never 60, and then adds the result to attendance.
print("Prof. Ajay: Your score in MSC201 is %.1f. Congrats!" %score) # Produces a
float number rounded to 1 decimal place, as indicated by %.1f

Python Operators
Python operators are used to perform mathematical operations on variables and
values. They are similar to mathematical operators (+, -, ÷, x, =, Λ, ε, C, ~ etc). The
values or variables to be computed are called operands.

There are seven (7) groups of Operators in Python.

 Arithmetic Operators
These are the most common operators used in mathematical operations.
Division uses /, while // performs division, and then rounds the result down to
the lowest nearest integer. E.g 2.9//1 is 2.0. Use ** for power, and % for
finding division remainders, just like in Modular Arithmetics. For instance:

a=5
b=2

print(a + b) # Prints 7 (Addition)


print(a - b) # Prints 3 (Subtraction)
print(a * b) # Prints 10 (Multiplication)
print(a / b) # Prints 2.5 (Division)
print(a // b) # Prints 2 (Floor Division: rounds down the quotient to an integer)
print(a % b) # Prints 1 (Modulus/Division remainder)
print(a ** b) # Prints 25 (Exponentiation/Power)

 Assignment Operators
These are used to assign values to variables. a = 2 assigns 2 to the variable a. x
+= 1 performs x = x + 1. It calls for the former value of x (say 2), adds 1 to it,
and then assigns the result (3) to x again. Assignment operators include +=, -=,
/=, **=, |=, ^=, >>=, <<= etc.

a=5
3 |B e y o n d P ap e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

a += 1
print(a) # Prints 6

b=5
b -= 2
print(b) # Prints 3

c=2
c *= 3
print(c) # Prints 6

 Comparison Operators
These operators perform checks on two operands (values or variables) and
return a boolean (True or False), depending on the validity of the argument. x
== y, for example, checks if x is equal to y, and returns True or False.

a = 10
b=5
c=7
d = 10

print(a > b) # Prints True (greater than)


print(b <= c-2) # Prints True (less than or equal to)
print(a != d) # Print False (not equal to)
print(5 > 4) # Prints True

 Logical Operators
Logical operators work like the Truth table. It includes and, or and not. Using
the and operator, when the two statements to be compared are True, returns
True.

Truth Table for and


X Y x and y
True True True
True False False
False True False
False False False

4 |B e y o n d P ap e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

Truth Table for or


X Y x or y
True True True
True False True
False True True
False False False

a=5

print(a<6 and a>4) # Prints True


print(a<10 or a==5) # Prints True
print(not(a<6 and a>4)) # Prints False
print(not True) # Prints False

 Identity Operators
Identity operators are used to check if two operands are identical, that is
located on the same memory location. They return a boolean. It includes is
and is not.

a=3
b=3
print(a is b) # Prints True

a = "BeyondPapers"
b = "BeyondPapers"
print(a is not b) # Prints False

a = ["Red","Green","Blue"]
b = ["Red","Green","Blue"]
print(a is b) # Prints False. The two lists are equal but not on the same memory
location. Hence they are not identical.

 Membership Operators
These are used to check whether an operand is in a string, list, set, tuple or
dictionary. It works just like the "is an element of" (ε) statement in Set Theory.
(In Maths, x ε y). It includes in and not in.

5 |B e y o n d P ap e r s
BeyondPapers Workshop 1.0 (Launch into Python Programming)

fruits = {"apple", "banana", "cashew", "grape"}

print("apple" in fruits) # Prints True


print("grape" not in fruits) # Prints False

word = "BeyondPapers"
print("y" in word) # Prints True
print(word in "y") # Prints False. "BeyondPapers" is not found in "y".

 Bitwise operators
Bitwise operators are used to 'mutilate' operands in the binary state. It
converts a number to binary, and then treats it like a string of True and False
values (1 and 0), where it deals with the string bit by bit. It uses the Truth
Table system too. It includes & (for AND), | (for OR), ^ (for XOR), ~ (for NOT),
>>, and <<.

x=1
y=1
print(x & y) # Prints 1
print(x | y) # Prints 1

a=1
b=0
print(a & b) # Prints 0
print(a | b) # Prints 1

p=0
q=0
print(p & q) # Prints 0
print(p | q) # Prints 0

 You can learn more about operators on:


 http://www.w3schools.com/python/python_operators.asp
 https://www.programiz.com/python-programming/operators

6 |B e y o n d P ap e r s

You might also like